code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
<?php
namespace TYPO3\Neos\Routing;
/*
* This file is part of the TYPO3.Neos package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use TYPO3\Flow\Annotations as Flow;
/**
* A route part handler for finding nodes specifically in the website's frontend.
*
* @Flow\Scope("singleton")
*/
class BackendModuleArgumentsRoutePartHandler extends \TYPO3\Flow\Mvc\Routing\DynamicRoutePart
{
/**
* @Flow\Inject
* @var \TYPO3\Flow\Persistence\PersistenceManagerInterface
*/
protected $persistenceManager;
/**
* Iterate through the configured modules, find the matching module and set
* the route path accordingly
*
* @param array $value (contains action, controller and package of the module controller)
* @return boolean
*/
protected function resolveValue($value)
{
if (is_array($value)) {
$this->value = isset($value['@action']) && $value['@action'] !== 'index' ? $value['@action'] : '';
if ($this->value !== '' && isset($value['@format'])) {
$this->value .= '.' . $value['@format'];
}
$exceedingArguments = array();
foreach ($value as $argumentKey => $argumentValue) {
if (substr($argumentKey, 0, 1) !== '@' && substr($argumentKey, 0, 2) !== '__') {
$exceedingArguments[$argumentKey] = $argumentValue;
}
}
if ($exceedingArguments !== array()) {
$exceedingArguments = \TYPO3\Flow\Utility\Arrays::removeEmptyElementsRecursively($exceedingArguments);
$exceedingArguments = $this->persistenceManager->convertObjectsToIdentityArrays($exceedingArguments);
$queryString = http_build_query(array($this->name => $exceedingArguments), null, '&');
if ($queryString !== '') {
$this->value .= '?' . $queryString;
}
}
}
return true;
}
}
| Java |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "meshSearch.H"
#include "polyMesh.H"
#include "indexedOctree.H"
#include "DynamicList.H"
#include "demandDrivenData.H"
#include "treeDataCell.H"
#include "treeDataFace.H"
#include "treeDataPoint.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
defineTypeNameAndDebug(Foam::meshSearch, 0);
Foam::scalar Foam::meshSearch::tol_ = 1E-3;
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
bool Foam::meshSearch::findNearer
(
const point& sample,
const pointField& points,
label& nearestI,
scalar& nearestDistSqr
)
{
bool nearer = false;
forAll(points, pointI)
{
scalar distSqr = magSqr(points[pointI] - sample);
if (distSqr < nearestDistSqr)
{
nearestDistSqr = distSqr;
nearestI = pointI;
nearer = true;
}
}
return nearer;
}
bool Foam::meshSearch::findNearer
(
const point& sample,
const pointField& points,
const labelList& indices,
label& nearestI,
scalar& nearestDistSqr
)
{
bool nearer = false;
forAll(indices, i)
{
label pointI = indices[i];
scalar distSqr = magSqr(points[pointI] - sample);
if (distSqr < nearestDistSqr)
{
nearestDistSqr = distSqr;
nearestI = pointI;
nearer = true;
}
}
return nearer;
}
// tree based searching
Foam::label Foam::meshSearch::findNearestCellTree(const point& location) const
{
const indexedOctree<treeDataPoint>& tree = cellCentreTree();
scalar span = tree.bb().mag();
pointIndexHit info = tree.findNearest(location, Foam::sqr(span));
if (!info.hit())
{
info = tree.findNearest(location, Foam::sqr(GREAT));
}
return info.index();
}
// linear searching
Foam::label Foam::meshSearch::findNearestCellLinear(const point& location) const
{
const vectorField& centres = mesh_.cellCentres();
label nearestIndex = 0;
scalar minProximity = magSqr(centres[nearestIndex] - location);
findNearer
(
location,
centres,
nearestIndex,
minProximity
);
return nearestIndex;
}
// walking from seed
Foam::label Foam::meshSearch::findNearestCellWalk
(
const point& location,
const label seedCellI
) const
{
if (seedCellI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestCellWalk(const point&, const label)"
) << "illegal seedCell:" << seedCellI << exit(FatalError);
}
// Walk in direction of face that decreases distance
label curCellI = seedCellI;
scalar distanceSqr = magSqr(mesh_.cellCentres()[curCellI] - location);
bool closer;
do
{
// Try neighbours of curCellI
closer = findNearer
(
location,
mesh_.cellCentres(),
mesh_.cellCells()[curCellI],
curCellI,
distanceSqr
);
} while (closer);
return curCellI;
}
// tree based searching
Foam::label Foam::meshSearch::findNearestFaceTree(const point& location) const
{
// Search nearest cell centre.
const indexedOctree<treeDataPoint>& tree = cellCentreTree();
scalar span = tree.bb().mag();
// Search with decent span
pointIndexHit info = tree.findNearest(location, Foam::sqr(span));
if (!info.hit())
{
// Search with desparate span
info = tree.findNearest(location, Foam::sqr(GREAT));
}
// Now check any of the faces of the nearest cell
const vectorField& centres = mesh_.faceCentres();
const cell& ownFaces = mesh_.cells()[info.index()];
label nearestFaceI = ownFaces[0];
scalar minProximity = magSqr(centres[nearestFaceI] - location);
findNearer
(
location,
centres,
ownFaces,
nearestFaceI,
minProximity
);
return nearestFaceI;
}
// linear searching
Foam::label Foam::meshSearch::findNearestFaceLinear(const point& location) const
{
const vectorField& centres = mesh_.faceCentres();
label nearestFaceI = 0;
scalar minProximity = magSqr(centres[nearestFaceI] - location);
findNearer
(
location,
centres,
nearestFaceI,
minProximity
);
return nearestFaceI;
}
// walking from seed
Foam::label Foam::meshSearch::findNearestFaceWalk
(
const point& location,
const label seedFaceI
) const
{
if (seedFaceI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestFaceWalk(const point&, const label)"
) << "illegal seedFace:" << seedFaceI << exit(FatalError);
}
const vectorField& centres = mesh_.faceCentres();
// Walk in direction of face that decreases distance
label curFaceI = seedFaceI;
scalar distanceSqr = magSqr(centres[curFaceI] - location);
while (true)
{
label betterFaceI = curFaceI;
findNearer
(
location,
centres,
mesh_.cells()[mesh_.faceOwner()[curFaceI]],
betterFaceI,
distanceSqr
);
if (mesh_.isInternalFace(curFaceI))
{
findNearer
(
location,
centres,
mesh_.cells()[mesh_.faceNeighbour()[curFaceI]],
betterFaceI,
distanceSqr
);
}
if (betterFaceI == curFaceI)
{
break;
}
curFaceI = betterFaceI;
}
return curFaceI;
}
Foam::label Foam::meshSearch::findCellLinear(const point& location) const
{
bool cellFound = false;
label n = 0;
label cellI = -1;
while ((!cellFound) && (n < mesh_.nCells()))
{
if (pointInCell(location, n))
{
cellFound = true;
cellI = n;
}
else
{
n++;
}
}
if (cellFound)
{
return cellI;
}
else
{
return -1;
}
}
Foam::label Foam::meshSearch::findNearestBoundaryFaceWalk
(
const point& location,
const label seedFaceI
) const
{
if (seedFaceI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestBoundaryFaceWalk"
"(const point&, const label)"
) << "illegal seedFace:" << seedFaceI << exit(FatalError);
}
// Start off from seedFaceI
label curFaceI = seedFaceI;
const face& f = mesh_.faces()[curFaceI];
scalar minDist = f.nearestPoint
(
location,
mesh_.points()
).distance();
bool closer;
do
{
closer = false;
// Search through all neighbouring boundary faces by going
// across edges
label lastFaceI = curFaceI;
const labelList& myEdges = mesh_.faceEdges()[curFaceI];
forAll (myEdges, myEdgeI)
{
const labelList& neighbours = mesh_.edgeFaces()[myEdges[myEdgeI]];
// Check any face which uses edge, is boundary face and
// is not curFaceI itself.
forAll(neighbours, nI)
{
label faceI = neighbours[nI];
if
(
(faceI >= mesh_.nInternalFaces())
&& (faceI != lastFaceI)
)
{
const face& f = mesh_.faces()[faceI];
pointHit curHit = f.nearestPoint
(
location,
mesh_.points()
);
// If the face is closer, reset current face and distance
if (curHit.distance() < minDist)
{
minDist = curHit.distance();
curFaceI = faceI;
closer = true; // a closer neighbour has been found
}
}
}
}
} while (closer);
return curFaceI;
}
Foam::vector Foam::meshSearch::offset
(
const point& bPoint,
const label bFaceI,
const vector& dir
) const
{
// Get the neighbouring cell
label ownerCellI = mesh_.faceOwner()[bFaceI];
const point& c = mesh_.cellCentres()[ownerCellI];
// Typical dimension: distance from point on face to cell centre
scalar typDim = mag(c - bPoint);
return tol_*typDim*dir;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from components
Foam::meshSearch::meshSearch(const polyMesh& mesh, const bool faceDecomp)
:
mesh_(mesh),
faceDecomp_(faceDecomp),
cloud_(mesh_, IDLList<passiveParticle>()),
boundaryTreePtr_(NULL),
cellTreePtr_(NULL),
cellCentreTreePtr_(NULL)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::meshSearch::~meshSearch()
{
clearOut();
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
const Foam::indexedOctree<Foam::treeDataFace>& Foam::meshSearch::boundaryTree()
const
{
if (!boundaryTreePtr_)
{
//
// Construct tree
//
// all boundary faces (not just walls)
labelList bndFaces(mesh_.nFaces()-mesh_.nInternalFaces());
forAll(bndFaces, i)
{
bndFaces[i] = mesh_.nInternalFaces() + i;
}
treeBoundBox overallBb(mesh_.points());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
boundaryTreePtr_ = new indexedOctree<treeDataFace>
(
treeDataFace // all information needed to search faces
(
false, // do not cache bb
mesh_,
bndFaces // boundary faces only
),
overallBb, // overall search domain
8, // maxLevel
10, // leafsize
3.0 // duplicity
);
}
return *boundaryTreePtr_;
}
const Foam::indexedOctree<Foam::treeDataCell>& Foam::meshSearch::cellTree()
const
{
if (!cellTreePtr_)
{
//
// Construct tree
//
treeBoundBox overallBb(mesh_.points());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
cellTreePtr_ = new indexedOctree<treeDataCell>
(
treeDataCell
(
false, // not cache bb
mesh_
),
overallBb, // overall search domain
8, // maxLevel
10, // leafsize
3.0 // duplicity
);
}
return *cellTreePtr_;
}
const Foam::indexedOctree<Foam::treeDataPoint>&
Foam::meshSearch::cellCentreTree() const
{
if (!cellCentreTreePtr_)
{
//
// Construct tree
//
treeBoundBox overallBb(mesh_.cellCentres());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
cellCentreTreePtr_ = new indexedOctree<treeDataPoint>
(
treeDataPoint(mesh_.cellCentres()),
overallBb, // overall search domain
10, // max levels
10.0, // maximum ratio of cubes v.s. cells
100.0 // max. duplicity; n/a since no bounding boxes.
);
}
return *cellCentreTreePtr_;
}
// Is the point in the cell
// Works by checking if there is a face inbetween the point and the cell
// centre.
// Check for internal uses proper face decomposition or just average normal.
bool Foam::meshSearch::pointInCell(const point& p, label cellI) const
{
if (faceDecomp_)
{
const point& ctr = mesh_.cellCentres()[cellI];
vector dir(p - ctr);
scalar magDir = mag(dir);
// Check if any faces are hit by ray from cell centre to p.
// If none -> p is in cell.
const labelList& cFaces = mesh_.cells()[cellI];
// Make sure half_ray does not pick up any faces on the wrong
// side of the ray.
scalar oldTol = intersection::setPlanarTol(0.0);
forAll(cFaces, i)
{
label faceI = cFaces[i];
pointHit inter = mesh_.faces()[faceI].ray
(
ctr,
dir,
mesh_.points(),
intersection::HALF_RAY,
intersection::VECTOR
);
if (inter.hit())
{
scalar dist = inter.distance();
if (dist < magDir)
{
// Valid hit. Hit face so point is not in cell.
intersection::setPlanarTol(oldTol);
return false;
}
}
}
intersection::setPlanarTol(oldTol);
// No face inbetween point and cell centre so point is inside.
return true;
}
else
{
const labelList& f = mesh_.cells()[cellI];
const labelList& owner = mesh_.faceOwner();
const vectorField& cf = mesh_.faceCentres();
const vectorField& Sf = mesh_.faceAreas();
forAll(f, facei)
{
label nFace = f[facei];
vector proj = p - cf[nFace];
vector normal = Sf[nFace];
if (owner[nFace] == cellI)
{
if ((normal & proj) > 0)
{
return false;
}
}
else
{
if ((normal & proj) < 0)
{
return false;
}
}
}
return true;
}
}
Foam::label Foam::meshSearch::findNearestCell
(
const point& location,
const label seedCellI,
const bool useTreeSearch
) const
{
if (seedCellI == -1)
{
if (useTreeSearch)
{
return findNearestCellTree(location);
}
else
{
return findNearestCellLinear(location);
}
}
else
{
return findNearestCellWalk(location, seedCellI);
}
}
Foam::label Foam::meshSearch::findNearestFace
(
const point& location,
const label seedFaceI,
const bool useTreeSearch
) const
{
if (seedFaceI == -1)
{
if (useTreeSearch)
{
return findNearestFaceTree(location);
}
else
{
return findNearestFaceLinear(location);
}
}
else
{
return findNearestFaceWalk(location, seedFaceI);
}
}
Foam::label Foam::meshSearch::findCell
(
const point& location,
const label seedCellI,
const bool useTreeSearch
) const
{
// Find the nearest cell centre to this location
label nearCellI = findNearestCell(location, seedCellI, useTreeSearch);
if (debug)
{
Pout<< "findCell : nearCellI:" << nearCellI
<< " ctr:" << mesh_.cellCentres()[nearCellI]
<< endl;
}
if (pointInCell(location, nearCellI))
{
return nearCellI;
}
else
{
if (useTreeSearch)
{
// Start searching from cell centre of nearCell
point curPoint = mesh_.cellCentres()[nearCellI];
vector edgeVec = location - curPoint;
edgeVec /= mag(edgeVec);
do
{
// Walk neighbours (using tracking) to get closer
passiveParticle tracker(cloud_, curPoint, nearCellI);
if (debug)
{
Pout<< "findCell : tracked from curPoint:" << curPoint
<< " nearCellI:" << nearCellI;
}
tracker.track(location);
if (debug)
{
Pout<< " to " << tracker.position()
<< " need:" << location
<< " onB:" << tracker.onBoundary()
<< " cell:" << tracker.cell()
<< " face:" << tracker.face() << endl;
}
if (!tracker.onBoundary())
{
// stopped not on boundary -> reached location
return tracker.cell();
}
// stopped on boundary face. Compare positions
scalar typDim = sqrt(mag(mesh_.faceAreas()[tracker.face()]));
if ((mag(tracker.position() - location)/typDim) < SMALL)
{
return tracker.cell();
}
// tracking stopped at boundary. Find next boundary
// intersection from current point (shifted out a little bit)
// in the direction of the destination
curPoint =
tracker.position()
+ offset(tracker.position(), tracker.face(), edgeVec);
if (debug)
{
Pout<< "Searching for next boundary from curPoint:"
<< curPoint
<< " to location:" << location << endl;
}
pointIndexHit curHit = intersection(curPoint, location);
if (debug)
{
Pout<< "Returned from line search with ";
curHit.write(Pout);
Pout<< endl;
}
if (!curHit.hit())
{
return -1;
}
else
{
nearCellI = mesh_.faceOwner()[curHit.index()];
curPoint =
curHit.hitPoint()
+ offset(curHit.hitPoint(), curHit.index(), edgeVec);
}
}
while(true);
}
else
{
return findCellLinear(location);
}
}
return -1;
}
Foam::label Foam::meshSearch::findNearestBoundaryFace
(
const point& location,
const label seedFaceI,
const bool useTreeSearch
) const
{
if (seedFaceI == -1)
{
if (useTreeSearch)
{
const indexedOctree<treeDataFace>& tree = boundaryTree();
scalar span = tree.bb().mag();
pointIndexHit info = boundaryTree().findNearest
(
location,
Foam::sqr(span)
);
if (!info.hit())
{
info = boundaryTree().findNearest
(
location,
Foam::sqr(GREAT)
);
}
return tree.shapes().faceLabels()[info.index()];
}
else
{
scalar minDist = GREAT;
label minFaceI = -1;
for
(
label faceI = mesh_.nInternalFaces();
faceI < mesh_.nFaces();
faceI++
)
{
const face& f = mesh_.faces()[faceI];
pointHit curHit =
f.nearestPoint
(
location,
mesh_.points()
);
if (curHit.distance() < minDist)
{
minDist = curHit.distance();
minFaceI = faceI;
}
}
return minFaceI;
}
}
else
{
return findNearestBoundaryFaceWalk(location, seedFaceI);
}
}
Foam::pointIndexHit Foam::meshSearch::intersection
(
const point& pStart,
const point& pEnd
) const
{
pointIndexHit curHit = boundaryTree().findLine(pStart, pEnd);
if (curHit.hit())
{
// Change index into octreeData into face label
curHit.setIndex(boundaryTree().shapes().faceLabels()[curHit.index()]);
}
return curHit;
}
Foam::List<Foam::pointIndexHit> Foam::meshSearch::intersections
(
const point& pStart,
const point& pEnd
) const
{
DynamicList<pointIndexHit> hits;
vector edgeVec = pEnd - pStart;
edgeVec /= mag(edgeVec);
point pt = pStart;
pointIndexHit bHit;
do
{
bHit = intersection(pt, pEnd);
if (bHit.hit())
{
hits.append(bHit);
const vector& area = mesh_.faceAreas()[bHit.index()];
scalar typDim = Foam::sqrt(mag(area));
if ((mag(bHit.hitPoint() - pEnd)/typDim) < SMALL)
{
break;
}
// Restart from hitPoint shifted a little bit in the direction
// of the destination
pt =
bHit.hitPoint()
+ offset(bHit.hitPoint(), bHit.index(), edgeVec);
}
} while(bHit.hit());
hits.shrink();
return hits;
}
bool Foam::meshSearch::isInside(const point& p) const
{
return
boundaryTree().getVolumeType(p)
== indexedOctree<treeDataFace>::INSIDE;
}
// Delete all storage
void Foam::meshSearch::clearOut()
{
deleteDemandDrivenData(boundaryTreePtr_);
deleteDemandDrivenData(cellTreePtr_);
deleteDemandDrivenData(cellCentreTreePtr_);
}
void Foam::meshSearch::correct()
{
clearOut();
}
// ************************************************************************* //
| Java |
#include "simulation/Elements.h"
//#TPT-Directive ElementClass Element_FRZZ PT_FRZZ 100
Element_FRZZ::Element_FRZZ()
{
Identifier = "DEFAULT_PT_FRZZ";
Name = "FRZZ";
Colour = PIXPACK(0xC0E0FF);
MenuVisible = 1;
MenuSection = SC_POWDERS;
Enabled = 1;
Advection = 0.7f;
AirDrag = 0.01f * CFDS;
AirLoss = 0.96f;
Loss = 0.90f;
Collision = -0.1f;
Gravity = 0.05f;
Diffusion = 0.01f;
HotAir = -0.00005f* CFDS;
Falldown = 1;
Flammable = 0;
Explosive = 0;
Meltable = 0;
Hardness = 20;
Weight = 50;
Temperature = 253.15f;
HeatConduct = 46;
Description = "Freeze powder. When melted, forms ice that always cools. Spreads with regular water.";
State = ST_SOLID;
Properties = TYPE_PART;
LowPressure = IPL;
LowPressureTransition = NT;
HighPressure = 1.8f;
HighPressureTransition = PT_SNOW;
LowTemperature = 50.0f;
LowTemperatureTransition = PT_ICEI;
HighTemperature = 273.15;
HighTemperatureTransition = PT_WATR;
Update = &Element_FRZZ::update;
}
//#TPT-Directive ElementHeader Element_FRZZ static int update(UPDATE_FUNC_ARGS)
int Element_FRZZ::update(UPDATE_FUNC_ARGS)
{
int r, rx, ry;
for (rx=-1; rx<2; rx++)
for (ry=-1; ry<2; ry++)
if (x+rx>=0 && y+ry>0 && x+rx<XRES && y+ry<YRES && (rx || ry))
{
r = pmap[y+ry][x+rx];
if (!r)
continue;
if ((r&0xFF)==PT_WATR&&5>rand()%100)
{
sim->part_change_type(r>>8,x+rx,y+ry,PT_FRZW);
parts[r>>8].life = 100;
parts[i].type = PT_NONE;
}
}
if (parts[i].type==PT_NONE) {
sim->kill_part(i);
return 1;
}
return 0;
}
Element_FRZZ::~Element_FRZZ() {} | Java |
package net.minecraft.inventory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
// CraftBukkit start
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting;
import org.bukkit.craftbukkit.inventory.CraftInventoryView;
// CraftBukkit end
public class ContainerPlayer extends Container
{
public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2);
public IInventory craftResult = new InventoryCraftResult();
public boolean isLocalWorld;
private final EntityPlayer thePlayer;
// CraftBukkit start
private CraftInventoryView bukkitEntity = null;
private InventoryPlayer player;
// CraftBukkit end
private static final String __OBFID = "CL_00001754";
public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_)
{
this.isLocalWorld = p_i1819_2_;
this.thePlayer = p_i1819_3_;
this.craftResult = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction
this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player
this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot
this.player = p_i1819_1_; // CraftBukkit - save player
this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36));
int i;
int j;
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18));
}
}
for (i = 0; i < 4; ++i)
{
final int k = i;
this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18)
{
private static final String __OBFID = "CL_00001755";
public int getSlotStackLimit()
{
return 1;
}
public boolean isItemValid(ItemStack p_75214_1_)
{
if (p_75214_1_ == null) return false;
return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer);
}
@SideOnly(Side.CLIENT)
public IIcon getBackgroundIconIndex()
{
return ItemArmor.func_94602_b(k);
}
});
}
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 9; ++j)
{
this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i)
{
this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142));
}
// this.onCraftMatrixChanged(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty
}
public void onCraftMatrixChanged(IInventory p_75130_1_)
{
// CraftBukkit start (Note: the following line would cause an error if called during construction)
CraftingManager.getInstance().lastCraftView = getBukkitView();
ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj);
this.craftResult.setInventorySlotContents(0, craftResult);
if (super.crafters.size() < 1)
{
return;
}
EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it.
player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult));
// CraftBukkit end
}
public void onContainerClosed(EntityPlayer p_75134_1_)
{
super.onContainerClosed(p_75134_1_);
for (int i = 0; i < 4; ++i)
{
ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);
if (itemstack != null)
{
p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false);
}
}
this.craftResult.setInventorySlotContents(0, (ItemStack)null);
}
public boolean canInteractWith(EntityPlayer p_75145_1_)
{
return true;
}
public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_)
{
ItemStack itemstack = null;
Slot slot = (Slot)this.inventorySlots.get(p_82846_2_);
if (slot != null && slot.getHasStack())
{
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (p_82846_2_ == 0)
{
if (!this.mergeItemStack(itemstack1, 9, 45, true))
{
return null;
}
slot.onSlotChange(itemstack1, itemstack);
}
else if (p_82846_2_ >= 1 && p_82846_2_ < 5)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 5 && p_82846_2_ < 9)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack())
{
int j = 5 + ((ItemArmor)itemstack.getItem()).armorType;
if (!this.mergeItemStack(itemstack1, j, j + 1, false))
{
return null;
}
}
else if (p_82846_2_ >= 9 && p_82846_2_ < 36)
{
if (!this.mergeItemStack(itemstack1, 36, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 36 && p_82846_2_ < 45)
{
if (!this.mergeItemStack(itemstack1, 9, 36, false))
{
return null;
}
}
else if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
if (itemstack1.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
else
{
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize)
{
return null;
}
slot.onPickupFromSlot(p_82846_1_, itemstack1);
}
return itemstack;
}
public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_)
{
return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_);
}
// CraftBukkit start
public CraftInventoryView getBukkitView()
{
if (bukkitEntity != null)
{
return bukkitEntity;
}
CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftMatrix, this.craftResult);
bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this);
return bukkitEntity;
}
// CraftBukkit end
} | Java |
/*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
opj_image_t* opj_image_create0(void)
{
opj_image_t *image = (opj_image_t*)opj_calloc(1, sizeof(opj_image_t));
return image;
}
opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts,
opj_image_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc)
{
int compno;
opj_image_t *image = NULL;
image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t));
if (image) {
image->color_space = clrspc;
image->numcomps = numcmpts;
/* allocate memory for the per-component information */
image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof(
opj_image_comp_t));
if (!image->comps) {
fprintf(stderr, "Unable to allocate memory for image.\n");
opj_image_destroy(image);
return NULL;
}
/* create the individual image components */
for (compno = 0; compno < numcmpts; compno++) {
opj_image_comp_t *comp = &image->comps[compno];
comp->dx = cmptparms[compno].dx;
comp->dy = cmptparms[compno].dy;
comp->w = cmptparms[compno].w;
comp->h = cmptparms[compno].h;
comp->x0 = cmptparms[compno].x0;
comp->y0 = cmptparms[compno].y0;
comp->prec = cmptparms[compno].prec;
comp->bpp = cmptparms[compno].bpp;
comp->sgnd = cmptparms[compno].sgnd;
comp->data = (int*) opj_calloc(comp->w * comp->h, sizeof(int));
if (!comp->data) {
fprintf(stderr, "Unable to allocate memory for image.\n");
opj_image_destroy(image);
return NULL;
}
}
}
return image;
}
void OPJ_CALLCONV opj_image_destroy(opj_image_t *image)
{
int i;
if (image) {
if (image->comps) {
/* image components */
for (i = 0; i < image->numcomps; i++) {
opj_image_comp_t *image_comp = &image->comps[i];
if (image_comp->data) {
opj_free(image_comp->data);
}
}
opj_free(image->comps);
}
opj_free(image);
}
}
| Java |
#include "spammer.h"
SpammerType Settings::Spammer::type = SpammerType::SPAMMER_NONE;
bool Settings::Spammer::say_team = false;
bool Settings::Spammer::KillSpammer::enabled = false;
bool Settings::Spammer::KillSpammer::sayTeam = false;
std::vector<std::string> Settings::Spammer::KillSpammer::messages = {
"$nick owned by ELITE4",
"$nick suck's again"
};
bool Settings::Spammer::RadioSpammer::enabled = false;
std::vector<std::string> Settings::Spammer::NormalSpammer::messages = {
"I'AM BAD CODER",
"DON'T LIKE TOMATOES",
"SUPREME HACK",
"ELITE4 OWNS U AND ALL",
"ELITE4LEGIT.TK",
"ELITE4HVH.TK"
};
int Settings::Spammer::PositionSpammer::team = 1;
bool Settings::Spammer::PositionSpammer::showName = true;
bool Settings::Spammer::PositionSpammer::showWeapon = true;
bool Settings::Spammer::PositionSpammer::showRank = true;
bool Settings::Spammer::PositionSpammer::showWins = true;
bool Settings::Spammer::PositionSpammer::showHealth = true;
bool Settings::Spammer::PositionSpammer::showMoney = true;
bool Settings::Spammer::PositionSpammer::showLastplace = true;
std::vector<int> killedPlayerQueue;
void Spammer::BeginFrame(float frameTime)
{
if (!engine->IsInGame())
return;
// Grab the current time in milliseconds
long currentTime_ms = Util::GetEpochTime();
static long timeStamp = currentTime_ms;
if (currentTime_ms - timeStamp < 850)
return;
// Kill spammer
if (Settings::Spammer::KillSpammer::enabled && killedPlayerQueue.size() > 0)
{
IEngineClient::player_info_t playerInfo;
engine->GetPlayerInfo(killedPlayerQueue[0], &playerInfo);
// Prepare dead player's nickname without ';' & '"' characters
// as they might cause user to execute a command.
std::string dead_player_name = std::string(playerInfo.name);
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), ';'), dead_player_name.end());
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '"'), dead_player_name.end());
// Remove end line character
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '\n'), dead_player_name.end());
// Construct a command with our message
pstring str;
str << (Settings::Spammer::KillSpammer::sayTeam ? "say_team" : "say");
std::string message = Settings::Spammer::KillSpammer::messages[std::rand() % Settings::Spammer::KillSpammer::messages.size()];
str << " \"" << Util::ReplaceString(message, "$nick", dead_player_name) << "\"";
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
// Remove the first element from the vector
killedPlayerQueue.erase(killedPlayerQueue.begin(), killedPlayerQueue.begin() + 1);
return;
}
if (Settings::Spammer::RadioSpammer::enabled)
{
const char* radioCommands[] = {
"coverme",
"takepoint",
"holdpos",
"regroup",
"followme",
"takingfire",
"go",
"fallback",
"sticktog",
"report",
"roger",
"enemyspot",
"needbackup",
"sectorclear",
"inposition",
"reportingin",
"getout",
"negative",
"enemydown",
};
engine->ClientCmd_Unrestricted(radioCommands[std::rand() % IM_ARRAYSIZE(radioCommands)]);
}
if (Settings::Spammer::type == SpammerType::SPAMMER_NORMAL)
{
if (Settings::Spammer::NormalSpammer::messages.empty())
return;
// Grab a random message string
std::string message = Settings::Spammer::NormalSpammer::messages[std::rand() % Settings::Spammer::NormalSpammer::messages.size()];
// Construct a command with our message
pstring str;
str << (Settings::Spammer::say_team ? "say_team" : "say") << " ";
str << message;
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
}
else if (Settings::Spammer::type == SpammerType::SPAMMER_POSITIONS)
{
C_BasePlayer* localplayer = (C_BasePlayer*) entityList->GetClientEntity(engine->GetLocalPlayer());
static int lastId = 1;
for (int i = lastId; i < engine->GetMaxClients(); i++)
{
C_BasePlayer* player = (C_BasePlayer*) entityList->GetClientEntity(i);
lastId++;
if (lastId == engine->GetMaxClients())
lastId = 1;
if (!player
|| player->GetDormant()
|| !player->GetAlive())
continue;
if (Settings::Spammer::PositionSpammer::team == 0 && player->GetTeam() != localplayer->GetTeam())
continue;
if (Settings::Spammer::PositionSpammer::team == 1 && player->GetTeam() == localplayer->GetTeam())
continue;
IEngineClient::player_info_t entityInformation;
engine->GetPlayerInfo(i, &entityInformation);
C_BaseCombatWeapon* activeWeapon = (C_BaseCombatWeapon*) entityList->GetClientEntityFromHandle(player->GetActiveWeapon());
// Prepare player's nickname without ';' & '"' characters
// as they might cause user to execute a command.
std::string playerName = std::string(entityInformation.name);
playerName.erase(std::remove(playerName.begin(), playerName.end(), ';'), playerName.end());
playerName.erase(std::remove(playerName.begin(), playerName.end(), '"'), playerName.end());
// Remove end line character
playerName.erase(std::remove(playerName.begin(), playerName.end(), '\n'), playerName.end());
// Construct a command with our message
pstring str;
str << (Settings::Spammer::say_team ? "say_team" : "say") << " \"";
if (Settings::Spammer::PositionSpammer::showName)
str << playerName << " | ";
if (Settings::Spammer::PositionSpammer::showWeapon)
str << Util::Items::GetItemDisplayName(*activeWeapon->GetItemDefinitionIndex()) << " | ";
if (Settings::Spammer::PositionSpammer::showRank)
str << ESP::ranks[*(*csPlayerResource)->GetCompetitiveRanking(i)] << " | ";
if (Settings::Spammer::PositionSpammer::showWins)
str << *(*csPlayerResource)->GetCompetitiveWins(i) << " wins | ";
if (Settings::Spammer::PositionSpammer::showHealth)
str << player->GetHealth() << "HP | ";
if (Settings::Spammer::PositionSpammer::showMoney)
str << "$" << player->GetMoney() << " | ";
if (Settings::Spammer::PositionSpammer::showLastplace)
str << player->GetLastPlaceName();
str << "\"";
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
break;
}
}
// Update the time stamp
timeStamp = currentTime_ms;
}
void Spammer::FireGameEvent(IGameEvent* event)
{
if (!Settings::Spammer::KillSpammer::enabled)
return;
if (!engine->IsInGame())
return;
if (strcmp(event->GetName(), "player_death") != 0)
return;
int attacker_id = engine->GetPlayerForUserID(event->GetInt("attacker"));
int deadPlayer_id = engine->GetPlayerForUserID(event->GetInt("userid"));
// Make sure it's not a suicide.x
if (attacker_id == deadPlayer_id)
return;
// Make sure we're the one who killed someone...
if (attacker_id != engine->GetLocalPlayer())
return;
killedPlayerQueue.push_back(deadPlayer_id);
}
| Java |
package com.app.server.repository;
import com.athena.server.repository.SearchInterface;
import com.athena.annotation.Complexity;
import com.athena.annotation.SourceCodeAuthorClass;
import com.athena.framework.server.exception.repository.SpartanPersistenceException;
import java.util.List;
import com.athena.framework.server.exception.biz.SpartanConstraintViolationException;
@SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Title Master table Entity", complexity = Complexity.LOW)
public interface TitleRepository<T> extends SearchInterface {
public List<T> findAll() throws SpartanPersistenceException;
public T save(T entity) throws SpartanPersistenceException;
public List<T> save(List<T> entity) throws SpartanPersistenceException;
public void delete(String id) throws SpartanPersistenceException;
public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException;
public void update(List<T> entity) throws SpartanPersistenceException;
public T findById(String titleId) throws Exception, SpartanPersistenceException;
}
| Java |
body {
background: #EEE;
font-family: arial, helvetica, sans-serif;
}
.controls {
position: relative;
width: 640px;
}
#seek {
width: 400px;
position: absolute;
right: 0;
top: 0;
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>RebeccaAIML: Class Members</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.5 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li id="current"><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="namespaces.html"><span>Namespace List</span></a></li>
<li id="current"><a href="namespacemembers.html"><span>Namespace Members</span></a></li>
</ul></div>
<div class="tabs">
<ul>
<li id="current"><a href="namespacemembers.html"><span>All</span></a></li>
<li><a href="namespacemembers_func.html"><span>Functions</span></a></li>
<li><a href="namespacemembers_type.html"><span>Typedefs</span></a></li>
</ul>
</div>
Here is a list of all documented namespace members with links to the namespaces they belong to:
<p>
<ul>
<li>MapStringLinks
: <a class="el" href="namespacecustom_tag_1_1impl.html#ea8a448ca159d020766f77fdb2b41580">customTag::impl</a><li>MapWebPageMapStringLinks
: <a class="el" href="namespacecustom_tag_1_1impl.html#31022de1a67c828d770e09c75caa835c">customTag::impl</a><li>operator<()
: <a class="el" href="namespacecustom_tag_1_1impl.html#9950795db5c5a7018096dfb22494a6a5">customTag::impl</a><li>sanitizeString()
: <a class="el" href="namespacecustom_tag_1_1impl.html#8063ee0dbe5e9d96d9dd4933210f9cbb">customTag::impl</a></ul>
<hr size="1"><address style="align: right;"><small>Generated on Tue Feb 14 22:44:55 2006 for RebeccaAIML by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.5 </small></address>
</body>
</html>
| Java |
/*
* Copyright (c) 2011 Sveriges Television AB <[email protected]>
*
* This file is part of CasparCG (www.casparcg.com).
*
* CasparCG 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.
*
* CasparCG 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 CasparCG. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Robert Nagy, [email protected]
*/
#pragma once
#include <common/except.h>
#include <string>
namespace caspar { namespace ffmpeg {
struct ffmpeg_error : virtual caspar_exception{};
struct averror_bsf_not_found : virtual ffmpeg_error{};
struct averror_decoder_not_found : virtual ffmpeg_error{};
struct averror_demuxer_not_found : virtual ffmpeg_error{};
struct averror_encoder_not_found : virtual ffmpeg_error{};
struct averror_eof : virtual ffmpeg_error{};
struct averror_exit : virtual ffmpeg_error{};
struct averror_filter_not_found : virtual ffmpeg_error{};
struct averror_muxer_not_found : virtual ffmpeg_error{};
struct averror_option_not_found : virtual ffmpeg_error{};
struct averror_patchwelcome : virtual ffmpeg_error{};
struct averror_protocol_not_found : virtual ffmpeg_error{};
struct averror_stream_not_found : virtual ffmpeg_error{};
std::string av_error_str(int errn);
void throw_on_ffmpeg_error(int ret, const char* source, const char* func, const char* local_func, const char* file, int line);
void throw_on_ffmpeg_error(int ret, const std::wstring& source, const char* func, const char* local_func, const char* file, int line);
//#define THROW_ON_ERROR(ret, source, func) throw_on_ffmpeg_error(ret, source, __FUNC__, __FILE__, __LINE__)
#define THROW_ON_ERROR_STR_(call) #call
#define THROW_ON_ERROR_STR(call) THROW_ON_ERROR_STR_(call)
#define THROW_ON_ERROR(ret, func, source) \
throw_on_ffmpeg_error(ret, source, func, __FUNCTION__, __FILE__, __LINE__);
#define THROW_ON_ERROR2(call, source) \
[&]() -> int \
{ \
int ret = call; \
throw_on_ffmpeg_error(ret, source, THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \
return ret; \
}()
#define LOG_ON_ERROR2(call, source) \
[&]() -> int \
{ \
int ret = -1;\
try{ \
ret = call; \
throw_on_ffmpeg_error(ret, source, THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \
return ret; \
}catch(...){CASPAR_LOG_CURRENT_EXCEPTION();} \
return ret; \
}()
#define FF_RET(ret, func) \
caspar::ffmpeg::throw_on_ffmpeg_error(ret, L"", func, __FUNCTION__, __FILE__, __LINE__);
#define FF(call) \
[&]() -> int \
{ \
auto ret = call; \
caspar::ffmpeg::throw_on_ffmpeg_error(static_cast<int>(ret), L"", THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \
return ret; \
}()
}}
| Java |
#
# Makefile Makefile for the systemV init suite.
# Targets: all compiles everything
# install installs the binaries (not the scripts)
# clean cleans up object files
# clobber really cleans up
#
# Version: @(#)Makefile 2.85-13 23-Mar-2004 [email protected]
#
CPPFLAGS =
CFLAGS ?= -ansi -O2 -fomit-frame-pointer
override CFLAGS += -W -Wall -D_GNU_SOURCE
override CFLAGS += $(shell getconf LFS_CFLAGS)
STATIC =
# For some known distributions we do not build all programs, otherwise we do.
BIN =
SBIN = init halt shutdown runlevel killall5 fstab-decode
USRBIN = last mesg
MAN1 = last.1 lastb.1 mesg.1
MAN5 = initscript.5 inittab.5
MAN8 = halt.8 init.8 killall5.8 pidof.8 poweroff.8 reboot.8 runlevel.8
MAN8 += shutdown.8 telinit.8 fstab-decode.8
ifeq ($(DISTRO),)
BIN += mountpoint
SBIN += sulogin bootlogd
USRBIN += utmpdump wall
MAN1 += utmpdump.1 mountpoint.1 wall.1
MAN8 += sulogin.8 bootlogd.8
endif
ifeq ($(DISTRO),Debian)
CPPFLAGS+= -DACCTON_OFF
BIN += mountpoint
SBIN += sulogin bootlogd
MAN1 += mountpoint.1
MAN8 += sulogin.8 bootlogd.8
endif
ifeq ($(DISTRO),Owl)
USRBIN += wall
MAN1 += wall.1
endif
ifeq ($(DISTRO),SuSE)
CPPFLAGS+= -DUSE_SYSFS -DSANE_TIO -DSIGINT_ONLYONCE -DUSE_ONELINE
BIN += mountpoint
SBIN += sulogin
USRBIN += utmpdump
MAN1 += utmpdump.1 mountpoint.1
MAN8 += sulogin.8
endif
ID = $(shell id -u)
BIN_OWNER = root
BIN_GROUP = root
BIN_COMBO = $(BIN_OWNER):$(BIN_GROUP)
ifeq ($(ID),0)
INSTALL_EXEC = install -o $(BIN_OWNER) -g $(BIN_GROUP) -m 755
INSTALL_DATA = install -o $(BIN_OWNER) -g $(BIN_GROUP) -m 644
else
INSTALL_EXEC = install -m 755
INSTALL_DATA = install -m 644
endif
INSTALL_DIR = install -m 755 -d
MANDIR = /usr/share/man
ifeq ($(WITH_SELINUX),yes)
SELINUX_DEF = -DWITH_SELINUX
INITLIBS += -lsepol -lselinux
SULOGINLIBS = -lselinux
else
SELINUX_DEF =
INITLIBS =
SULOGINLIBS =
endif
# Additional libs for GNU libc.
ifneq ($(wildcard /usr/lib*/libcrypt.a),)
SULOGINLIBS += -lcrypt
endif
all: $(BIN) $(SBIN) $(USRBIN)
#%: %.o
# $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
#%.o: %.c
# $(CC) $(CFLAGS) $(CPPFLAGS) -c $^ -o $@
init: LDLIBS += $(INITLIBS) $(STATIC)
init: init.o init_utmp.o
halt: halt.o ifdown.o hddown.o utmp.o reboot.h
last: last.o oldutmp.h
mesg: mesg.o
mountpoint: mountpoint.o
utmpdump: utmpdump.o
runlevel: runlevel.o
sulogin: LDLIBS += $(SULOGINLIBS) $(STATIC)
sulogin: sulogin.o
wall: dowall.o wall.o
shutdown: dowall.o shutdown.o utmp.o reboot.h
bootlogd: LDLIBS += -lutil
bootlogd: bootlogd.o
sulogin.o: CPPFLAGS += $(SELINUX_DEF)
sulogin.o: sulogin.c
init.o: CPPFLAGS += $(SELINUX_DEF)
init.o: init.c init.h set.h reboot.h initreq.h
utmp.o: utmp.c init.h
init_utmp.o: CPPFLAGS += -DINIT_MAIN
init_utmp.o: utmp.c init.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
cleanobjs:
rm -f *.o *.bak
clean: cleanobjs
@echo Type \"make clobber\" to really clean up.
clobber: cleanobjs
rm -f $(BIN) $(SBIN) $(USRBIN)
distclean: clobber
install:
$(INSTALL_DIR) $(ROOT)/bin/ $(ROOT)/sbin/
$(INSTALL_DIR) $(ROOT)/usr/bin/
for i in $(BIN); do \
$(INSTALL_EXEC) $$i $(ROOT)/bin/ ; \
done
for i in $(SBIN); do \
$(INSTALL_EXEC) $$i $(ROOT)/sbin/ ; \
done
for i in $(USRBIN); do \
$(INSTALL_EXEC) $$i $(ROOT)/usr/bin/ ; \
done
# $(INSTALL_DIR) $(ROOT)/etc/
# $(INSTALL_EXEC) initscript.sample $(ROOT)/etc/
ln -sf halt $(ROOT)/sbin/reboot
ln -sf halt $(ROOT)/sbin/poweroff
ln -sf init $(ROOT)/sbin/telinit
ln -sf /sbin/killall5 $(ROOT)/bin/pidof
if [ ! -f $(ROOT)/usr/bin/lastb ]; then \
ln -sf last $(ROOT)/usr/bin/lastb; \
fi
$(INSTALL_DIR) $(ROOT)/usr/include/
$(INSTALL_DATA) initreq.h $(ROOT)/usr/include/
$(INSTALL_DIR) $(ROOT)$(MANDIR)/man1/
$(INSTALL_DIR) $(ROOT)$(MANDIR)/man5/
$(INSTALL_DIR) $(ROOT)$(MANDIR)/man8/
for i in $(MAN1); do \
$(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man1/; \
done
for i in $(MAN5); do \
$(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man5/; \
done
for i in $(MAN8); do \
$(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man8/; \
done
ifeq ($(ROOT),)
#
# This part is skipped on Debian systems, the
# debian.preinst script takes care of it.
@if [ ! -p /dev/initctl ]; then \
echo "Creating /dev/initctl"; \
rm -f /dev/initctl; \
mknod -m 600 /dev/initctl p; fi
endif
| Java |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition 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.
*
* OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @copyright (C) OXID eSales AG 2003-2016
* @version OXID eShop CE
*/
namespace OxidEsales\EshopCommunity\Tests\Integration\Seo;
use OxidEsales\Eshop\Application\Model\Article;
use OxidEsales\Eshop\Application\Model\Category;
use OxidEsales\Eshop\Application\Model\Object2Category;
use OxidEsales\Eshop\Core\DatabaseProvider;
use OxidEsales\Eshop\Core\Field;
/**
* Class PaginationSeoTest
*
* @package OxidEsales\EshopCommunity\Tests\Integration\Seo
*/
class PaginationSeoTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/** @var string Original theme */
private $origTheme;
/**
* @var string
*/
private $seoUrl = '';
/**
* @var string
*/
private $categoryOxid = '';
/**
* Sets up test
*/
protected function setUp(): void
{
parent::setUp();
$this->origTheme = $this->getConfig()->getConfigParam('sTheme');
$this->activateTheme('azure');
$this->getConfig()->saveShopConfVar('bool', 'blEnableSeoCache', false);
$this->cleanRegistry();
$this->cleanSeoTable();
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
oxNew(\OxidEsales\Eshop\Application\Model\ArticleList::class)->renewPriceUpdateTime();
oxNew(\OxidEsales\Eshop\Core\SystemEventHandler::class)->onShopEnd();
}
/**
* Tear down test.
*/
protected function tearDown(): void
{
//restore theme, do it directly in database as it might be dummy 'basic' theme
$query = "UPDATE `oxconfig` SET `OXVARVALUE` = '" . $this->origTheme . "' WHERE `OXVARNAME` = 'sTheme'";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$this->cleanRegistry();
$this->cleanSeoTable();
$_GET = [];
parent::tearDown();
}
/**
* Call with a seo url that is not yet stored in oxseo table.
* Category etc exists.
* We hit the 404 as no entry for this url exists in oxseo table.
* But when shop shows the 404 page, it creates the main category seo urls.
*/
public function testCallWithSeoUrlNoEntryInTableExists()
{
$this->callCurl('');
$this->callCurl($this->seoUrl);
$this->cleanRegistry();
$this->cleanSeoTable();
$this->clearProxyCache();
$seoUrl = $this->seoUrl;
$checkResponse = '404 Not Found';
//before
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` like '%" . $seoUrl . "%'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEmpty($res);
//check what shop does
$response = $this->callCurl($seoUrl);
$this->assertStringContainsString($checkResponse, $response, "Should get $checkResponse");
}
/**
* Call with a standard url that is not yet stored in oxseo table.
* Category etc exists. No pgNr is provided.
*
*
*/
public function testCallWithStdUrlNoEntryExists()
{
$urlToCall = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
$checkResponse = 'HTTP/1.1 200 OK';
//Check entries in oxseo table for oxtype = 'oxcategory'
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEmpty($res);
$response = $this->callCurl($urlToCall);
$this->assertStringContainsString($checkResponse, $response, "Should get $checkResponse");
}
/**
* Call shop with standard url, no matching entry in seo table exists atm.
*/
public function testStandardUrlNoMatchingSeoUrlSavedYet()
{
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
//No match in oxseo table
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertFalse($redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_NOINDEXFOLLOW, $controller->noIndex());
$this->assertEmpty($this->getCategorySeoEntries());
}
/**
* Call shop with standard url, a matching entry in seo table already exists.
*/
public function testStandardUrlMatchingSeoUrlAvailable()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl, $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$this->assertEquals(1, count($this->getCategorySeoEntries()));
}
/**
* Call shop with standard url and append pgNr request parameter.
* Blank seo url already is stored in oxseo table.
* Case that pgNr should exist as there are sufficient items in that category.
*/
public function testSeoUrlWithPgNr()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=2';
//base seo url is found in database and page part appended
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=2', $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
}
/**
* Test paginated entries. Call with standard url with appended pgNr parameter.
*/
public function testExistingPaginatedSeoEntries()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$this->assertGeneratedPages();
//Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case.
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=1';
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=1', $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
}
/**
* Test paginated entries. Call with standard url with appended pgNr parameter.
* Dofference to test case before: call with ot existing page Nr.
*/
public function testNotExistingPaginatedSeoEntries()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$this->assertGeneratedPages();
//Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case.
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=20';
//The paginated page url is created on the fly. This seo page would not contain any data.
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=20', $redirectUrl);
}
public function providerTestDecodeNewSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
$data = [];
$data['plain_seo_url'] = ['params' => $this->seoUrl,
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0']
];
$data['old_style_paginated_page'] = ['params' => $this->seoUrl . '2/',
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => 1]
];
return $data;
}
/**
* Test decoding seo calls.
*
* @param string $params
* @param array $expected
*
* @dataProvider providerTestDecodeNewSeoUrl
*/
public function testDecodeNewSeoUrl($params, $expected)
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
$decoded = $seoDecoder->decodeUrl($params); //decoded new url
$this->assertEquals($expected, $decoded);
}
public function providerTestProcessingSeoCallNewSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
$data = [];
$data['plain_seo_url'] = ['request' => $this->seoUrl,
'get' => [],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0']
];
$data['paginated_page'] = ['request' => $this->seoUrl . '2/',
'get' => ['pgNr' => '1'],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => '1']
];
$data['pgnr_as_get'] = ['params' => $this->seoUrl . '?pgNr=2',
'get' => ['pgNr' => '2'],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => '2']
];
return $data;
}
/**
* Test decoding seo calls. Call shop with seo main page plus pgNr parameter.
* No additional paginated pages are stored in oxseo table. pgNr parameter
* come in via GET and all other needed parameters for processing the call
* are extracted via decodeUrl.
* To be able to correctly decode an url like 'Geschenke/2/' without having
* a matching entry stored in oxseo table, we need to parse this url into
* 'Geschenke/' plus pgNr parameter.
*
* @param string $params
* @param array $get
* @param array $expected
*
* @dataProvider providerTestProcessingSeoCallNewSeoUrl
*/
public function testProcessingSeoCallNewSeoUrl($request, $get, $expected)
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
$_GET = $get;
$seoDecoder->processSeoCall($request, '/');
$this->assertEquals($expected, $_GET);
$this->assertGeneratedPages();
}
/**
* Test SeoEncoderCategory::getCategoryPageUrl()
*/
public function testGetCategoryPageUrl()
{
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$category = oxNew(\OxidEsales\Eshop\Application\Model\Category::class);
$category->load($this->categoryOxid);
$seoEncoderCategory = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class);
$result = $seoEncoderCategory->getCategoryPageUrl($category, 2);
$this->assertEquals($shopUrl . $this->seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderCategory = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class, ['_saveToDb']);
$seoEncoderCategory->expects($this->never())->method('_saveToDb');
$seoEncoderCategory->getCategoryPageUrl($category, 0);
$seoEncoderCategory->getCategoryPageUrl($category, 1);
$seoEncoderCategory->getCategoryPageUrl($category, 2);
}
/**
* Test SeoEncoderVendor::getVendorPageUrl()
*/
public function testGetVendorPageUrl()
{
$facts = new \OxidEsales\Facts\Facts();
if ('EE' != $facts->getEdition()) {
$this->markTestSkipped('missing testdata');
}
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$vendorOxid = 'd2e44d9b31fcce448.08890330';
$seoUrl = 'Nach-Lieferant/Hersteller-1/';
$vendor = oxNew(\OxidEsales\Eshop\Application\Model\Vendor::class);
$vendor->load($vendorOxid);
$seoEncoderVendor = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class);
$result = $seoEncoderVendor->getVendorPageUrl($vendor, 2);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderVendor = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class, ['_saveToDb']);
$seoEncoderVendor->expects($this->never())->method('_saveToDb');
$seoEncoderVendor->getVendorPageUrl($vendor, 0);
$seoEncoderVendor->getVendorPageUrl($vendor, 1);
$seoEncoderVendor->getVendorPageUrl($vendor, 2);
}
/**
* Test SeoEncoderManufacturer::getManufacturerPageUrl()
*/
public function testGetManufacturerPageUrl()
{
$facts = new \OxidEsales\Facts\Facts();
if ('EE' != $facts->getEdition()) {
$this->markTestSkipped('missing testdata');
}
$languageId = 1; //en
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$manufacturerOxid = '2536d76675ebe5cb777411914a2fc8fb';
$seoUrl = 'en/By-manufacturer/Manufacturer-2/';
$manufacturer = oxNew(\OxidEsales\Eshop\Application\Model\Manufacturer::class);
$manufacturer->load($manufacturerOxid);
$seoEncoderManufacturer = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderManufacturer::class);
$result = $seoEncoderManufacturer->getManufacturerPageUrl($manufacturer, 2, $languageId);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
}
/**
* Test SeoEncoderRecomm::getRecommPageUrl()
*/
public function testGetRecommPageUrl()
{
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$seoUrl = 'testTitle/';
$recomm = $this->getMock(\OxidEsales\Eshop\Application\Model\RecommendationList::class, ['getId', 'getBaseStdLink']);
$recomm->expects($this->any())->method('getId')->will($this->returnValue('testRecommId'));
$recomm->expects($this->any())->method('getBaseStdLink')->will($this->returnValue('testStdLink'));
$recomm->oxrecommlists__oxtitle = new \OxidEsales\Eshop\Core\Field('testTitle');
$seoEncoderRecomm = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class);
$result = $seoEncoderRecomm->getRecommPageUrl($recomm, 2);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderRecomm = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class, ['_saveToDb']);
$seoEncoderRecomm->expects($this->never())->method('_saveToDb');
$seoEncoderRecomm->getRecommPageUrl($recomm, 0);
$seoEncoderRecomm->getRecommPageUrl($recomm, 1);
$seoEncoderRecomm->getRecommPageUrl($recomm, 2);
}
public function providerCheckSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$oxidLiving = ('EE' != $facts->getEdition()) ? '8a142c3e44ea4e714.31136811' : '30e44ab83b6e585c9.63147165';
$data = [
['Eco-Fashion/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['Eco-Fashion/3/', ['404 Not Found'], [], ['Eco-Fashion/']],
['Eco-Fashion/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], []],
['Eco-Fashion/?pgNr=34', ['404 Not Found'],[], []],
['index.php?cl=alist&cnid=oxmore', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=0', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=10', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=20', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=' . $oxidLiving, ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=100', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=200', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]]
];
if (('EE' == $facts->getEdition())) {
$data[] = ['Fuer-Sie/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []];
$data[] = ['Fuer-Sie/45/', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']];
$data[] = ['Fuer-Sie/?pgNr=0', ['HTTP/1.1 200 OK'], [ 'Location', 'ROBOTS'], []];
$data[] = ['Fuer-Sie/?pgNr=34', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']];
} else {
$data[] = ['Geschenke/', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving]];
$data[] = ['Geschenke/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=100', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/30/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=1', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=3', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=4', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/4/', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1',]];
$data[] = ['Geschenke/10/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1', 'Geschenke/4/']];
}
return $data;
}
/**
* Calling not existing pagenumbers must not result in additional entries in oxseo table.
*
* @dataProvider providerCheckSeoUrl
*
* @param string $urlToCall Url to call
* @param array $responseContains Curl call response must contain.
* @param array $responseNotContains Curl call response must not contain.
* @param array $prepareUrls To make test cases independent, call this url first.
*/
public function testCheckSeoUrl(
$urlToCall,
$responseContains,
$responseNotContains,
$prepareUrls
) {
$this->initSeoUrlGeneration();
foreach ($prepareUrls as $url) {
$this->callCurl($url);
}
$response = $this->callCurl($urlToCall);
foreach ($responseContains as $checkFor) {
$this->assertStringContainsString($checkFor, $response, "Should get $checkFor");
}
foreach ($responseNotContains as $checkFor) {
$this->assertStringNotContainsString($checkFor, $response, "Should not get $checkFor");
}
}
public function testCreateProductSeoUrlsOnProductListPageRequest()
{
$this->prepareSeoUrlTestData();
$this->initSeoUrlGeneration();
$seoUrl = 'testSeoUrl/';
$productSeoUrlsCountBeforeRequest = $this->getProductSeoUrlsCount($seoUrl);
$this->callCurl($seoUrl . '?pgNr=0');
$this->clearProxyCache();
$this->callCurl($seoUrl . '?pgNr=0');
$productSeoUrlsCountAfterRequest = $this->getProductSeoUrlsCount($seoUrl);
$productsPerPage = 10;
$this->assertEquals(
$productSeoUrlsCountBeforeRequest + $productsPerPage,
$productSeoUrlsCountAfterRequest
);
}
public function testDoNotCreateAnotherCategorySeoUrlsOnProductListPageRequest()
{
$this->prepareSeoUrlTestData();
$seoUrl = 'testSeoUrl/';
$this->callCurl($seoUrl);
$this->assertCount(
1,
$this->getCategorySeoUrls($seoUrl)
);
$this->callCurl($seoUrl . '?pgNr=0');
$this->callCurl($seoUrl . '1');
$this->assertCount(
1,
$this->getCategorySeoUrls($seoUrl)
);
}
private function initSeoUrlGeneration()
{
$this->clearProxyCache();
$this->callCurl(''); //call shop startpage
$this->clearProxyCache();
}
private function getProductSeoUrlsCount($url)
{
$query = "
SELECT
count(*)
FROM
`oxseo`
WHERE
oxseourl LIKE '%" . $url . "%'
AND oxtype = 'oxarticle'
";
return DatabaseProvider::getDb()->getOne($query);
}
private function getCategorySeoUrls($url)
{
$query = "
SELECT
oxseourl
FROM
`oxseo`
WHERE
oxseourl LIKE '%" . $url . "%'
AND oxtype = 'oxcategory'
";
return DatabaseProvider::getDb()->getAll($query);
}
private function prepareSeoUrlTestData()
{
$seoUrl = 'testSeoUrl';
$shopId = $this->getConfig()->getBaseShopId();
$category = oxNew(Category::class);
$category->oxcategories__oxactive = new Field(1, Field::T_RAW);
$category->oxcategories__oxparentid = new Field('oxrootid', Field::T_RAW);
$category->oxcategories__oxshopid = new Field($shopId, Field::T_RAW);
$category->oxcategories__oxtitle = new Field($seoUrl, Field::T_RAW);
$category->save();
for ($i = 1; $i <= 20; $i++) {
$product = oxNew(Article::class);
$product->oxarticles__oxtitle = new Field($seoUrl, Field::T_RAW);
$product->save();
$relation = oxNew(Object2Category::class);
$relation->setCategoryId($category->getId());
$relation->setProductId($product->getId());
$relation->save();
}
}
/**
* Clean oxseo for testing.
*/
private function cleanSeoTable()
{
$query = "DELETE FROM oxseo WHERE oxtype in ('oxcategory', 'oxarticle')";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
}
/**
* Ensure that whatever mocks were added are removed from Registry.
*/
private function cleanRegistry()
{
$seoEncoder = oxNew(\OxidEsales\Eshop\Core\SeoEncoder::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoEncoder::class, $seoEncoder);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoDecoder::class, $seoDecoder);
$utils = oxNew(\OxidEsales\Eshop\Core\Utils::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = oxNew(\OxidEsales\Eshop\Core\Request::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
}
/**
* @param string $fileUrlPart Shop url part to call.
*
* @return string
*/
private function callCurl($fileUrlPart)
{
$url = $this->getConfig()->getShopMainUrl() . $fileUrlPart;
$curl = oxNew(\OxidEsales\Eshop\Core\Curl::class);
$curl->setOption('CURLOPT_HEADER', true);
$curl->setOption('CURLOPT_RETURNTRANSFER', true);
$curl->setUrl($url);
$return = $curl->execute();
sleep(0.5); // for master slave: please wait before checking the results.
return $return;
}
/**
* Test helper to check for paginated seo pages.
*/
private function assertGeneratedPages()
{
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` LIKE '{$this->seoUrl}'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}%pgNr%'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}1/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}2/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}3/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}4/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}5/'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEquals(1, count($res));
}
/**
* Test helper.
*
* @return array
*/
private function getCategorySeoEntries()
{
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" .
" AND oxtype = 'oxcategory'";
return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
}
/**
* Test helper.
*/
private function clearProxyCache()
{
$cacheService = oxNew(\OxidEsales\TestingLibrary\Services\Library\Cache::class);
$cacheService->clearReverseProxyCache();
}
}
| Java |
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <vgui/IBorder.h>
#include <vgui/IInputInternal.h>
#include <vgui/IPanel.h>
#include <vgui/IScheme.h>
#include <vgui/IVGui.h>
#include <vgui/KeyCode.h>
#include <KeyValues.h>
#include <vgui/MouseCode.h>
#include <vgui/ISurface.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/Controls.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/PropertySheet.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/ToolWindow.h>
#include <vgui_controls/TextImage.h>
#include <vgui_controls/ImagePanel.h>
#include <vgui_controls/PropertyPage.h>
#include "vgui_controls/AnimationController.h"
#include "strtools_local.h" // TODO: temp
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui2;
namespace vgui2
{
class ContextLabel : public Label
{
DECLARE_CLASS_SIMPLE(ContextLabel, Label);
public:
ContextLabel(Button *parent, char const *panelName, char const *text)
: BaseClass((Panel *)parent, panelName, text),
m_pTabButton(parent)
{
SetBlockDragChaining(true);
}
virtual void OnMousePressed(MouseCode code)
{
if(m_pTabButton)
{
m_pTabButton->FireActionSignal();
}
}
virtual void OnMouseReleased(MouseCode code)
{
BaseClass::OnMouseReleased(code);
if(GetParent())
{
GetParent()->OnCommand("ShowContextMenu");
}
}
virtual void ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
HFont marlett = pScheme->GetFont("Marlett");
SetFont(marlett);
SetTextInset(0, 0);
SetContentAlignment(Label::a_northwest);
if(GetParent())
{
SetFgColor(pScheme->GetColor("Button.TextColor", GetParent()->GetFgColor()));
SetBgColor(GetParent()->GetBgColor());
}
}
private:
Button *m_pTabButton;
};
//-----------------------------------------------------------------------------
// Purpose: Helper for drag drop
// Input : msglist -
// Output : static PropertySheet
//-----------------------------------------------------------------------------
static PropertySheet *IsDroppingSheet(CUtlVector<KeyValues *> &msglist)
{
if(msglist.Count() == 0)
return NULL;
KeyValues *data = msglist[0];
PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet"));
if(sheet)
return sheet;
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: A single tab
//-----------------------------------------------------------------------------
class PageTab : public Button
{
DECLARE_CLASS_SIMPLE(PageTab, Button);
private:
bool _active;
SDK_Color _textColor;
SDK_Color _dimTextColor;
int m_bMaxTabWidth;
IBorder *m_pActiveBorder;
IBorder *m_pNormalBorder;
PropertySheet *m_pParent;
Panel *m_pPage;
ImagePanel *m_pImage;
char *m_pszImageName;
bool m_bShowContextLabel;
ContextLabel *m_pContextLabel;
public:
PageTab(PropertySheet *parent, const char *panelName, const char *text, char const *imageName, int maxTabWidth, Panel *page, bool showContextButton)
: Button((Panel *)parent, panelName, text),
m_pParent(parent),
m_pPage(page),
m_pImage(0),
m_pszImageName(0),
m_bShowContextLabel(showContextButton)
{
SetCommand(new KeyValues("TabPressed"));
_active = false;
m_bMaxTabWidth = maxTabWidth;
SetDropEnabled(true);
SetDragEnabled(m_pParent->IsDraggableTab());
if(imageName)
{
m_pImage = new ImagePanel(this, text);
int buflen = Q_strlen(imageName) + 1;
m_pszImageName = new char[buflen];
Q_strncpy(m_pszImageName, imageName, buflen);
}
SetMouseClickEnabled(MOUSE_RIGHT, true);
m_pContextLabel = m_bShowContextLabel ? new ContextLabel(this, "Context", "9") : NULL;
REGISTER_COLOR_AS_OVERRIDABLE(_textColor, "selectedcolor");
REGISTER_COLOR_AS_OVERRIDABLE(_dimTextColor, "unselectedcolor");
}
~PageTab()
{
delete[] m_pszImageName;
}
virtual void Paint()
{
BaseClass::Paint();
}
virtual bool IsDroppable(CUtlVector<KeyValues *> &msglist)
{
// It's never droppable, but should activate
FireActionSignal();
SetSelected(true);
Repaint();
if(!GetParent())
return false;
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
return GetParent()->IsDroppable(msglist);
}
// Defer to active page...
Panel *active = m_pParent->GetActivePage();
if(!active || !active->IsDroppable(msglist))
return false;
return active->IsDroppable(msglist);
}
virtual void OnDroppablePanelPaint(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
Panel *target = GetParent()->GetDropTarget(msglist);
if(target)
{
// Fixme, mouse pos could be wrong...
target->OnDroppablePanelPaint(msglist, dragPanels);
return;
}
}
// Just highlight the tab if dropping onto active page via the tab
BaseClass::OnDroppablePanelPaint(msglist, dragPanels);
}
virtual void OnPanelDropped(CUtlVector<KeyValues *> &msglist)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
Panel *target = GetParent()->GetDropTarget(msglist);
if(target)
{
// Fixme, mouse pos could be wrong...
target->OnPanelDropped(msglist);
}
}
// Defer to active page...
Panel *active = m_pParent->GetActivePage();
if(!active || !active->IsDroppable(msglist))
return;
active->OnPanelDropped(msglist);
}
virtual void OnDragFailed(CUtlVector<KeyValues *> &msglist)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
return;
// Create a new property sheet
if(m_pParent->IsDraggableTab())
{
if(msglist.Count() == 1)
{
KeyValues *data = msglist[0];
int screenx = data->GetInt("screenx");
int screeny = data->GetInt("screeny");
// m_pParent->ScreenToLocal( screenx, screeny );
if(!m_pParent->IsWithin(screenx, screeny))
{
Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage"));
PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet"));
char const *title = data->GetString("tabname", "");
if(!page || !sheet)
return;
// Can only create if sheet was part of a ToolWindow derived object
ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent());
if(tw)
{
IToolWindowFactory *factory = tw->GetToolWindowFactory();
if(factory)
{
bool hasContextMenu = sheet->PageHasContextMenu(page);
sheet->RemovePage(page);
factory->InstanceToolWindow(tw->GetParent(), sheet->ShouldShowContextButtons(), page, title, hasContextMenu);
if(sheet->GetNumPages() == 0)
{
tw->MarkForDeletion();
}
}
}
}
}
}
}
virtual void OnCreateDragData(KeyValues *msg)
{
Assert(m_pParent->IsDraggableTab());
msg->SetPtr("propertypage", m_pPage);
msg->SetPtr("propertysheet", m_pParent);
char sz[256];
GetText(sz, sizeof(sz));
msg->SetString("tabname", sz);
msg->SetString("text", sz);
}
virtual void ApplySchemeSettings(IScheme *pScheme)
{
// set up the scheme settings
Button::ApplySchemeSettings(pScheme);
_textColor = GetSchemeColor("PropertySheet.SelectedTextColor", GetFgColor(), pScheme);
_dimTextColor = GetSchemeColor("PropertySheet.TextColor", GetFgColor(), pScheme);
m_pActiveBorder = pScheme->GetBorder("TabActiveBorder");
m_pNormalBorder = pScheme->GetBorder("TabBorder");
if(m_pImage)
{
ClearImages();
m_pImage->SetImage(scheme()->GetImage(m_pszImageName, false));
AddImage(m_pImage->GetImage(), 2);
int w, h;
m_pImage->GetSize(w, h);
w += m_pContextLabel ? 10 : 0;
if(m_pContextLabel)
{
m_pImage->SetPos(10, 0);
}
SetSize(w + 4, h + 2);
}
else
{
int wide, tall;
int contentWide, contentTall;
GetSize(wide, tall);
GetContentSize(contentWide, contentTall);
wide = std::max(m_bMaxTabWidth, contentWide + 10); // 10 = 5 pixels margin on each side
wide += m_pContextLabel ? 10 : 0;
SetSize(wide, tall);
}
if(m_pContextLabel)
{
SetTextInset(12, 0);
}
}
virtual void OnCommand(char const *cmd)
{
if(!Q_stricmp(cmd, "ShowContextMenu"))
{
KeyValues *kv = new KeyValues("OpenContextMenu");
kv->SetPtr("page", m_pPage);
kv->SetPtr("contextlabel", m_pContextLabel);
PostActionSignal(kv);
return;
}
BaseClass::OnCommand(cmd);
}
IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus)
{
if(_active)
{
return m_pActiveBorder;
}
return m_pNormalBorder;
}
virtual SDK_Color GetButtonFgColor()
{
if(_active)
{
return _textColor;
}
else
{
return _dimTextColor;
}
}
virtual void SetActive(bool state)
{
_active = state;
InvalidateLayout();
Repaint();
}
virtual bool CanBeDefaultButton(void)
{
return false;
}
//Fire action signal when mouse is pressed down instead of on release.
virtual void OnMousePressed(MouseCode code)
{
// check for context menu open
if(!IsEnabled())
return;
if(!IsMouseClickEnabled(code))
return;
if(IsUseCaptureMouseEnabled())
{
{
RequestFocus();
FireActionSignal();
SetSelected(true);
Repaint();
}
// lock mouse input to going to this button
input()->SetMouseCapture(GetVPanel());
}
}
virtual void OnMouseReleased(MouseCode code)
{
// ensure mouse capture gets released
if(IsUseCaptureMouseEnabled())
{
input()->SetMouseCapture(NULL_HANDLE);
}
// make sure the button gets unselected
SetSelected(false);
Repaint();
if(code == MOUSE_RIGHT)
{
KeyValues *kv = new KeyValues("OpenContextMenu");
kv->SetPtr("page", m_pPage);
kv->SetPtr("contextlabel", m_pContextLabel);
PostActionSignal(kv);
}
}
virtual void PerformLayout()
{
BaseClass::PerformLayout();
if(m_pContextLabel)
{
int w, h;
GetSize(w, h);
m_pContextLabel->SetBounds(0, 0, 10, h);
}
}
};
}; // namespace vgui2
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
PropertySheet::PropertySheet(
Panel *parent,
const char *panelName,
bool draggableTabs /*= false*/)
: BaseClass(parent, panelName)
{
_activePage = NULL;
_activeTab = NULL;
_tabWidth = 64;
_activeTabIndex = 0;
_showTabs = true;
_combo = NULL;
_tabFocus = false;
m_flPageTransitionEffectTime = 0.0f;
m_bSmallTabs = false;
m_tabFont = 0;
m_bDraggableTabs = draggableTabs;
if(m_bDraggableTabs)
{
SetDropEnabled(true);
}
m_bKBNavigationEnabled = true;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor, associates pages with a combo box
//-----------------------------------------------------------------------------
PropertySheet::PropertySheet(Panel *parent, const char *panelName, ComboBox *combo)
: BaseClass(parent, panelName)
{
_activePage = NULL;
_activeTab = NULL;
_tabWidth = 64;
_activeTabIndex = 0;
_combo = combo;
_combo->AddActionSignalTarget(this);
_showTabs = false;
_tabFocus = false;
m_flPageTransitionEffectTime = 0.0f;
m_bSmallTabs = false;
m_tabFont = 0;
m_bDraggableTabs = false;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
PropertySheet::~PropertySheet()
{
}
//-----------------------------------------------------------------------------
// Purpose: ToolWindow uses this to drag tools from container to container by dragging the tab
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::IsDraggableTab() const
{
return m_bDraggableTabs;
}
void PropertySheet::SetDraggableTabs(bool state)
{
m_bDraggableTabs = state;
}
//-----------------------------------------------------------------------------
// Purpose: Lower profile tabs
// Input : state -
//-----------------------------------------------------------------------------
void PropertySheet::SetSmallTabs(bool state)
{
m_bSmallTabs = state;
m_tabFont = scheme()->GetIScheme(GetScheme())->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default");
int c = m_PageTabs.Count();
for(int i = 0; i < c; ++i)
{
PageTab *tab = m_PageTabs[i];
Assert(tab);
tab->SetFont(m_tabFont);
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::IsSmallTabs() const
{
return m_bSmallTabs;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : state -
//-----------------------------------------------------------------------------
void PropertySheet::ShowContextButtons(bool state)
{
m_bContextButton = state;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::ShouldShowContextButtons() const
{
return m_bContextButton;
}
int PropertySheet::FindPage(Panel *page) const
{
int c = m_Pages.Count();
for(int i = 0; i < c; ++i)
{
if(m_Pages[i].page == page)
return i;
}
return m_Pages.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Purpose: adds a page to the sheet
//-----------------------------------------------------------------------------
void PropertySheet::AddPage(Panel *page, const char *title, char const *imageName /*= NULL*/, bool bHasContextMenu /*= false*/)
{
if(!page)
return;
// don't add the page if we already have it
if(FindPage(page) != m_Pages.InvalidIndex())
return;
PageTab *tab = new PageTab(this, "tab", title, imageName, _tabWidth, page, m_bContextButton && bHasContextMenu);
if(m_bDraggableTabs)
{
tab->SetDragEnabled(true);
}
tab->SetFont(m_tabFont);
if(_showTabs)
{
tab->AddActionSignalTarget(this);
}
else if(_combo)
{
_combo->AddItem(title, NULL);
}
m_PageTabs.AddToTail(tab);
Page_t info;
info.page = page;
info.contextMenu = m_bContextButton && bHasContextMenu;
m_Pages.AddToTail(info);
page->SetParent(this);
page->AddActionSignalTarget(this);
PostMessage(page, new KeyValues("ResetData"));
page->SetVisible(false);
InvalidateLayout();
if(!_activePage)
{
// first page becomes the active page
ChangeActiveTab(0);
if(_activePage)
{
_activePage->RequestFocus(0);
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::SetActivePage(Panel *page)
{
// walk the list looking for this page
int index = FindPage(page);
if(!m_Pages.IsValidIndex(index))
return;
ChangeActiveTab(index);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::SetTabWidth(int pixels)
{
_tabWidth = pixels;
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: reloads the data in all the property page
//-----------------------------------------------------------------------------
void PropertySheet::ResetAllData()
{
// iterate all the dialogs resetting them
for(int i = 0; i < m_Pages.Count(); i++)
{
ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ResetData"), GetVPanel());
}
}
//-----------------------------------------------------------------------------
// Purpose: Applies any changes made by the dialog
//-----------------------------------------------------------------------------
void PropertySheet::ApplyChanges()
{
// iterate all the dialogs resetting them
for(int i = 0; i < m_Pages.Count(); i++)
{
ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ApplyChanges"), GetVPanel());
}
}
//-----------------------------------------------------------------------------
// Purpose: gets a pointer to the currently active page
//-----------------------------------------------------------------------------
Panel *PropertySheet::GetActivePage()
{
return _activePage;
}
//-----------------------------------------------------------------------------
// Purpose: gets a pointer to the currently active tab
//-----------------------------------------------------------------------------
Panel *PropertySheet::GetActiveTab()
{
return _activeTab;
}
//-----------------------------------------------------------------------------
// Purpose: returns the number of panels in the sheet
//-----------------------------------------------------------------------------
int PropertySheet::GetNumPages()
{
return m_Pages.Count();
}
//-----------------------------------------------------------------------------
// Purpose: returns the name contained in the active tab
// Input : a text buffer to contain the output
//-----------------------------------------------------------------------------
void PropertySheet::GetActiveTabTitle(char *textOut, int bufferLen)
{
if(_activeTab)
_activeTab->GetText(textOut, bufferLen);
}
//-----------------------------------------------------------------------------
// Purpose: returns the name contained in the active tab
// Input : a text buffer to contain the output
//-----------------------------------------------------------------------------
bool PropertySheet::GetTabTitle(int i, char *textOut, int bufferLen)
{
if(i < 0 && i > m_PageTabs.Count())
{
return false;
}
m_PageTabs[i]->GetText(textOut, bufferLen);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the index of the currently active page
//-----------------------------------------------------------------------------
int PropertySheet::GetActivePageNum()
{
for(int i = 0; i < m_Pages.Count(); i++)
{
if(m_Pages[i].page == _activePage)
{
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Forwards focus requests to current active page
//-----------------------------------------------------------------------------
void PropertySheet::RequestFocus(int direction)
{
if(direction == -1 || direction == 0)
{
if(_activePage)
{
_activePage->RequestFocus(direction);
_tabFocus = false;
}
}
else
{
if(_showTabs && _activeTab)
{
_activeTab->RequestFocus(direction);
_tabFocus = true;
}
else if(_activePage)
{
_activePage->RequestFocus(direction);
_tabFocus = false;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: moves focus back
//-----------------------------------------------------------------------------
bool PropertySheet::RequestFocusPrev(VPANEL panel)
{
if(_tabFocus || !_showTabs || !_activeTab)
{
_tabFocus = false;
return BaseClass::RequestFocusPrev(panel);
}
else
{
if(GetVParent())
{
PostMessage(GetVParent(), new KeyValues("FindDefaultButton"));
}
_activeTab->RequestFocus(-1);
_tabFocus = true;
return true;
}
}
//-----------------------------------------------------------------------------
// Purpose: moves focus forward
//-----------------------------------------------------------------------------
bool PropertySheet::RequestFocusNext(VPANEL panel)
{
if(!_tabFocus || !_activePage)
{
return BaseClass::RequestFocusNext(panel);
}
else
{
if(!_activeTab)
{
return BaseClass::RequestFocusNext(panel);
}
else
{
_activePage->RequestFocus(1);
_tabFocus = false;
return true;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Gets scheme settings
//-----------------------------------------------------------------------------
void PropertySheet::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
// a little backwards-compatibility with old scheme files
IBorder *pBorder = pScheme->GetBorder("PropertySheetBorder");
if(pBorder == pScheme->GetBorder("Default"))
{
// get the old name
pBorder = pScheme->GetBorder("RaisedBorder");
}
SetBorder(pBorder);
m_flPageTransitionEffectTime = atof(pScheme->GetResourceString("PropertySheet.TransitionEffectTime"));
m_tabFont = pScheme->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default");
}
//-----------------------------------------------------------------------------
// Purpose: Paint our border specially, with the tabs in mind
//-----------------------------------------------------------------------------
void PropertySheet::PaintBorder()
{
IBorder *border = GetBorder();
if(!border)
return;
// draw the border, but with a break at the active tab
int px = 0, py = 0, pwide = 0, ptall = 0;
if(_activeTab)
{
_activeTab->GetBounds(px, py, pwide, ptall);
ptall -= 1;
}
// draw the border underneath the buttons, with a break
int wide, tall;
GetSize(wide, tall);
border->Paint(0, py + ptall, wide, tall, IBorder::SIDE_TOP, px + 1, px + pwide - 1);
}
//-----------------------------------------------------------------------------
// Purpose: Lays out the dialog
//-----------------------------------------------------------------------------
void PropertySheet::PerformLayout()
{
BaseClass::PerformLayout();
int x, y, wide, tall;
GetBounds(x, y, wide, tall);
if(_activePage)
{
int tabHeight = IsSmallTabs() ? 14 : 28;
if(_showTabs)
{
_activePage->SetBounds(0, tabHeight, wide, tall - tabHeight);
}
else
{
_activePage->SetBounds(0, 0, wide, tall);
}
_activePage->InvalidateLayout();
}
int xtab;
int limit = m_PageTabs.Count();
xtab = 0;
// draw the visible tabs
if(_showTabs)
{
for(int i = 0; i < limit; i++)
{
int tabHeight = IsSmallTabs() ? 13 : 27;
int width, tall;
m_PageTabs[i]->GetSize(width, tall);
if(m_PageTabs[i] == _activeTab)
{
// active tab is taller
_activeTab->SetBounds(xtab, 2, width, tabHeight);
}
else
{
m_PageTabs[i]->SetBounds(xtab, 4, width, tabHeight - 2);
}
m_PageTabs[i]->SetVisible(true);
xtab += (width + 1);
}
}
else
{
for(int i = 0; i < limit; i++)
{
m_PageTabs[i]->SetVisible(false);
}
}
// ensure draw order (page drawing over all the tabs except one)
if(_activePage)
{
_activePage->MoveToFront();
_activePage->Repaint();
}
if(_activeTab)
{
_activeTab->MoveToFront();
_activeTab->Repaint();
}
}
//-----------------------------------------------------------------------------
// Purpose: Switches the active panel
//-----------------------------------------------------------------------------
void PropertySheet::OnTabPressed(Panel *panel)
{
// look for the tab in the list
for(int i = 0; i < m_PageTabs.Count(); i++)
{
if(m_PageTabs[i] == panel)
{
// flip to the new tab
ChangeActiveTab(i);
return;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: returns the panel associated with index i
// Input : the index of the panel to return
//-----------------------------------------------------------------------------
Panel *PropertySheet::GetPage(int i)
{
if(i < 0 && i > m_Pages.Count())
{
return NULL;
}
return m_Pages[i].page;
}
//-----------------------------------------------------------------------------
// Purpose: disables page by name
//-----------------------------------------------------------------------------
void PropertySheet::DisablePage(const char *title)
{
SetPageEnabled(title, false);
}
//-----------------------------------------------------------------------------
// Purpose: enables page by name
//-----------------------------------------------------------------------------
void PropertySheet::EnablePage(const char *title)
{
SetPageEnabled(title, true);
}
//-----------------------------------------------------------------------------
// Purpose: enabled or disables page by name
//-----------------------------------------------------------------------------
void PropertySheet::SetPageEnabled(const char *title, bool state)
{
for(int i = 0; i < m_PageTabs.Count(); i++)
{
if(_showTabs)
{
char tmp[50];
m_PageTabs[i]->GetText(tmp, 50);
if(!strnicmp(title, tmp, strlen(tmp)))
{
m_PageTabs[i]->SetEnabled(state);
}
}
else
{
_combo->SetItemEnabled(title, state);
}
}
}
void PropertySheet::RemoveAllPages()
{
int c = m_Pages.Count();
for(int i = c - 1; i >= 0; --i)
{
RemovePage(m_Pages[i].page);
}
}
//-----------------------------------------------------------------------------
// Purpose: deletes the page associated with panel
// Input : *panel - the panel of the page to remove
//-----------------------------------------------------------------------------
void PropertySheet::RemovePage(Panel *panel)
{
int location = FindPage(panel);
if(location == m_Pages.InvalidIndex())
return;
// Since it's being deleted, don't animate!!!
m_hPreviouslyActivePage = NULL;
_activeTab = NULL;
// ASSUMPTION = that the number of pages equals number of tabs
if(_showTabs)
{
m_PageTabs[location]->RemoveActionSignalTarget(this);
}
// now remove the tab
PageTab *tab = m_PageTabs[location];
m_PageTabs.Remove(location);
tab->MarkForDeletion();
// Remove from page list
m_Pages.Remove(location);
// Unparent
panel->SetParent((Panel *)NULL);
if(_activePage == panel)
{
_activePage = NULL;
// if this page is currently active, backup to the page before this.
ChangeActiveTab(std::max(location - 1, 0));
}
PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose: deletes the page associated with panel
// Input : *panel - the panel of the page to remove
//-----------------------------------------------------------------------------
void PropertySheet::DeletePage(Panel *panel)
{
Assert(panel);
RemovePage(panel);
panel->MarkForDeletion();
}
//-----------------------------------------------------------------------------
// Purpose: flips to the new tab, sending out all the right notifications
// flipping to a tab activates the tab.
//-----------------------------------------------------------------------------
void PropertySheet::ChangeActiveTab(int index)
{
if(!m_Pages.IsValidIndex(index))
{
_activeTab = NULL;
if(m_Pages.Count() > 0)
{
_activePage = NULL;
ChangeActiveTab(0);
}
return;
}
if(m_Pages[index].page == _activePage)
{
if(_activeTab)
{
_activeTab->RequestFocus();
}
_tabFocus = true;
return;
}
int c = m_Pages.Count();
for(int i = 0; i < c; ++i)
{
m_Pages[i].page->SetVisible(false);
}
m_hPreviouslyActivePage = _activePage;
// notify old page
if(_activePage)
{
ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageHide"), GetVPanel());
KeyValues *msg = new KeyValues("PageTabActivated");
msg->SetPtr("panel", (Panel *)NULL);
ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel());
}
if(_activeTab)
{
//_activeTabIndex=index;
_activeTab->SetActive(false);
// does the old tab have the focus?
_tabFocus = _activeTab->HasFocus();
}
else
{
_tabFocus = false;
}
// flip page
_activePage = m_Pages[index].page;
_activeTab = m_PageTabs[index];
_activeTabIndex = index;
_activePage->SetVisible(true);
_activePage->MoveToFront();
_activeTab->SetVisible(true);
_activeTab->MoveToFront();
_activeTab->SetActive(true);
if(_tabFocus)
{
// if a tab already has focused,give the new tab the focus
_activeTab->RequestFocus();
}
else
{
// otherwise, give the focus to the page
_activePage->RequestFocus();
}
if(!_showTabs)
{
_combo->ActivateItemByRow(index);
}
_activePage->MakeReadyForUse();
// transition effect
if(m_flPageTransitionEffectTime)
{
if(m_hPreviouslyActivePage.Get())
{
// fade out the previous page
GetAnimationController()->RunAnimationCommand(m_hPreviouslyActivePage, "Alpha", 0.0f, 0.0f, m_flPageTransitionEffectTime / 2, AnimationController::INTERPOLATOR_LINEAR);
}
// fade in the new page
_activePage->SetAlpha(0);
GetAnimationController()->RunAnimationCommand(_activePage, "Alpha", 255.0f, m_flPageTransitionEffectTime / 2, m_flPageTransitionEffectTime / 2, AnimationController::INTERPOLATOR_LINEAR);
}
else
{
if(m_hPreviouslyActivePage.Get())
{
// no transition, just hide the previous page
m_hPreviouslyActivePage->SetVisible(false);
}
_activePage->SetAlpha(255);
}
// notify
ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageShow"), GetVPanel());
KeyValues *msg = new KeyValues("PageTabActivated");
msg->SetPtr("panel", (Panel *)_activeTab);
ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel());
// tell parent
PostActionSignal(new KeyValues("PageChanged"));
// Repaint
InvalidateLayout();
Repaint();
}
//-----------------------------------------------------------------------------
// Purpose: Gets the panel with the specified hotkey, from the current page
//-----------------------------------------------------------------------------
Panel *PropertySheet::HasHotkey(wchar_t key)
{
if(!_activePage)
return NULL;
for(int i = 0; i < _activePage->GetChildCount(); i++)
{
Panel *hot = _activePage->GetChild(i)->HasHotkey(key);
if(hot)
{
return hot;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: catches the opencontextmenu event
//-----------------------------------------------------------------------------
void PropertySheet::OnOpenContextMenu(KeyValues *params)
{
// tell parent
KeyValues *kv = params->MakeCopy();
PostActionSignal(kv);
Panel *page = reinterpret_cast<Panel *>(params->GetPtr("page"));
if(page)
{
PostMessage(page->GetVPanel(), params->MakeCopy());
}
}
//-----------------------------------------------------------------------------
// Purpose: Handle key presses, through tabs.
//-----------------------------------------------------------------------------
void PropertySheet::OnKeyCodeTyped(KeyCode code)
{
bool shift = (input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT));
bool ctrl = (input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL));
bool alt = (input()->IsKeyDown(KEY_LALT) || input()->IsKeyDown(KEY_RALT));
if(ctrl && shift && alt && code == KEY_B)
{
// enable build mode
EditablePanel *ep = dynamic_cast<EditablePanel *>(GetActivePage());
if(ep)
{
ep->ActivateBuildMode();
return;
}
}
if(IsKBNavigationEnabled())
{
switch(code)
{
// for now left and right arrows just open or close submenus if they are there.
case KEY_RIGHT:
{
ChangeActiveTab(_activeTabIndex + 1);
break;
}
case KEY_LEFT:
{
ChangeActiveTab(_activeTabIndex - 1);
break;
}
default:
BaseClass::OnKeyCodeTyped(code);
break;
}
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: Called by the associated combo box (if in that mode), changes the current panel
//-----------------------------------------------------------------------------
void PropertySheet::OnTextChanged(Panel *panel, const wchar_t *wszText)
{
if(panel == _combo)
{
wchar_t tabText[30];
for(int i = 0; i < m_PageTabs.Count(); i++)
{
tabText[0] = 0;
m_PageTabs[i]->GetText(tabText, 30);
if(!wcsicmp(wszText, tabText))
{
ChangeActiveTab(i);
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnCommand(const char *command)
{
// propogate the close command to our parent
if(!stricmp(command, "Close") && GetVParent())
{
CallParentFunction(new KeyValues("Command", "command", command));
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnApplyButtonEnable()
{
// tell parent
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnCurrentDefaultButtonSet(Panel *defaultButton)
{
// forward the message up
if(GetVParent())
{
KeyValues *msg = new KeyValues("CurrentDefaultButtonSet");
msg->SetPtr("button", defaultButton);
PostMessage(GetVParent(), msg);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnDefaultButtonSet(Panel *defaultButton)
{
// forward the message up
if(GetVParent())
{
KeyValues *msg = new KeyValues("DefaultButtonSet");
msg->SetPtr("button", defaultButton);
PostMessage(GetVParent(), msg);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnFindDefaultButton()
{
if(GetVParent())
{
PostMessage(GetVParent(), new KeyValues("FindDefaultButton"));
}
}
bool PropertySheet::PageHasContextMenu(Panel *page) const
{
int pageNum = FindPage(page);
if(pageNum == m_Pages.InvalidIndex())
return false;
return m_Pages[pageNum].contextMenu;
}
void PropertySheet::OnPanelDropped(CUtlVector<KeyValues *> &msglist)
{
if(msglist.Count() != 1)
{
return;
}
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
{
// Defer to active page
if(_activePage && _activePage->IsDropEnabled())
{
return _activePage->OnPanelDropped(msglist);
}
return;
}
KeyValues *data = msglist[0];
Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage"));
char const *title = data->GetString("tabname", "");
if(!page || !sheet)
return;
// Can only create if sheet was part of a ToolWindow derived object
ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent());
if(tw)
{
IToolWindowFactory *factory = tw->GetToolWindowFactory();
if(factory)
{
bool showContext = sheet->PageHasContextMenu(page);
sheet->RemovePage(page);
if(sheet->GetNumPages() == 0)
{
tw->MarkForDeletion();
}
AddPage(page, title, NULL, showContext);
}
}
}
bool PropertySheet::IsDroppable(CUtlVector<KeyValues *> &msglist)
{
if(!m_bDraggableTabs)
return false;
if(msglist.Count() != 1)
{
return false;
}
int mx, my;
input()->GetCursorPos(mx, my);
ScreenToLocal(mx, my);
int tabHeight = IsSmallTabs() ? 14 : 28;
if(my > tabHeight)
return false;
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
{
return false;
}
if(sheet == this)
return false;
return true;
}
// Mouse is now over a droppable panel
void PropertySheet::OnDroppablePanelPaint(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels)
{
// Convert this panel's bounds to screen space
int x, y, w, h;
GetSize(w, h);
int tabHeight = IsSmallTabs() ? 14 : 28;
h = tabHeight + 4;
x = y = 0;
LocalToScreen(x, y);
surface()->DrawSetColor(GetDropFrameColor());
// Draw 2 pixel frame
surface()->DrawOutlinedRect(x, y, x + w, y + h);
surface()->DrawOutlinedRect(x + 1, y + 1, x + w - 1, y + h - 1);
if(!IsDroppable(msglist))
{
return;
}
if(!_showTabs)
{
return;
}
// Draw a fake new tab...
x = 0;
y = 2;
w = 1;
h = tabHeight;
int last = m_PageTabs.Count();
if(last != 0)
{
m_PageTabs[last - 1]->GetBounds(x, y, w, h);
}
// Compute left edge of "fake" tab
x += (w + 1);
// Compute size of new panel
KeyValues *data = msglist[0];
char const *text = data->GetString("tabname", "");
Assert(text);
PageTab *fakeTab = new PageTab(this, "FakeTab", text, NULL, _tabWidth, NULL, false);
fakeTab->SetBounds(x, 4, w, tabHeight - 4);
fakeTab->SetFont(m_tabFont);
SETUP_PANEL(fakeTab);
fakeTab->Repaint();
surface()->SolveTraverse(fakeTab->GetVPanel(), true);
surface()->PaintTraverse(fakeTab->GetVPanel());
delete fakeTab;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : state -
//-----------------------------------------------------------------------------
void PropertySheet::SetKBNavigationEnabled(bool state)
{
m_bKBNavigationEnabled = state;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::IsKBNavigationEnabled() const
{
return m_bKBNavigationEnabled;
}
| Java |
import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
"""
# features extension supports
features = ()
def __init__(self, parent, window):
self._parent = parent
self._window = window
self._application = self._parent._application
# create user interface
self._container = gtk.VBox(False, 5)
self._controls = gtk.HBox(False, 5)
separator = gtk.HSeparator()
# pack interface
self._container.pack_end(separator, False, False, 0)
self._container.pack_end(self._controls, False, False, 0)
def can_handle(self, uri):
"""Returns boolean denoting if specified URI can be handled by this extension"""
return False
def get_container(self):
"""Return container widget"""
return self._container
def get_information(self):
"""Returns information about extension"""
icon = None
name = None
return icon, name
def unmount(self, uri):
"""Method called by the mount manager for unmounting the selected URI"""
pass
def focus_object(self):
"""Method called by the mount manager for focusing main object"""
pass
@classmethod
def get_features(cls):
"""Returns set of features supported by extension"""
return cls.features
| Java |
<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_gantt.php');
$graph = new GanttGraph();
$graph->SetBox();
$graph->SetShadow();
// Add title and subtitle
$graph->title->Set("Example of captions");
$graph->title->SetFont(FF_ARIAL,FS_BOLD,12);
$graph->subtitle->Set("(ganttex16.php)");
// Show day, week and month scale
$graph->ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH);
// Set table title
$graph->scale->tableTitle->Set("(Rev: 1.22)");
$graph->scale->tableTitle->SetFont(FF_FONT1,FS_BOLD);
$graph->scale->SetTableTitleBackground("silver");
$graph->scale->tableTitle->Show();
// Use the short name of the month together with a 2 digit year
// on the month scale
$graph->scale->month->SetStyle(MONTHSTYLE_SHORTNAMEYEAR2);
$graph->scale->month->SetFontColor("white");
$graph->scale->month->SetBackgroundColor("blue");
// 0 % vertical label margin
$graph->SetLabelVMarginFactor(1);
// Format the bar for the first activity
// ($row,$title,$startdate,$enddate)
$activity = new GanttBar(0,"Project","2001-12-21","2002-01-07","[50%]");
// Yellow diagonal line pattern on a red background
$activity->SetPattern(BAND_RDIAG,"yellow");
$activity->SetFillColor("red");
// Set absolute height
$activity->SetHeight(10);
// Specify progress to 60%
$activity->progress->Set(0.6);
$activity->progress->SetPattern(BAND_HVCROSS,"blue");
// Format the bar for the second activity
// ($row,$title,$startdate,$enddate)
$activity2 = new GanttBar(1,"Project","2001-12-21","2002-01-02","[30%]");
// Yellow diagonal line pattern on a red background
$activity2->SetPattern(BAND_RDIAG,"yellow");
$activity2->SetFillColor("red");
// Set absolute height
$activity2->SetHeight(10);
// Specify progress to 30%
$activity2->progress->Set(0.3);
$activity2->progress->SetPattern(BAND_HVCROSS,"blue");
// Finally add the bar to the graph
$graph->Add($activity);
$graph->Add($activity2);
// Add a vertical line
$vline = new GanttVLine("2001-12-24","Phase 1");
$vline->SetDayOffset(0.5);
//$graph->Add($vline);
// ... and display it
$graph->Stroke();
?>
| Java |
/*! @license Firebase v4.3.1
Build: rev-b4fe95f
Terms: https://firebase.google.com/terms/ */
"use strict";
//# sourceMappingURL=requestmaker.js.map
| Java |
package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Vector3 implements Cloneable {
public double x;
public double y;
public double z;
public Vector3() {
this(0, 0, 0);
}
public Vector3(double x) {
this(x, 0, 0);
}
public Vector3(double x, double y) {
this(x, y, 0);
}
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getZ() {
return this.z;
}
public int getFloorX() {
return (int) Math.floor(this.x);
}
public int getFloorY() {
return (int) Math.floor(this.y);
}
public int getFloorZ() {
return (int) Math.floor(this.z);
}
public double getRight() {
return this.x;
}
public double getUp() {
return this.y;
}
public double getForward() {
return this.z;
}
public double getSouth() {
return this.x;
}
public double getWest() {
return this.z;
}
public Vector3 add(double x) {
return this.add(x, 0, 0);
}
public Vector3 add(double x, double y) {
return this.add(x, y, 0);
}
public Vector3 add(double x, double y, double z) {
return new Vector3(this.x + x, this.y + y, this.z + z);
}
public Vector3 add(Vector3 x) {
return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public Vector3 subtract() {
return this.subtract(0, 0, 0);
}
public Vector3 subtract(double x) {
return this.subtract(x, 0, 0);
}
public Vector3 subtract(double x, double y) {
return this.subtract(x, y, 0);
}
public Vector3 subtract(double x, double y, double z) {
return this.add(-x, -y, -z);
}
public Vector3 subtract(Vector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public Vector3 multiply(double number) {
return new Vector3(this.x * number, this.y * number, this.z * number);
}
public Vector3 divide(double number) {
return new Vector3(this.x / number, this.y / number, this.z / number);
}
public Vector3 ceil() {
return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z));
}
public Vector3 floor() {
return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
public Vector3 round() {
return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z));
}
public Vector3 abs() {
return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z));
}
public Vector3 getSide(BlockFace face) {
return this.getSide(face, 1);
}
public Vector3 getSide(BlockFace face, int step) {
return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step);
}
public Vector3 up() {
return up(1);
}
public Vector3 up(int step) {
return getSide(BlockFace.UP, step);
}
public Vector3 down() {
return down(1);
}
public Vector3 down(int step) {
return getSide(BlockFace.DOWN, step);
}
public Vector3 north() {
return north(1);
}
public Vector3 north(int step) {
return getSide(BlockFace.NORTH, step);
}
public Vector3 south() {
return south(1);
}
public Vector3 south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public Vector3 east() {
return east(1);
}
public Vector3 east(int step) {
return getSide(BlockFace.EAST, step);
}
public Vector3 west() {
return west(1);
}
public Vector3 west(int step) {
return getSide(BlockFace.WEST, step);
}
public double distance(Vector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distanceSquared(Vector3 pos) {
return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2);
}
public double maxPlainDistance() {
return this.maxPlainDistance(0, 0);
}
public double maxPlainDistance(double x) {
return this.maxPlainDistance(x, 0);
}
public double maxPlainDistance(double x, double z) {
return Math.max(Math.abs(this.x - x), Math.abs(this.z - z));
}
public double maxPlainDistance(Vector2 vector) {
return this.maxPlainDistance(vector.x, vector.y);
}
public double maxPlainDistance(Vector3 x) {
return this.maxPlainDistance(x.x, x.z);
}
public double length() {
return Math.sqrt(this.lengthSquared());
}
public double lengthSquared() {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
public Vector3 normalize() {
double len = this.lengthSquared();
if (len > 0) {
return this.divide(Math.sqrt(len));
}
return new Vector3(0, 0, 0);
}
public double dot(Vector3 v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
public Vector3 cross(Vector3 v) {
return new Vector3(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
/**
* Returns a new vector with x value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithXValue(Vector3 v, double x) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (xDiff * xDiff < 0.0000001) {
return null;
}
double f = (x - this.x) / xDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with y value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithYValue(Vector3 v, double y) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (yDiff * yDiff < 0.0000001) {
return null;
}
double f = (y - this.y) / yDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with z value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithZValue(Vector3 v, double z) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (zDiff * zDiff < 0.0000001) {
return null;
}
double f = (z - this.z) / zDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
public Vector3 setComponents(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public String toString() {
return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")";
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector3)) {
return false;
}
Vector3 other = (Vector3) obj;
return this.x == other.x && this.y == other.y && this.z == other.z;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32);
return hash;
}
public int rawHashCode() {
return super.hashCode();
}
@Override
public Vector3 clone() {
try {
return (Vector3) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public Vector3f asVector3f() {
return new Vector3f((float) this.x, (float) this.y, (float) this.z);
}
public BlockVector3 asBlockVector3() {
return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
} | Java |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
class FileListTreeItem : public TreeViewItem,
private TimeSliceClient,
private AsyncUpdater,
private ChangeListener
{
public:
FileListTreeItem (FileTreeComponent& treeComp,
DirectoryContentsList* parentContents,
int indexInContents,
const File& f,
TimeSliceThread& t)
: file (f),
owner (treeComp),
parentContentsList (parentContents),
indexInContentsList (indexInContents),
subContentsList (nullptr, false),
thread (t)
{
DirectoryContentsList::FileInfo fileInfo;
if (parentContents != nullptr
&& parentContents->getFileInfo (indexInContents, fileInfo))
{
fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
isDirectory = fileInfo.isDirectory;
}
else
{
isDirectory = true;
}
}
~FileListTreeItem() override
{
thread.removeTimeSliceClient (this);
clearSubItems();
removeSubContentsList();
}
//==============================================================================
bool mightContainSubItems() override { return isDirectory; }
String getUniqueName() const override { return file.getFullPathName(); }
int getItemHeight() const override { return owner.getItemHeight(); }
var getDragSourceDescription() override { return owner.getDragAndDropDescription(); }
void itemOpennessChanged (bool isNowOpen) override
{
if (isNowOpen)
{
clearSubItems();
isDirectory = file.isDirectory();
if (isDirectory)
{
if (subContentsList == nullptr)
{
jassert (parentContentsList != nullptr);
auto l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
l->setDirectory (file,
parentContentsList->isFindingDirectories(),
parentContentsList->isFindingFiles());
setSubContentsList (l, true);
}
changeListenerCallback (nullptr);
}
}
}
void removeSubContentsList()
{
if (subContentsList != nullptr)
{
subContentsList->removeChangeListener (this);
subContentsList.reset();
}
}
void setSubContentsList (DirectoryContentsList* newList, const bool canDeleteList)
{
removeSubContentsList();
subContentsList = OptionalScopedPointer<DirectoryContentsList> (newList, canDeleteList);
newList->addChangeListener (this);
}
bool selectFile (const File& target)
{
if (file == target)
{
setSelected (true, true);
return true;
}
if (target.isAChildOf (file))
{
setOpen (true);
for (int maxRetries = 500; --maxRetries > 0;)
{
for (int i = 0; i < getNumSubItems(); ++i)
if (auto* f = dynamic_cast<FileListTreeItem*> (getSubItem (i)))
if (f->selectFile (target))
return true;
// if we've just opened and the contents are still loading, wait for it..
if (subContentsList != nullptr && subContentsList->isStillLoading())
{
Thread::sleep (10);
rebuildItemsFromContentList();
}
else
{
break;
}
}
}
return false;
}
void changeListenerCallback (ChangeBroadcaster*) override
{
rebuildItemsFromContentList();
}
void rebuildItemsFromContentList()
{
clearSubItems();
if (isOpen() && subContentsList != nullptr)
{
for (int i = 0; i < subContentsList->getNumFiles(); ++i)
addSubItem (new FileListTreeItem (owner, subContentsList, i,
subContentsList->getFile(i), thread));
}
}
void paintItem (Graphics& g, int width, int height) override
{
ScopedLock lock (iconUpdate);
if (file != File())
{
updateIcon (true);
if (icon.isNull())
thread.addTimeSliceClient (this);
}
owner.getLookAndFeel().drawFileBrowserRow (g, width, height,
file, file.getFileName(),
&icon, fileSize, modTime,
isDirectory, isSelected(),
indexInContentsList, owner);
}
void itemClicked (const MouseEvent& e) override
{
owner.sendMouseClickMessage (file, e);
}
void itemDoubleClicked (const MouseEvent& e) override
{
TreeViewItem::itemDoubleClicked (e);
owner.sendDoubleClickMessage (file);
}
void itemSelectionChanged (bool) override
{
owner.sendSelectionChangeMessage();
}
int useTimeSlice() override
{
updateIcon (false);
return -1;
}
void handleAsyncUpdate() override
{
owner.repaint();
}
const File file;
private:
FileTreeComponent& owner;
DirectoryContentsList* parentContentsList;
int indexInContentsList;
OptionalScopedPointer<DirectoryContentsList> subContentsList;
bool isDirectory;
TimeSliceThread& thread;
CriticalSection iconUpdate;
Image icon;
String fileSize, modTime;
void updateIcon (const bool onlyUpdateIfCached)
{
if (icon.isNull())
{
auto hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
auto im = ImageCache::getFromHashCode (hashCode);
if (im.isNull() && ! onlyUpdateIfCached)
{
im = juce_createIconForFile (file);
if (im.isValid())
ImageCache::addImageToCache (im, hashCode);
}
if (im.isValid())
{
{
ScopedLock lock (iconUpdate);
icon = im;
}
triggerAsyncUpdate();
}
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem)
};
//==============================================================================
FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
: DirectoryContentsDisplayComponent (listToShow),
itemHeight (22)
{
setRootItemVisible (false);
refresh();
}
FileTreeComponent::~FileTreeComponent()
{
deleteRootItem();
}
void FileTreeComponent::refresh()
{
deleteRootItem();
auto root = new FileListTreeItem (*this, nullptr, 0, directoryContentsList.getDirectory(),
directoryContentsList.getTimeSliceThread());
root->setSubContentsList (&directoryContentsList, false);
setRootItem (root);
}
//==============================================================================
File FileTreeComponent::getSelectedFile (const int index) const
{
if (auto* item = dynamic_cast<const FileListTreeItem*> (getSelectedItem (index)))
return item->file;
return {};
}
void FileTreeComponent::deselectAllFiles()
{
clearSelectedItems();
}
void FileTreeComponent::scrollToTop()
{
getViewport()->getVerticalScrollBar().setCurrentRangeStart (0);
}
void FileTreeComponent::setDragAndDropDescription (const String& description)
{
dragAndDropDescription = description;
}
void FileTreeComponent::setSelectedFile (const File& target)
{
if (auto* t = dynamic_cast<FileListTreeItem*> (getRootItem()))
if (! t->selectFile (target))
clearSelectedItems();
}
void FileTreeComponent::setItemHeight (int newHeight)
{
if (itemHeight != newHeight)
{
itemHeight = newHeight;
if (auto* root = getRootItem())
root->treeHasChanged();
}
}
} // namespace juce
| Java |
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Newsletter\Controller\Adminhtml\Template;
class NewAction extends \Magento\Newsletter\Controller\Adminhtml\Template
{
/**
* Create new Newsletter Template
*
* @return void
*/
public function execute()
{
$this->_forward('edit');
}
}
| Java |
//
// StyleDressApp.h
// DressApp
//
// Created by Javier Sanchez Sierra on 12/24/11.
// Copyright (c) 2011 Javier Sanchez Sierra. All rights reserved.
//
// This file is part of DressApp.
// DressApp 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.
//
// DressApp 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//https://github.com/jsanchezsierra/DressApp
#import <Foundation/Foundation.h>
typedef enum {
StyleTypeVintage = 1,
StyleTypeModern =2,
} StyleType;
typedef enum {
StyleColorMainNavigationBar,
StyleColorMainToolBar,
StyleColorPREmptyCategoria,
StyleColorPRHeader,
StyleColorPRBackground,
StyleColorPRSectionSeparator,
StyleColorPRDetailHeader,
StyleColorPRDetailMarcaTitle,
StyleColorPRDetailMarcaName,
StyleColorPRDetailPrecio,
StyleColorPRDetailEtiqueta,
StyleColorPRDetailBackground,
StyleColorPRDetailBackgroundPrenda,
StyleColorPRNotasSectionTitle,
StyleColorPRNotasCell,
StyleColorPRNotasBtnFont,
StyleColorPREtiquetasSectionTitle,
StyleColorPREtiquetasCell,
StyleColorPRCategoriaHeader,
StyleColorPRCategoriaSectionTitle,
StyleColorPRCategoriaCell,
StyleColorPRCategoriaCellBackground,
StyleColorPRCategoriaCellSeparatorLine,
StyleColorPRPrecioHeader,
StyleColorPRPrecioCell,
StyleColorPRTallaHeader,
StyleColorPRTallaSectionTitle,
StyleColorPRTallaCell,
StyleColorPRTallaResetBtn,
StyleColorPRCompHeader,
StyleColorPRCompCell,
StyleColorPRMisMarcasHeader,
StyleColorPRMisMarcasEmptySectionTitle,
StyleColorPRMisMarcasCell,
StyleColorPRMisMarcasCellBackground,
StyleColorPRMisMarcasCellSeparatorLine,
StyleColorPRMarcasHeader,
StyleColorPRMarcasCell,
StyleColorPRMarcasCellBackground,
StyleColorPRMarcasCellSeparatorLine,
StyleColorMainMenuBackground,
StyleColorMainMenuHeader,
StyleColorMainMenuSection,
StyleColorMainMenuSectionBackground,
StyleColorMainMenuCell,
StyleColorMainMenuCellBackground,
StyleColorMainMenuCellForegroundView,
StyleColorCOEmptyConjunto,
StyleColorCOHeader,
StyleColorCOBackground,
StyleColorCODetailHeader,
StyleColorCODetailBackground,
StyleColorCODetailTollBarButtons,
StyleColorCOCategoriaHeader,
StyleColorCOCategoriaCell,
StyleColorCOCategoriaCellBackground,
StyleColorCOCategoriaCellSeparatorLine,
StyleColorCONotasHeader,
StyleColorCONotasSectionTitle,
StyleColorCONotasCell,
StyleColorActionViewBackground,
StyleColorActionViewTitle,
StyleColorActionViewCell,
StyleColorActionViewCellSelected,
StyleColorHelpCell,
StyleColorHelpCellBackground,
StyleColorHelpCellSeparatorLine,
StyleColorHelpVersion,
StyleColorHelpDetailTitle,
StyleColorHelpDetailText,
StyleColorProfileBtnTitle,
StyleColorProfileBtnRecoverPwdTitle,
StyleColorProfileBtnRecoverPwdTitleInverse,
StyleColorProfileDetailBtnTitle,
StyleColorProfileDetailTextView,
StyleColorRegisterWelcomeTitle,
StyleColorRegisterWelcomeBtn,
StyleColorFechaHeader,
StyleColorYourStyleHeader,
StyleColorYourStyleBtnTitle,
StyleColorYourStyleCualEsBackground,
StyleColorYourStyleCualEsHeader,
StyleColorYourStyleCualEsTitle,
StyleColorYourStyleCualEsText,
StyleColorYourStyleFashionBackground,
StyleColorYourStyleFashionHeader,
StyleColorYourStyleFashionTitle,
StyleColorYourStyleFashionText,
StyleColorCalendarBackground,
StyleColorCalendarMonthTitle,
StyleColorCalendarWeekDayTitle,
StyleColorCalendarDay,
StyleColorCalendarOtherMonthDay,
StyleColorCalendarWeekendDay,
StyleColorCalendarFillToday,
StyleColorCalendarFillNormalDay,
StyleColorCalendarFillOtherMonthDay,
StyleColorCalendarSelectedDay,
StyleColorCalendarDetailHeader,
StyleColorCalendarDetailBackground,
StyleColorStylesHeader,
StyleColorStylesTitle,
StyleColorStylesDetailHeader,
StyleColorStyleST01DetailInAppHeaderColor,
StyleColorStyleST02DetailInAppHeaderColor,
StyleColorStyleST01DetailInAppHeaderTextColor,
StyleColorStyleST02DetailInAppHeaderTextColor,
StyleColorStyleST01DetailInAppText,
StyleColorStyleST02DetailInAppText,
StyleColorSortBackground,
StyleColorSortTitleColor,
StyleColorSortCellText,
StyleColorSortCellBackground,
StyleColorSortNotesBackground,
StyleColorSortNotesCellText
} StyleColorType;
typedef enum {
StyleFontMainType,
StyleFontFlat,
StyleFontBottomBtns,
StyleFontActionView,
StyleFontAparienciaST01,
StyleFontAparienciaST02,
} StyleFontType;
@interface StyleDressApp : NSObject
+(void) setStyle:(StyleType)newAppStyle;
+(StyleType) getStyle;
+(UIImage*) imageWithStyleNamed:(NSString*)imageName;
+(UIColor*) colorWithStyleForObject:(StyleColorType)styleColor;
+(UIFont*) fontWithStyleNamed:(StyleFontType)newFontType AndSize:(CGFloat)newFontSize;
@end
| Java |
/*****************************************************************************
* Copyright (c) 2014-2019 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "TileElement.h"
#include "../core/Guard.hpp"
#include "../interface/Window.h"
#include "../localisation/Localisation.h"
#include "../ride/Track.h"
#include "Banner.h"
#include "LargeScenery.h"
#include "Scenery.h"
uint8_t TileElementBase::GetType() const
{
return this->type & TILE_ELEMENT_TYPE_MASK;
}
void TileElementBase::SetType(uint8_t newType)
{
this->type &= ~TILE_ELEMENT_TYPE_MASK;
this->type |= (newType & TILE_ELEMENT_TYPE_MASK);
}
Direction TileElementBase::GetDirection() const
{
return this->type & TILE_ELEMENT_DIRECTION_MASK;
}
void TileElementBase::SetDirection(Direction direction)
{
this->type &= ~TILE_ELEMENT_DIRECTION_MASK;
this->type |= (direction & TILE_ELEMENT_DIRECTION_MASK);
}
Direction TileElementBase::GetDirectionWithOffset(uint8_t offset) const
{
return ((this->type & TILE_ELEMENT_DIRECTION_MASK) + offset) & TILE_ELEMENT_DIRECTION_MASK;
}
bool TileElementBase::IsLastForTile() const
{
return (this->flags & TILE_ELEMENT_FLAG_LAST_TILE) != 0;
}
void TileElementBase::SetLastForTile(bool on)
{
if (on)
flags |= TILE_ELEMENT_FLAG_LAST_TILE;
else
flags &= ~TILE_ELEMENT_FLAG_LAST_TILE;
}
bool TileElementBase::IsGhost() const
{
return (this->flags & TILE_ELEMENT_FLAG_GHOST) != 0;
}
void TileElementBase::SetGhost(bool isGhost)
{
if (isGhost)
{
this->flags |= TILE_ELEMENT_FLAG_GHOST;
}
else
{
this->flags &= ~TILE_ELEMENT_FLAG_GHOST;
}
}
bool tile_element_is_underground(TileElement* tileElement)
{
do
{
tileElement++;
if ((tileElement - 1)->IsLastForTile())
return false;
} while (tileElement->GetType() != TILE_ELEMENT_TYPE_SURFACE);
return true;
}
BannerIndex tile_element_get_banner_index(TileElement* tileElement)
{
rct_scenery_entry* sceneryEntry;
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_LARGE_SCENERY:
sceneryEntry = tileElement->AsLargeScenery()->GetEntry();
if (sceneryEntry->large_scenery.scrolling_mode == SCROLLING_MODE_NONE)
return BANNER_INDEX_NULL;
return tileElement->AsLargeScenery()->GetBannerIndex();
case TILE_ELEMENT_TYPE_WALL:
sceneryEntry = tileElement->AsWall()->GetEntry();
if (sceneryEntry == nullptr || sceneryEntry->wall.scrolling_mode == SCROLLING_MODE_NONE)
return BANNER_INDEX_NULL;
return tileElement->AsWall()->GetBannerIndex();
case TILE_ELEMENT_TYPE_BANNER:
return tileElement->AsBanner()->GetIndex();
default:
return BANNER_INDEX_NULL;
}
}
void tile_element_set_banner_index(TileElement* tileElement, BannerIndex bannerIndex)
{
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_WALL:
tileElement->AsWall()->SetBannerIndex(bannerIndex);
break;
case TILE_ELEMENT_TYPE_LARGE_SCENERY:
tileElement->AsLargeScenery()->SetBannerIndex(bannerIndex);
break;
case TILE_ELEMENT_TYPE_BANNER:
tileElement->AsBanner()->SetIndex(bannerIndex);
break;
default:
log_error("Tried to set banner index on unsuitable tile element!");
Guard::Assert(false);
}
}
void tile_element_remove_banner_entry(TileElement* tileElement)
{
auto bannerIndex = tile_element_get_banner_index(tileElement);
auto banner = GetBanner(bannerIndex);
if (banner != nullptr)
{
window_close_by_number(WC_BANNER, bannerIndex);
*banner = {};
}
}
uint8_t tile_element_get_ride_index(const TileElement* tileElement)
{
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_TRACK:
return tileElement->AsTrack()->GetRideIndex();
case TILE_ELEMENT_TYPE_ENTRANCE:
return tileElement->AsEntrance()->GetRideIndex();
case TILE_ELEMENT_TYPE_PATH:
return tileElement->AsPath()->GetRideIndex();
default:
return RIDE_ID_NULL;
}
}
void TileElement::ClearAs(uint8_t newType)
{
type = newType;
flags = 0;
base_height = 2;
clearance_height = 2;
std::fill_n(pad_04, sizeof(pad_04), 0x00);
std::fill_n(pad_08, sizeof(pad_08), 0x00);
}
void TileElementBase::Remove()
{
tile_element_remove((TileElement*)this);
}
// Rotate both of the values amount
const QuarterTile QuarterTile::Rotate(uint8_t amount) const
{
switch (amount)
{
case 0:
return QuarterTile{ *this };
break;
case 1:
{
auto rotVal1 = _val << 1;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b11101110;
// Clear the bit from the zQuarter
rotVal2 &= 0b00010001;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
case 2:
{
auto rotVal1 = _val << 2;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b11001100;
// Clear the bit from the zQuarter
rotVal2 &= 0b00110011;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
case 3:
{
auto rotVal1 = _val << 3;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b10001000;
// Clear the bit from the zQuarter
rotVal2 &= 0b01110111;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
default:
log_error("Tried to rotate QuarterTile invalid amount.");
return QuarterTile{ 0 };
}
}
uint8_t TileElementBase::GetOccupiedQuadrants() const
{
return flags & TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK;
}
void TileElementBase::SetOccupiedQuadrants(uint8_t quadrants)
{
flags &= ~TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK;
flags |= (quadrants & TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK);
}
int32_t TileElementBase::GetBaseZ() const
{
return base_height * 8;
}
void TileElementBase::SetBaseZ(int32_t newZ)
{
base_height = (newZ / 8);
}
int32_t TileElementBase::GetClearanceZ() const
{
return clearance_height * 8;
}
void TileElementBase::SetClearanceZ(int32_t newZ)
{
clearance_height = (newZ / 8);
}
| Java |
/*
FreeRTOS V7.3.0 - Copyright (C) 2012 Real Time Engineers Ltd.
FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT
http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
>>>NOTE<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it
can be viewed here: http://www.freertos.org/a00114.html and also obtained
by writing to Richard Barry, contact details for whom are available on the
FreeRTOS WEB site.
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, training, latest versions, license
and contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool.
Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell
the code with commercial support, indemnification, and middleware, under
the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also
provide a safety engineered and independently SIL3 certified version under
the SafeRTOS brand: http://www.SafeRTOS.com.
*/
/*-----------------------------------------------------------
* Implementation of functions defined in portable.h for the PIC32MX port.
*----------------------------------------------------------*/
/* Scheduler include files. */
#include "FreeRTOS.h"
#include "task.h"
/* Hardware specifics. */
#define portTIMER_PRESCALE 8
/* Bits within various registers. */
#define portIE_BIT ( 0x00000001 )
#define portEXL_BIT ( 0x00000002 )
/* The EXL bit is set to ensure interrupts do not occur while the context of
the first task is being restored. */
#define portINITIAL_SR ( portIE_BIT | portEXL_BIT )
#ifndef configTICK_INTERRUPT_VECTOR
#define configTICK_INTERRUPT_VECTOR _TIMER_1_VECTOR
#endif
/* Records the interrupt nesting depth. This starts at one as it will be
decremented to 0 when the first task starts. */
volatile unsigned portBASE_TYPE uxInterruptNesting = 0x01;
/* Stores the task stack pointer when a switch is made to use the system stack. */
unsigned portBASE_TYPE uxSavedTaskStackPointer = 0;
/* The stack used by interrupt service routines that cause a context switch. */
portSTACK_TYPE xISRStack[ configISR_STACK_SIZE ] = { 0 };
/* The top of stack value ensures there is enough space to store 6 registers on
the callers stack, as some functions seem to want to do this. */
const portSTACK_TYPE * const xISRStackTop = &( xISRStack[ configISR_STACK_SIZE - 7 ] );
/*
* Place the prototype here to ensure the interrupt vector is correctly installed.
* Note that because the interrupt is written in assembly, the IPL setting in the
* following line of code has no effect. The interrupt priority is set by the
* call to ConfigIntTimer1() in vApplicationSetupTickTimerInterrupt().
*/
extern void __attribute__( (interrupt(ipl1), vector( configTICK_INTERRUPT_VECTOR ))) vPortTickInterruptHandler( void );
/*
* The software interrupt handler that performs the yield. Note that, because
* the interrupt is written in assembly, the IPL setting in the following line of
* code has no effect. The interrupt priority is set by the call to
* mConfigIntCoreSW0() in xPortStartScheduler().
*/
void __attribute__( (interrupt(ipl1), vector(_CORE_SOFTWARE_0_VECTOR))) vPortYieldISR( void );
/*-----------------------------------------------------------*/
/*
* See header file for description.
*/
portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
{
/* Ensure byte alignment is maintained when leaving this function. */
pxTopOfStack--;
*pxTopOfStack = (portSTACK_TYPE) 0xDEADBEEF;
pxTopOfStack--;
*pxTopOfStack = (portSTACK_TYPE) 0x12345678; /* Word to which the stack pointer will be left pointing after context restore. */
pxTopOfStack--;
*pxTopOfStack = (portSTACK_TYPE) _CP0_GET_CAUSE();
pxTopOfStack--;
*pxTopOfStack = (portSTACK_TYPE) portINITIAL_SR; /* CP0_STATUS */
pxTopOfStack--;
*pxTopOfStack = (portSTACK_TYPE) pxCode; /* CP0_EPC */
pxTopOfStack--;
*pxTopOfStack = (portSTACK_TYPE) NULL; /* ra */
pxTopOfStack -= 15;
*pxTopOfStack = (portSTACK_TYPE) pvParameters; /* Parameters to pass in */
pxTopOfStack -= 14;
*pxTopOfStack = (portSTACK_TYPE) 0x00000000; /* critical nesting level - no longer used. */
pxTopOfStack--;
return pxTopOfStack;
}
/*-----------------------------------------------------------*/
/*
* Setup a timer for a regular tick. This function uses peripheral timer 1.
* The function is declared weak so an application writer can use a different
* timer by redefining this implementation. If a different timer is used then
* configTICK_INTERRUPT_VECTOR must also be defined in FreeRTOSConfig.h to
* ensure the RTOS provided tick interrupt handler is installed on the correct
* vector number. When Timer 1 is used the vector number is defined as
* _TIMER_1_VECTOR.
*/
__attribute__(( weak )) void vApplicationSetupTickTimerInterrupt( void )
{
const unsigned long ulCompareMatch = ( (configPERIPHERAL_CLOCK_HZ / portTIMER_PRESCALE) / configTICK_RATE_HZ ) - 1;
OpenTimer1( ( T1_ON | T1_PS_1_8 | T1_SOURCE_INT ), ulCompareMatch );
ConfigIntTimer1( T1_INT_ON | configKERNEL_INTERRUPT_PRIORITY );
}
/*-----------------------------------------------------------*/
void vPortEndScheduler(void)
{
/* It is unlikely that the scheduler for the PIC port will get stopped
once running. If required disable the tick interrupt here, then return
to xPortStartScheduler(). */
for( ;; );
}
/*-----------------------------------------------------------*/
portBASE_TYPE xPortStartScheduler( void )
{
extern void vPortStartFirstTask( void );
extern void *pxCurrentTCB;
/* Setup the software interrupt. */
mConfigIntCoreSW0( CSW_INT_ON | configKERNEL_INTERRUPT_PRIORITY | CSW_INT_SUB_PRIOR_0 );
/* Setup the timer to generate the tick. Interrupts will have been
disabled by the time we get here. */
vApplicationSetupTickTimerInterrupt();
/* Kick off the highest priority task that has been created so far.
Its stack location is loaded into uxSavedTaskStackPointer. */
uxSavedTaskStackPointer = *( unsigned portBASE_TYPE * ) pxCurrentTCB;
vPortStartFirstTask();
/* Should never get here as the tasks will now be executing. */
return pdFALSE;
}
/*-----------------------------------------------------------*/
void vPortIncrementTick( void )
{
unsigned portBASE_TYPE uxSavedStatus;
uxSavedStatus = uxPortSetInterruptMaskFromISR();
vTaskIncrementTick();
vPortClearInterruptMaskFromISR( uxSavedStatus );
/* If we are using the preemptive scheduler then we might want to select
a different task to execute. */
#if configUSE_PREEMPTION == 1
SetCoreSW0();
#endif /* configUSE_PREEMPTION */
/* Clear timer 0 interrupt. */
mT1ClearIntFlag();
}
/*-----------------------------------------------------------*/
unsigned portBASE_TYPE uxPortSetInterruptMaskFromISR( void )
{
unsigned portBASE_TYPE uxSavedStatusRegister;
asm volatile ( "di" );
uxSavedStatusRegister = _CP0_GET_STATUS() | 0x01;
/* This clears the IPL bits, then sets them to
configMAX_SYSCALL_INTERRUPT_PRIORITY. This function should not be called
from an interrupt that has a priority above
configMAX_SYSCALL_INTERRUPT_PRIORITY so, when used correctly, the action
can only result in the IPL being unchanged or raised, and therefore never
lowered. */
_CP0_SET_STATUS( ( ( uxSavedStatusRegister & ( ~portALL_IPL_BITS ) ) ) | ( configMAX_SYSCALL_INTERRUPT_PRIORITY << portIPL_SHIFT ) );
return uxSavedStatusRegister;
}
/*-----------------------------------------------------------*/
void vPortClearInterruptMaskFromISR( unsigned portBASE_TYPE uxSavedStatusRegister )
{
_CP0_SET_STATUS( uxSavedStatusRegister );
}
/*-----------------------------------------------------------*/
| Java |
/*
* PktGen by Steffen Schulz © 2009
*
* Braindead TCP server that waits for a packet and then
* - replies with stream of packets
* - with inter-packet delays read as integers from stdin
*
* Disables Nagle Algo to prevent buffering in local network stack
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#define DEBUG (1)
/* Basic signal handler closes nfq hooks on exit */
static void sig_handler(int signum) {
printf("\nCaught Signal ...\n\n");
exit(0);
}
int main(int argc, char **argv) {
struct sockaddr_in sin;
struct sockaddr_in sout;
int s = socket(AF_INET,SOCK_STREAM,0);
unsigned int slen = sizeof(sout);
unsigned int len = 0;
char line[500];
long delay = 0;
unsigned int cntr = 0;
int port = 1194;
int tmp = 0;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = INADDR_ANY;
/* make stdin non-blocking, i.e. optional */
int flags = fcntl(0, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(0, F_SETFL, flags);
/* close nfq hooks on exit */
if (signal(SIGINT, sig_handler) == SIG_IGN)
signal(SIGINT, SIG_IGN);
if (signal(SIGHUP, sig_handler) == SIG_IGN)
signal(SIGHUP, SIG_IGN);
if (signal(SIGTERM, sig_handler) == SIG_IGN)
signal(SIGTERM, SIG_IGN);
// wait for conn, store peer in sout
bind(s, (struct sockaddr *)&sin, sizeof(sin));
listen(s, 2);
int c = accept(s, (struct sockaddr *)&sout, &tmp);
tmp=1;
if (setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &tmp, sizeof(tmp)) < 0)
fprintf(stderr, "Error when disabling buffer..\n");
printf("Got connection from %s:%d, start sending..\n",
inet_ntoa(sout.sin_addr), ntohs(sout.sin_port));
len = snprintf(line, 499, "%010d\n",cntr++);
send(c, line, len+1,0);
while (1) {
if (fgets(line, 49, stdin)) {
delay = atol(line);
}
else {
if (argc > 1)
exit(0);
delay = 5000;
}
if (delay < 0)
delay = 0;
usleep(delay);
len = snprintf(line, 499, "%010d\n",cntr++);
send(c, line, len+1,0);
}
}
| Java |
-----------------------------------
-- Area: Sauromugue Champaign (S) (98)
-- Mob: Goblin_Flagman
-----------------------------------
-- require("scripts/zones/Sauromugue_Champaign_[S]/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
| Java |
/*
Copyright 2013-2015 Skytechnology sp. z o.o.
This file is part of LizardFS.
LizardFS 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, version 3.
LizardFS 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 LizardFS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/platform.h"
#include <gtest/gtest.h>
#include "common/chunk_read_planner.h"
#include "unittests/chunk_type_constants.h"
#include "unittests/plan_tester.h"
static ChunkPartType xor_part(int level, int part) {
return slice_traits::xors::ChunkPartType(level, part);
}
static void checkReadingChunk(std::map<ChunkPartType, std::vector<uint8_t>> &part_data,
int first_block, int block_count,
const ChunkReadPlanner::PartsContainer &available_parts) {
ChunkReadPlanner planner;
planner.prepare(first_block, block_count, available_parts);
ASSERT_TRUE(planner.isReadingPossible());
std::unique_ptr<ReadPlan> plan = planner.buildPlan();
unittests::ReadPlanTester tester;
std::cout << to_string(*plan) << std::endl;
ASSERT_TRUE(tester.executePlan(std::move(plan), part_data) >= 0);
EXPECT_TRUE(unittests::ReadPlanTester::compareBlocks(
tester.output_buffer_, 0, part_data[slice_traits::standard::ChunkPartType()],
first_block * MFSBLOCKSIZE, block_count));
}
static void checkReadingChunk(int first_block, int block_count,
const ChunkReadPlanner::PartsContainer &available_parts) {
std::map<ChunkPartType, std::vector<uint8_t>> part_data;
unittests::ReadPlanTester::buildData(part_data, available_parts);
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()});
checkReadingChunk(part_data, first_block, block_count, available_parts);
}
/*
TEST(ChunkReadPlannerTests, Unrecoverable1) {
checkUnrecoverable(xor_p_of_4, {xor_1_of_4, xor_2_of_4, xor_3_of_4});
}
TEST(ChunkReadPlannerTests, Unrecoverable2) {
checkUnrecoverable(xor_p_of_4, {xor_1_of_4, xor_2_of_4, xor_3_of_4});
}
TEST(ChunkReadPlannerTests, Unrecoverable3) {
checkUnrecoverable(xor_p_of_2, {xor_1_of_4, xor_2_of_4, xor_p_of_4});
}
TEST(ChunkReadPlannerTests, Unrecoverable4) {
checkUnrecoverable(xor_p_of_4, {xor_p_of_2});
}
*/
TEST(ChunkReadPlannerTests, VerifyRead1) {
std::map<ChunkPartType, std::vector<uint8_t>> part_data;
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::xors::ChunkPartType(5, 1)});
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()});
for (int i = 1; i <= 10; ++i) {
checkReadingChunk(part_data, 0, i, {xor_part(5, 0), xor_part(5, 1), xor_part(5, 2),
xor_part(5, 3), xor_part(5, 4), xor_part(5, 5)});
}
}
TEST(ChunkReadPlannerTests, VerifyRead2) {
std::map<ChunkPartType, std::vector<uint8_t>> part_data;
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::xors::ChunkPartType(5, 1)});
unittests::ReadPlanTester::buildData(
part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()});
for (int i = 1; i <= 10; ++i) {
checkReadingChunk(part_data, i, 2, {xor_part(5, 0), xor_part(5, 1), xor_part(5, 2),
xor_part(5, 3), xor_part(5, 4), xor_part(5, 5)});
}
}
TEST(ChunkReadPlannerTests, VerifyRead3) {
checkReadingChunk(0, 10, {xor_p_of_4, xor_2_of_4, xor_3_of_4, xor_4_of_4});
}
TEST(ChunkReadPlannerTests, VerifyRead4) {
checkReadingChunk(10, 100, {xor_p_of_7, xor_1_of_7, xor_2_of_7, xor_3_of_7, xor_4_of_7,
xor_5_of_7, xor_6_of_7, xor_7_of_7});
}
| Java |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library functions for WIRIS plugin for Atto.
*
* @package tinymce
* @subpackage tiny_mce_wiris
* @copyright Maths for More S.L. <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
class tinymce_tiny_mce_wiris extends editor_tinymce_plugin {
protected $buttons = array('tiny_mce_wiris_formulaEditor', 'tiny_mce_wiris_CAS');
protected function update_init_params(array &$params, context $context,
array $options = null) {
global $PAGE, $CFG;
$PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/baseURL.js', false);
// Add button after emoticon button in advancedbuttons3.
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_formulaEditor', '', false);
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_formulaEditorChemistry', '', false);
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_CAS', '', false);
// Add JS file, which uses default name.
$this->add_js_plugin($params);
$filterwiris = $CFG->dirroot . '/filter/wiris/filter.php';
if (!file_exists($filterwiris)) {
$PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/js/message.js', false);
}
}
}
| Java |
var searchData=
[
['save_5fcomments',['save_comments',['../useful__functions_8php.html#af56aec073a82606e9a7dac498de28d96',1,'useful_functions.php']]],
['save_5fexperiment_5flist',['save_experiment_list',['../choose__experiments_8php.html#a5d24f39ae6c336d7828523216bce6fae',1,'choose_experiments.php']]],
['save_5fsessions',['save_sessions',['../useful__functions_8php.html#a38a4632f417ceaa2f1c09c3ed0494d5e',1,'useful_functions.php']]],
['save_5fsignup_5fto_5fdb',['save_signup_to_db',['../useful__functions_8php.html#a0dca9d754b1a0d7b5401c446878844c5',1,'useful_functions.php']]],
['save_5fuser_5fexpt_5fchoices',['save_user_expt_choices',['../useful__functions_8php.html#a461a04526110df604708381a9eac7da8',1,'useful_functions.php']]],
['signup_5fexists',['signup_exists',['../useful__functions_8php.html#a7cf6d3ac90a6fca8c3f595e68b6e62cc',1,'useful_functions.php']]]
];
| Java |
<?php
/**
*
* ThinkUp/webapp/_lib/model/class.UserMySQLDAO.php
*
* Copyright (c) 2009-2013 Gina Trapani
*
* LICENSE:
*
* This file is part of ThinkUp (http://thinkup.com).
*
* ThinkUp 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 2 of the License, or (at your option) any
* later version.
*
* ThinkUp 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 ThinkUp. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* User Data Access Object MySQL Implementation
*
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2009-2013 Gina Trapani
* @author Gina Trapani <ginatrapani[at]gmail[dot]com>
*
*/
class UserMySQLDAO extends PDODAO implements UserDAO {
/**
* Get the SQL to generate average_tweets_per_day number
* @TODO rename "tweets" "posts"
* @return str SQL calcuation
*/
private function getAverageTweetCount() {
return "round(post_count/(datediff(curdate(), joined)), 2) as avg_tweets_per_day";
}
public function isUserInDB($user_id, $network) {
$q = "SELECT user_id ";
$q .= "FROM #prefix#users ";
$q .= "WHERE user_id = :user_id AND network = :network;";
$vars = array(
':user_id'=>(string)$user_id,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataIsReturned($ps);
}
public function isUserInDBByName($username, $network) {
$q = "SELECT user_id ";
$q .= "FROM #prefix#users ";
$q .= "WHERE user_name = :username AND network = :network";
$vars = array(
':username'=>$username,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataIsReturned($ps);
}
public function updateUsers($users_to_update) {
$count = 0;
$status_message = "";
if (sizeof($users_to_update) > 0) {
$status_message .= count($users_to_update)." users queued for insert or update; ";
foreach ($users_to_update as $user) {
$count += $this->updateUser($user);
}
$status_message .= "$count users affected.";
}
$this->logger->logInfo($status_message, __METHOD__.','.__LINE__);
$status_message = "";
return $count;
}
public function updateUser($user) {
if (!isset($user->username)) {
return 0;
}
$status_message = "";
$has_friend_count = $user->friend_count != '' ? true : false;
$has_favorites_count = $user->favorites_count != '' ? true : false;
$has_last_post = $user->last_post != '' ? true : false;
$has_last_post_id = $user->last_post_id != '' ? true : false;
$network = $user->network != '' ? $user->network : 'twitter';
$user->follower_count = $user->follower_count != '' ? $user->follower_count : 0;
$user->post_count = $user->post_count != '' ? $user->post_count : 0;
$vars = array(
':user_id'=>(string)$user->user_id,
':username'=>$user->username,
':full_name'=>$user->full_name,
':avatar'=>$user->avatar,
':location'=>$user->location,
':description'=>$user->description,
':url'=>$user->url,
':is_protected'=>$this->convertBoolToDB($user->is_protected),
':follower_count'=>$user->follower_count,
':post_count'=>$user->post_count,
':found_in'=>$user->found_in,
':joined'=>$user->joined,
':network'=>$user->network
);
$is_user_in_storage = false;
$is_user_in_storage = $this->isUserInDB($user->user_id, $user->network);
if (!$is_user_in_storage) {
$q = "INSERT INTO #prefix#users (user_id, user_name, full_name, avatar, location, description, url, ";
$q .= "is_protected, follower_count, post_count, ".($has_friend_count ? "friend_count, " : "")." ".
($has_favorites_count ? "favorites_count, " : "")." ".
($has_last_post ? "last_post, " : "")." found_in, joined, network ".
($has_last_post_id ? ", last_post_id" : "").") ";
$q .= "VALUES ( :user_id, :username, :full_name, :avatar, :location, :description, :url, :is_protected, ";
$q .= ":follower_count, :post_count, ".($has_friend_count ? ":friend_count, " : "")." ".
($has_favorites_count ? ":favorites_count, " : "")." ".
($has_last_post ? ":last_post, " : "")." :found_in, :joined, :network ".
($has_last_post_id ? ", :last_post_id " : "")." )";
} else {
$q = "UPDATE #prefix#users SET full_name = :full_name, avatar = :avatar, location = :location, ";
$q .= "user_name = :username, description = :description, url = :url, is_protected = :is_protected, ";
$q .= "follower_count = :follower_count, post_count = :post_count, ".
($has_friend_count ? "friend_count= :friend_count, " : "")." ".
($has_favorites_count ? "favorites_count= :favorites_count, " : "")." ".
($has_last_post ? "last_post= :last_post, " : "")." last_updated = NOW(), found_in = :found_in, ";
$q .= "joined = :joined, network = :network ".
($has_last_post_id ? ", last_post_id = :last_post_id" : "")." ";
$q .= "WHERE user_id = :user_id AND network = :network;";
}
if ($has_friend_count) {
$vars[':friend_count'] = $user->friend_count;
}
if ($has_favorites_count) {
$vars[':favorites_count'] = $user->favorites_count;
}
if ($has_last_post) {
$vars[':last_post'] = $user->last_post;
}
if ($has_last_post_id) {
$vars[':last_post_id'] = $user->last_post_id;
}
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
$results = $this->getUpdateCount($ps);
return $results;
}
public function getDetails($user_id, $network) {
$q = "SELECT * , ".$this->getAverageTweetCount()." ";
$q .= "FROM #prefix#users u ";
$q .= "WHERE u.user_id = :user_id AND u.network = :network;";
$vars = array(
':user_id'=>(string)$user_id,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataRowAsObject($ps, "User");
}
public function getUserByName($user_name, $network) {
$q = "SELECT * , ".$this->getAverageTweetCount()." ";
$q .= "FROM #prefix#users u ";
$q .= "WHERE u.user_name = :user_name AND u.network = :network";
$vars = array(
':user_name'=>$user_name,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataRowAsObject($ps, "User");
}
}
| Java |
main = f `x y` g
| Java |
# NgrxSimpleLab4
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.1.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package VerilogCompiler.SyntacticTree;
import VerilogCompiler.SemanticCheck.ErrorHandler;
import VerilogCompiler.SemanticCheck.ExpressionType;
import VerilogCompiler.SyntacticTree.Expressions.Expression;
/**
*
* @author Néstor A. Bermúdez < [email protected] >
*/
public class Range extends VNode {
Expression minValue;
Expression maxValue;
public Range(Expression minValue, Expression maxValue, int line, int column) {
super(line, column);
this.minValue = minValue;
this.maxValue = maxValue;
}
public Expression getMinValue() {
return minValue;
}
public void setMinValue(Expression minValue) {
this.minValue = minValue;
}
public Expression getMaxValue() {
return maxValue;
}
public void setMaxValue(Expression maxValue) {
this.maxValue = maxValue;
}
@Override
public String toString() {
return String.format("[%s:%s]", this.minValue, this.maxValue);
}
@Override
public ExpressionType validateSemantics() {
ExpressionType minReturnType = minValue.validateSemantics();
ExpressionType maxReturnType = maxValue.validateSemantics();
if (minReturnType != ExpressionType.INTEGER || maxReturnType != ExpressionType.INTEGER)
{
ErrorHandler.getInstance().handleError(line, column, "range min and max value must be integer");
}
return null;
}
@Override
public VNode getCopy() {
return new Range((Expression)minValue.getCopy(), (Expression)maxValue.getCopy(), line, column);
}
}
| Java |
import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
| Java |
'use strict';
var async = require('async');
var nconf = require('nconf');
var querystring = require('querystring');
var meta = require('../meta');
var pagination = require('../pagination');
var user = require('../user');
var topics = require('../topics');
var plugins = require('../plugins');
var helpers = require('./helpers');
var unreadController = module.exports;
unreadController.get = function (req, res, next) {
var page = parseInt(req.query.page, 10) || 1;
var results;
var cid = req.query.cid;
var filter = req.query.filter || '';
var settings;
async.waterfall([
function (next) {
plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next);
},
function (data, _next) {
if (!data.filters[filter]) {
return next();
}
async.parallel({
watchedCategories: function (next) {
helpers.getWatchedCategories(req.uid, cid, next);
},
settings: function (next) {
user.getSettings(req.uid, next);
},
}, _next);
},
function (_results, next) {
results = _results;
settings = results.settings;
var start = Math.max(0, (page - 1) * settings.topicsPerPage);
var stop = start + settings.topicsPerPage - 1;
var cutoff = req.session.unreadCutoff ? req.session.unreadCutoff : topics.unreadCutoff();
topics.getUnreadTopics({
cid: cid,
uid: req.uid,
start: start,
stop: stop,
filter: filter,
cutoff: cutoff,
}, next);
},
function (data, next) {
user.blocks.filter(req.uid, data.topics, function (err, filtered) {
data.topics = filtered;
next(err, data);
});
},
function (data) {
data.title = meta.config.homePageTitle || '[[pages:home]]';
data.pageCount = Math.max(1, Math.ceil(data.topicCount / settings.topicsPerPage));
data.pagination = pagination.create(page, data.pageCount, req.query);
if (settings.usePagination && (page < 1 || page > data.pageCount)) {
req.query.page = Math.max(1, Math.min(data.pageCount, page));
return helpers.redirect(res, '/unread?' + querystring.stringify(req.query));
}
data.categories = results.watchedCategories.categories;
data.allCategoriesUrl = 'unread' + helpers.buildQueryString('', filter, '');
data.selectedCategory = results.watchedCategories.selectedCategory;
data.selectedCids = results.watchedCategories.selectedCids;
if (req.originalUrl.startsWith(nconf.get('relative_path') + '/api/unread') || req.originalUrl.startsWith(nconf.get('relative_path') + '/unread')) {
data.title = '[[pages:unread]]';
data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]);
}
data.filters = helpers.buildFilters('unread', filter, req.query);
data.selectedFilter = data.filters.find(function (filter) {
return filter && filter.selected;
});
res.render('unread', data);
},
], next);
};
unreadController.unreadTotal = function (req, res, next) {
var filter = req.query.filter || '';
async.waterfall([
function (next) {
plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next);
},
function (data, _next) {
if (!data.filters[filter]) {
return next();
}
topics.getTotalUnread(req.uid, filter, _next);
},
function (data) {
res.json(data);
},
], next);
};
| Java |
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
class Serializer(object):
schemaless = True
encapsulate = True
registry = {}
def __init__(self, query_params, pretty=False, **kwargs):
self.pretty = pretty
self._query_params = query_params
self._fileName = None
self._lastModified = None
self._extra_args = kwargs
@classmethod
def register(cls, tag, serializer):
cls.registry[tag] = serializer
@classmethod
def getAllFormats(cls):
return list(cls.registry)
@classmethod
def create(cls, dformat, query_params=None, **kwargs):
"""
A serializer factory
"""
query_params = query_params or {}
serializer = cls.registry.get(dformat)
if serializer:
return serializer(query_params, **kwargs)
else:
raise Exception("Serializer for '%s' does not exist!" % dformat)
def getMIMEType(self):
return self._mime
def set_headers(self, response):
response.content_type = self.getMIMEType()
def __call__(self, obj, *args, **kwargs):
self._obj = obj
self._data = self._execute(obj, *args, **kwargs)
return self._data
from indico.web.http_api.metadata.json import JSONSerializer
from indico.web.http_api.metadata.xml import XMLSerializer
| Java |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\Spi;
/**
* Interface ResourceInterface
*/
interface OrderPaymentResourceInterface
{
/**
* Save object data
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
public function save(\Magento\Framework\Model\AbstractModel $object);
/**
* Load an object
*
* @param mixed $value
* @param \Magento\Framework\Model\AbstractModel $object
* @param string|null $field field to load by (defaults to model id)
* @return mixed
*/
public function load(\Magento\Framework\Model\AbstractModel $object, $value, $field = null);
/**
* Delete the object
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return mixed
*/
public function delete(\Magento\Framework\Model\AbstractModel $object);
}
| Java |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
package android.renderscript.cts;
import android.renderscript.Allocation;
import android.renderscript.RSRuntimeException;
import android.renderscript.Element;
public class TestAsin extends RSBaseCompute {
private ScriptC_TestAsin script;
private ScriptC_TestAsinRelaxed scriptRelaxed;
@Override
protected void setUp() throws Exception {
super.setUp();
script = new ScriptC_TestAsin(mRS);
scriptRelaxed = new ScriptC_TestAsinRelaxed(mRS);
}
public class ArgumentsFloatFloat {
public float inV;
public Target.Floaty out;
}
private void checkAsinFloatFloat() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 1, 0x80b5674ff98b5a12l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE);
script.forEach_testAsinFloatFloat(inV, out);
verifyResultsAsinFloatFloat(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloatFloat(inV, out);
verifyResultsAsinFloatFloat(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString());
}
}
private void verifyResultsAsinFloatFloat(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 1];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 1];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 1 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 1 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 1 + j], Float.floatToRawIntBits(arrayOut[i * 1 + j]), arrayOut[i * 1 + j]));
if (!args.out.couldBe(arrayOut[i * 1 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloatFloat" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
private void checkAsinFloat2Float2() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 2, 0x9e11e5e823f7cce6l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE);
script.forEach_testAsinFloat2Float2(inV, out);
verifyResultsAsinFloat2Float2(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloat2Float2(inV, out);
verifyResultsAsinFloat2Float2(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString());
}
}
private void verifyResultsAsinFloat2Float2(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 2];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 2];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 2 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 2 + j];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 2 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 2 + j], Float.floatToRawIntBits(arrayOut[i * 2 + j]), arrayOut[i * 2 + j]));
if (!args.out.couldBe(arrayOut[i * 2 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloat2Float2" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
private void checkAsinFloat3Float3() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 3, 0x9e13af031a12edc4l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE);
script.forEach_testAsinFloat3Float3(inV, out);
verifyResultsAsinFloat3Float3(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloat3Float3(inV, out);
verifyResultsAsinFloat3Float3(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString());
}
}
private void verifyResultsAsinFloat3Float3(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 4];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 4];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 3 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 4 + j];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j]));
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloat3Float3" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
private void checkAsinFloat4Float4() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 4, 0x9e15781e102e0ea2l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE);
script.forEach_testAsinFloat4Float4(inV, out);
verifyResultsAsinFloat4Float4(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloat4Float4(inV, out);
verifyResultsAsinFloat4Float4(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString());
}
}
private void verifyResultsAsinFloat4Float4(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 4];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 4];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 4 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 4 + j];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j]));
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloat4Float4" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
public void testAsin() {
checkAsinFloatFloat();
checkAsinFloat2Float2();
checkAsinFloat3Float3();
checkAsinFloat4Float4();
}
}
| Java |
#!/usr/bin/perl
# $Id: Chain.pm,v 1.12 2001/06/18 08:27:53 heikki Exp $
#
# bioperl module for Bio::LiveSeq::Chain
#
# Cared for by Joseph Insana <[email protected]> <[email protected]>
#
# Copyright Joseph Insana
#
# You may distribute this module under the same terms as perl itself
#
# POD documentation - main docs before the code
#
=head1 NAME
Bio::LiveSeq::Chain - DoubleChain DataStructure for Perl
=head1 SYNOPSIS
#documentation needed
=head1 DESCRIPTION
This is a general purpose module (that's why it's not in object-oriented
form) that introduces a novel datastructure in PERL. It implements
the "double linked chain". The elements of the chain can contain basically
everything. From chars to strings, from object references to arrays or hashes.
It is used in the LiveSequence project to create a dynamical DNA sequence,
easier to manipulate and change. It's use is mainly for sequence variation
analysis but it could be used - for example - in e-cell projects.
The Chain module in itself doesn't have any biological bias, so can be
used for any programming purpose.
Each element of the chain (with the exclusion of the first and the last of the
chain) is connected to other two elements (the PREVious and the NEXT one).
There is no absolute position (like in an array), hence if positions are
important, they need to be computed (methods are provided).
Otherwise it's easy to keep track of the elements with their "LABELs".
There is one LABEL (think of it as a pointer) to each ELEMENT. The labels
won't change after insertions or deletions of the chain. So it's
always possible to retrieve an element even if the chain has been
modified by successive insertions or deletions.
From this the high potential profit for bioinformatics: dealing with
sequences in a way that doesn't have to rely on positions, without
the need of constantly updating them if the sequence changes, even
dramatically.
=head1 AUTHOR - Joseph A.L. Insana
Email: [email protected], [email protected]
Address:
EMBL Outstation, European Bioinformatics Institute
Wellcome Trust Genome Campus, Hinxton
Cambs. CB10 1SD, United Kingdom
=head1 APPENDIX
The rest of the documentation details each of the object
methods. Internal methods are usually preceded with a _
=cut
# Let the code begin...
# DoubleChain Data Structure for PERL
# by Joseph A.L. Insana - Deathson - Filius Mortis - Fal Mortais
# [email protected], [email protected]
package Bio::LiveSeq::Chain;
# Version history:
# Fri Mar 10 16:46:51 GMT 2000 v1.0 begun working on chains in perl
# Sat Mar 11 05:47:21 GMT 2000 v.1.4 working on splice method
# Sun Mar 12 14:08:31 GMT 2000 v.1.5
# Sun Mar 12 17:21:51 GMT 2000 v.2.0 splice method working, is_updownstream made
# Sun Mar 12 18:11:22 GMT 2000 v.2.04 wrapped all in package Chain.pm
# Sun Mar 12 18:49:23 GMT 2000 v.2.08 added elements()
# Sun Mar 12 21:18:04 GMT 2000 v.2.1 done array2dchain, working on *insert*
# Sun Mar 12 23:04:40 GMT 2000 v.2.16 done *insert*, up_element, create_elems
# Sun Mar 12 23:45:32 GMT 2000 v.2.17 debugged and checked
# Mon Mar 13 00:44:51 GMT 2000 v.2.2 added mutate()
# Mon Mar 13 02:00:32 GMT 2000 v 2.21 added invert_dchain()
# Mon Mar 13 03:01:21 GMT 2000 v 2.22 created updown_chain2string
# Mon Mar 13 03:45:50 GMT 2000 v.2.24 added subchain_length()
# Mon Mar 13 17:25:04 GMT 2000 v.2.26 added element_at_pos and pos_of_element
# Wed Mar 15 23:05:06 GMT 2000 v.2.27 use strict enforced
# Thu Mar 16 19:05:34 GMT 2000 v.2.3 changed dchain->chain everywhere
# Fri Mar 17 01:48:36 GMT 2000 v.2.33 mutate_element renamed, created new
# methods: set_value, get_value...
# Fri Mar 17 05:03:15 GMT 2000 v.2.4 set_value_at_pos, get_value_at_pos
# get_label_at_pos...
# Fri Mar 17 15:51:07 GMT 2000 v.2.41 renamed pos_of_element -> get_pos_of_label
# Fri Mar 17 18:10:36 GMT 2000 v.2.44 recoded subchain_length and pos_of_label
# Fri Mar 17 20:12:27 GMT 2000 v.2.5 NAMING change: index->label everywhere
# Mon Mar 20 18:33:10 GMT 2000 v.2.52 label_exists(), start(), end()
# Mon Mar 20 23:10:28 GMT 2000 v.2.6 labels() created
# Wed Mar 22 18:35:17 GMT 2000 v.2.61 chain2string() rewritten
# Tue Dec 12 14:47:58 GMT 2000 v 2.66 optimized with /use integer/
# Tue Dec 12 16:28:45 GMT 2000 v 2.7 rewritten comments to methods in pod style
#
$VERSION=2.7;
#
# TODO_list:
# **** cleanup code
# **** performance concerns
# *??* create hash2dchain ???? (with hashkeys used for label)
# **????** how about using array of arrays instead than hash of arrays??
#
# further strict complaints:
# in verbose $string assignment around line 721 ???
# TERMINOLOGY update, naming convention:
# "chain" the datastructure
# "element" the individual units that compose a chain
# "label" the unique name of a single element
# "position" the position of an element into the chain according to a
# particular coordinate system (e.g. counting from the start)
# "value" what is stored in a single element
use Carp qw(croak cluck carp); # as of 2.3
use strict; # as of 2.27
use integer; # WARNING: this is to increase performance
# a little bit of attention has to be given if float need to
# be stored as elements of the array
# the use of this "integer" affects all operations but not
# assignments. So float CAN be assigned as elements of the chain
# BUT, if you assign $z=-1.8;, $z will be equal to -1 because
# "-" counts as a unary operation!
=head2 _updown_chain2string
Title : chain2string
Usage : $string = Bio::LiveSeq::Chain::chain2string("down",$chain,6,9)
Function: reads the contents of the chain, outputting a string
Returns : a string
Examples:
: down_chain2string($chain) -> all the chain from begin to end
: down_chain2string($chain,6) -> from 6 to the end
: down_chain2string($chain,6,4) -> from 6, going on 4 elements
: down_chain2string($chain,6,"",10) -> from 6 to 10
: up_chain2string($chain,10,"",6) -> from 10 to 6 upstream
Defaults: start=first element; if len undef, goes to last
if last undef, goes to end
if last defined, it overrides len (undefining it)
Error code: -1
Args : "up"||"down" as first argument to specify the reading direction
reference (to the chain)
[first] [len] [last] optional integer arguments to specify how
much and from (and to) where to read
=cut
# methods rewritten 2.61
sub up_chain2string {
_updown_chain2string("up",@_);
}
sub down_chain2string {
_updown_chain2string("down",@_);
}
sub _updown_chain2string {
my ($direction,$chain,$first,$len,$last)=@_;
unless($chain) { cluck "no chain input"; return (-1); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
unless ($first) { $first=$end; } # if undef or 0, use $end
} else { # defaults to "down"
$flow=1; # used to determine the direction of chain navigation
unless ($first) { $first=$begin; } # if undef or 0, use $begin
}
unless($chain->{$first}) {
cluck "label for first not defined"; return (-1); }
if ($last) { # if last is defined, it gets priority and len is not used
unless($chain->{$last}) {
cluck "label for last not defined"; return (-1); }
if ($len) {
warn "Warning chain2string: argument LAST:$last overriding LEN:$len!";
undef $len;
}
} else {
if ($direction eq "up") {
$last=$begin; # if last not defined, go 'till begin (or upto len elements)
} else {
$last=$end; # if last not defined, go 'till end (or upto len elements)
}
}
my ($string,@array);
my $label=$first; my $i=1;
my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
# proceed for len elements or until last, whichever comes first
# if $len undef goes till end
while (($label) && ($label != $afterlast) && ($i <= ($len || $i + 1))) {
@array=@{$chain->{$label}};
$string .= $array[0];
$label = $array[$flow];
$i++;
}
return ($string); # if chain is interrupted $string won't be complete
}
=head2 _updown_labels
Title : labels
Usage : @labels = Bio::LiveSeq::Chain::_updown_labels("down",$chain,4,16)
Function: returns all the labels in a chain or those between two
specified ones (termed "first" and "last")
Returns : a reference to an array containing the labels
Args : "up"||"down" as first argument to specify the reading direction
reference (to the chain)
[first] [last] (integer for the starting and eneding labels)
=cut
# arguments: CHAIN_REF [FIRSTLABEL] [LASTLABEL]
# returns: reference to array containing the labels
sub down_labels {
my ($chain,$first,$last)=@_;
_updown_labels("down",$chain,$first,$last);
}
sub up_labels {
my ($chain,$first,$last)=@_;
_updown_labels("up",$chain,$first,$last);
}
# arguments: "up"||"down" CHAIN_REF [FIRSTLABEL] [LASTLABEL]
# returns: reference to array containing the labels
sub _updown_labels {
my ($direction,$chain,$first,$last)=@_;
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") { $flow=2;
unless ($first) { $first=$end; }
unless ($last) { $last=$begin; }
} else { $flow=1;
unless ($last) { $last=$end; }
unless ($first) { $first=$begin; }
}
unless($chain->{$first}) { warn "not existing label $first"; return (0); }
unless($chain->{$last}) { warn "not existing label $last"; return (0); }
my $label=$first; my @labels;
my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
while (($label)&&($label != $afterlast)) {
push(@labels,$label);
$label=$chain->{$label}[$flow];
}
return (\@labels); # if chain is interrupted @labels won't be complete
}
=head2 start
Title : start
Usage : $start = Bio::LiveSeq::Chain::start()
Returns : the label marking the start of the chain
Errorcode: -1
Args : none
=cut
sub start {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (-1); }
return ($chain->{'begin'});
}
=head2 end
Title : end
Usage : $end = Bio::LiveSeq::Chain::end()
Returns : the label marking the end of the chain
Errorcode: -1
Args : none
=cut
sub end {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (-1); }
return ($chain->{'end'});
}
=head2 label_exists
Title : label_exists
Usage : $check = Bio::LiveSeq::Chain::label_exists($chain,$label)
Function: It checks if a label is defined, i.e. if an element is there or
is not there anymore
Returns : 1 if the label exists, 0 if it is not there, -1 error
Errorcode: -1
Args : reference to the chain, integer
=cut
sub label_exists {
my ($chain,$label)=@_;
unless($chain) { cluck "no chain input"; return (-1); }
if ($label && $chain->{$label}) { return (1); } else { return (0) };
}
=head2 down_get_pos_of_label
Title : down_get_pos_of_label
Usage : $position = Bio::LiveSeq::Chain::down_get_pos_of_label($chain,$label,$first)
Function: returns the position of $label counting from $first, i.e. taking
$first as 1 of coordinate system. If $first is not specified it will
count from the start of the chain.
Returns :
Errorcode: 0
Args : reference to the chain, integer (the label of interest)
optional: integer (a different label that will be taken as the
first one, i.e. the one to count from)
Note: It counts "downstream". To proceed backward use up_get_pos_of_label
=cut
sub down_get_pos_of_label {
#down_chain2string($_[0],$_[2],undef,$_[1],"counting");
my ($chain,$label,$first)=@_;
_updown_count("down",$chain,$first,$label);
}
sub up_get_pos_of_label {
#up_chain2string($_[0],$_[2],undef,$_[1],"counting");
my ($chain,$label,$first)=@_;
_updown_count("up",$chain,$first,$label);
}
=head2 down_subchain_length
Title : down_subchain_length
Usage : $length = Bio::LiveSeq::Chain::down_subchain_length($chain,$first,$last)
Function: returns the length of the chain between the labels "first" and "last", included
Returns : integer
Errorcode: 0
Args : reference to the chain, integer, integer
Note: It counts "downstream". To proceed backward use up_subchain_length
=cut
# arguments: chain_ref [first] [last]
# returns the length of the chain between first and last (included)
sub down_subchain_length {
#down_chain2string($_[0],$_[1],undef,$_[2],"counting");
my ($chain,$first,$last)=@_;
_updown_count("down",$chain,$first,$last);
}
sub up_subchain_length {
#up_chain2string($_[0],$_[1],undef,$_[2],"counting");
my ($chain,$first,$last)=@_;
_updown_count("up",$chain,$first,$last);
}
# arguments: DIRECTION CHAIN_REF FIRSTLABEL LASTLABEL
# errorcode 0
sub _updown_count {
my ($direction,$chain,$first,$last)=@_;
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") { $flow=2;
unless ($first) { $first=$end; }
unless ($last) { $last=$begin; }
} else { $flow=1;
unless ($last) { $last=$end; }
unless ($first) { $first=$begin; }
}
unless($chain->{$first}) { warn "not existing label $first"; return (0); }
unless($chain->{$last}) { warn "not existing label $last"; return (0); }
my $label=$first; my $count;
my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
while (($label)&&($label != $afterlast)) {
$count++;
$label=$chain->{$label}[$flow];
}
return ($count); # if chain is interrupted, $i will be up to the breaking point
}
=head2 invert_chain
Title : invert_chain
Usage : $errorcode=Bio::LiveSeq::Chain::invert_chain($chain)
Function: completely inverts the order of the chain elements; begin is swapped with end and all links updated (PREV&NEXT fields swapped)
Returns : 1 if all OK, 0 if errors
Errorcode: 0
Args : reference to the chain
=cut
sub invert_chain {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the last element
my ($label,@array);
$label=$begin; # starts from the beginning
while ($label) { # proceed with linked elements, swapping PREV and NEXT
@array=@{$chain->{$label}};
($chain->{$label}[1],$chain->{$label}[2])=($array[2],$array[1]); # swap
$label = $array[1]; # go to the next one
}
# now swap begin and end fields
($chain->{'begin'},$chain->{'end'})=($end,$begin);
return (1); # that's it
}
# warning that method has changed name
#sub mutate_element {
#croak "Warning: old method name. Please update code to 'set_value_at_label'\n";
# &set_value_at_label;
#}
=head2 down_get_value_at_pos
Title : down_get_value_at_pos
Usage : $value = Bio::LiveSeq::Chain::down_get_value_at_pos($chain,$position,$first)
Function: used to access the value of the chain at a particular position instead than directly with a label pointer. It will count the position from the start of the chain or from the label $first, if $first is specified
Returns : whatever is stored in the element of the chain
Errorcode: 0
Args : reference to the chain, integer, [integer]
Note: It works "downstream". To proceed backward use up_get_value_at_pos
=cut
#sub get_value_at_pos {
#croak "Please use instead: down_get_value_at_pos";
##&down_get_value_at_pos;
#}
sub down_get_value_at_pos {
my ($chain,$position,$first)=@_;
my $label=down_get_label_at_pos($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
return _get_value($chain,$label);
}
sub up_get_value_at_pos {
my ($chain,$position,$first)=@_;
my $label=up_get_label_at_pos($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
return _get_value($chain,$label);
}
=head2 down_set_value_at_pos
Title : down_set_value_at_pos
Usage : $errorcode = Bio::LiveSeq::Chain::down_set_value_at_pos($chain,$newvalue,$position,$first)
Function: used to store a new value inside an element of the chain at a particular position instead than directly with a label pointer. It will count the position from the start of the chain or from the label $first, if $first is specified
Returns : 1
Errorcode: 0
Args : reference to the chain, newvalue, integer, [integer]
(newvalue can be: integer, string, object reference, hash ref)
Note: It works "downstream". To proceed backward use up_set_value_at_pos
Note2: If the $newvalue is undef, it will delete the contents of the
element but it won't remove the element from the chain.
=cut
#sub set_value_at_pos {
#croak "Please use instead: down_set_value_at_pos";
##&down_set_value_at_pos;
#}
sub down_set_value_at_pos {
my ($chain,$value,$position,$first)=@_;
my $label=down_get_label_at_pos($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
_set_value($chain,$label,$value);
return (1);
}
sub up_set_value_at_pos {
my ($chain,$value,$position,$first)=@_;
my $label=up_get_label_at_pos($chain,$position,$first);
# check place of change
if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
_set_value($chain,$label,$value);
return (1);
}
=head2 down_set_value_at_label
Title : down_set_value_at_label
Usage : $errorcode = Bio::LiveSeq::Chain::down_set_value_at_label($chain,$newvalue,$label)
Function: used to store a new value inside an element of the chain defined by its label.
Returns : 1
Errorcode: 0
Args : reference to the chain, newvalue, integer
(newvalue can be: integer, string, object reference, hash ref)
Note: It works "downstream". To proceed backward use up_set_value_at_label
Note2: If the $newvalue is undef, it will delete the contents of the
element but it won't remove the element from the chain.
=cut
sub set_value_at_label {
my ($chain,$value,$label)=@_;
unless($chain) { cluck "no chain input"; return (0); }
# check place of change
unless($chain->{$label}) { # complain if label doesn't exist
warn "not existing element $label"; return (0); }
_set_value($chain,$label,$value);
return (1);
}
=head2 down_get_value_at_label
Title : down_get_value_at_label
Usage : $value = Bio::LiveSeq::Chain::down_get_value_at_label($chain,$label)
Function: used to access the value of the chain from one element defined by its label.
Returns : whatever is stored in the element of the chain
Errorcode: 0
Args : reference to the chain, integer
Note: It works "downstream". To proceed backward use up_get_value_at_label
=cut
sub get_value_at_label {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (0); }
my $label = $_[1]; # the name of the element
# check place of change
unless($chain->{$label}) { # complain if label doesn't exist
warn "not existing label $label"; return (0); }
return _get_value($chain,$label);
}
# arguments: CHAIN_REF LABEL VALUE
sub _set_value {
my ($chain,$label,$value)=@_;
$chain->{$label}[0]=$value;
}
# arguments: CHAIN_REF LABEL
sub _get_value {
my ($chain,$label)=@_;
return $chain->{$label}[0];
}
=head2 down_get_label_at_pos
Title : down_get_label_at_pos
Usage : $label = Bio::LiveSeq::Chain::down_get_label_at_pos($chain,$position,$first)
Function: used to retrieve the label of an an element of the chain at a particular position. It will count the position from the start of the chain or from the label $first, if $first is specified
Returns : integer
Errorcode: 0
Args : reference to the chain, integer, [integer]
Note: It works "downstream". To proceed backward use up_get_label_at_pos
=cut
# arguments: CHAIN_REF POSITION [FIRST]
# returns: LABEL of element found counting from FIRST
sub down_get_label_at_pos {
_updown_get_label_at_pos("down",@_);
}
sub up_get_label_at_pos {
_updown_get_label_at_pos("up",@_);
}
# arguments: [DIRECTION] CHAIN_REF POSITION [FIRST]
# Default DIRECTION="down"
# if FIRST is undefined, FIRST=START (if DIRECTION=down) or FIRST=END (up)
sub _updown_get_label_at_pos {
my ($direction,$chain,$position,$first)=@_;
unless($chain) { cluck "no chain input"; return (0); }
my $begin=$chain->{'begin'}; # the label of the BEGIN element
my $end=$chain->{'end'}; # the label of the END element
my $flow;
if ($direction eq "up") { $flow=2; unless ($first) { $first=$end; }
} else { $flow=1; unless ($first) { $first=$begin; } }
unless($chain->{$first}) { warn "not existing label $first"; return (0); }
my $label=$first;
my $i=1;
while ($i < $position) {
$label=$chain->{$label}[$flow];
$i++;
unless ($label) { return (0); } # chain ended before position reached
}
return ($label);
}
# for english_concerned, latin_unconcerned people
sub preinsert_string { &praeinsert_string }
sub preinsert_array { &praeinsert_array }
# praeinsert_string CHAIN_REF STRING [POSITION]
# the chars of STRING are passed to praeinsert_array
# the chars are inserted in CHAIN, before POSITION
# if POSITION is undef, default is to prepend the string to the beginning
# i.e. POSITION is START of CHAIN
sub praeinsert_string {
my @string=split(//,$_[1]);
praeinsert_array($_[0],\@string,$_[2]);
}
# postinsert_string CHAIN_REF STRING [POSITION]
# the chars of STRING are passed to postinsert_array
# the chars are inserted in CHAIN, after POSITION
# if POSITION is undef, default is to append the string to the end
# i.e. POSITION is END of CHAIN
sub postinsert_string {
my @string=split(//,$_[1]);
postinsert_array($_[0],\@string,$_[2]);
}
# praeinsert_array CHAIN_REF ARRAY_REF [POSITION]
# the elements of ARRAY are inserted in CHAIN, before POSITION
# if POSITION is undef, default is to prepend the elements to the beginning
# i.e. POSITION is START of CHAIN
sub praeinsert_array {
_praepostinsert_array($_[0],"prae",$_[1],$_[2]);
}
# postinsert_array CHAIN_REF ARRAY_REF [POSITION]
# the elements of ARRAY are inserted in CHAIN, after POSITION
# if POSITION is undef, default is to append the elements to the end
# i.e. POSITION is END of CHAIN
sub postinsert_array {
_praepostinsert_array($_[0],"post",$_[1],$_[2]);
}
=head2 _praepostinsert_array
Title : _praepostinsert_array
Usage : ($insbegin,$insend) = Bio::LiveSeq::Chain::_praepostinsert_array($chainref,"post",$arrayref,$position)
Function: the elements of the array specified by $arrayref are inserted (creating a new subchain) in the chain specified by $chainref, before or after (depending on the "prae"||"post" keyword passed as second argument) the specified position.
Returns : two labels: the first and the last of the inserted subchain
Defaults: if no position is specified, the new chain will be inserted after
(post) the first element of the chain
Errorcode: 0
Args : chainref, "prae"||"post", arrayref, integer (position)
=cut
# returns: 0 if errors, otherwise returns references of begin and end of
# the insertion
sub _praepostinsert_array {
my $chain=$_[0];
unless($chain) { cluck "no chain input"; return (0); }
my $praepost=$_[1] || "post"; # defaults to post
my ($prae,$post);
my $position=$_[3];
my $begin=$chain->{'begin'}; # the name of the first element of the chain
my $end=$chain->{'end'}; # the name of the the last element of the chain
# check if prae or post insertion and prepare accordingly
if ($praepost eq "prae") {
$prae=1;
unless (($position eq 0)||($position)) { $position=$begin; } # if undef, use $begin
} else {
$post=1;
unless (($position eq 0)||($position)) { $position=$end; } # if undef, use $end
}
# check place of insertion
unless($chain->{$position}) { # complain if position doesn't exist
warn ("Warning _praepostinsert_array: not existing element $position");
return (0);
}
# check if there are elements to insert
my $elements=$_[2]; # reference to the array containing the new elements
my $elements_count=scalar(@{$elements});
unless ($elements_count) {
warn ("Warning _praepostinsert_array: no elements input"); return (0); }
# create new chainelements with offset=firstfree(chain)
my ($insertbegin,$insertend)=_create_chain_elements($chain,$elements);
# DEBUGGING
#print "Executing ${praepost}insertion of $elements_count elements ('@{$elements}') at position: $position\n";
# attach the new chain to the old chain
# 4 cases: prae@begin, prae@middle, post@middle, post@end
# NOTE: in case of double joinings always join wisely so not to
# delete the PREV/NEXT attribute before it is needed
my $noerror=1;
if ($prae) {
if ($position==$begin) { # 1st case: prae@begin
$noerror=_join_chain_elements($chain,$insertend,$begin);
$chain->{'begin'}=$insertbegin;
} else { # 2nd case: prae@middle
$noerror=_join_chain_elements($chain,up_element($chain,$position),$insertbegin);
$noerror=_join_chain_elements($chain,$insertend,$position);
}
} elsif ($post) {
if ($position==$end) { # 4th case: post@end
$noerror=_join_chain_elements($chain,$end,$insertbegin);
$chain->{'end'}=$insertend;
} else { # 3rd case: post@middle # note the order of joins (important)
$noerror=_join_chain_elements($chain,$insertend,down_element($chain,$position));
$noerror=_join_chain_elements($chain,$position,$insertbegin);
}
} else { # this should never happen
die "_praepostinsert_array: Something went very wrong";
}
# check for errors and return begin,end of insertion
if ($noerror) {
return ($insertbegin,$insertend);
} else { # something went wrong with the joinings
warn "Warning _praepostinsert_array: Joining of insertion failed";
return (0);
}
}
# create new chain elements with offset=firstfree
# arguments: CHAIN_REF ARRAY_REF
# returns: pointers to BEGIN and END of new chained elements created
# returns 0 if error(s) encountered
sub _create_chain_elements {
my $chain=$_[0];
unless($chain) {
warn ("Warning _create_chain_elements: no chain input"); return (0); }
my $arrayref=$_[1];
my $array_count=scalar(@{$arrayref});
unless ($array_count) {
warn ("Warning _create_chain_elements: no elements input"); return (0); }
my $begin=$chain->{'firstfree'};
my $i=$begin-1;
my $element;
foreach $element (@{$arrayref}) {
$i++;
$chain->{$i}=[$element,$i+1,$i-1];
}
my $end=$i;
$chain->{'firstfree'}=$i+1; # what a new added element should be called
$chain->{'size'} += $end-$begin+1; # increase size of chain
# leave sticky edges (to be joined by whoever called this subroutine)
$chain->{$begin}[2]=undef;
$chain->{$end}[1]=undef;
return ($begin,$end); # return pointers to first and last of the newelements
}
# argument: CHAIN_REF ELEMENT
# returns: name of DOWN/NEXT element (the downstream one)
# returns -1 if error encountered (e.g. chain or elements undefined)
# returns 0 if there's no DOWN element
sub down_element {
_updown_element("down",@_);
}
# argument: CHAIN_REF ELEMENT
# returns: name of UP/PREV element (the upstream one)
# returns -1 if error encountered (e.g. chain or elements undefined)
# returns 0 if there's no UP element
sub up_element {
_updown_element("up",@_);
}
# used by both is_up_element and down_element
sub _updown_element {
my $direction=$_[0] || "down"; # defaults to downstream
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
} else {
$flow=1; # used to determine the direction of chain navigation
}
my $chain=$_[1];
unless($chain) {
warn ("Warning ${direction}_element: no chain input"); return (-1); }
my $me = $_[2]; # the name of the element
my $it = $chain->{$me}[$flow]; # the prev||next one, upstream||downstream
if ($it) {
return ($it); # return the name of prev||next element
} else {
return (0); # there is no prev||next element ($it is undef)
}
}
# used by both is_downstream and is_upstream
sub _is_updownstream {
my $direction=$_[0] || "down"; # defaults to downstream
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
} else {
$flow=1; # used to determine the direction of chain navigation
}
my $chain=$_[1];
unless($chain) {
warn ("Warning is_${direction}stream: no chain input"); return (-1); }
my $first=$_[2]; # the name of the first element
my $second=$_[3]; # the name of the first element
if ($first==$second) {
warn ("Warning is_${direction}stream: first==second!!"); return (0); }
unless($chain->{$first}) {
warn ("Warning is_${direction}stream: first element not defined"); return (-1); }
unless($chain->{$second}) {
warn ("Warning is_${direction}stream: second element not defined"); return (-1); }
my ($label,@array);
$label=$first;
my $found=0;
while (($label)&&(!($found))) { # searches till the end or till found
if ($label==$second) {
$found=1;
}
@array=@{$chain->{$label}};
$label = $array[$flow]; # go to the prev||next one, upstream||downstream
}
return $found;
}
=head2 is_downstream
Title : is_downstream
Usage : Bio::LiveSeq::Chain::is_downstream($chainref,$firstlabel,$secondlabel)
Function: checks if SECONDlabel follows FIRSTlabel
It runs downstream the elements of the chain from FIRST searching
for SECOND.
Returns : 1 if SECOND is found /after/ FIRST; 0 otherwise (i.e. if it
reaches the end of the chain without having found it)
Errorcode -1
Args : two labels (integer)
=cut
sub is_downstream {
_is_updownstream("down",@_);
}
=head2 is_upstream
Title : is_upstream
Usage : Bio::LiveSeq::Chain::is_upstream($chainref,$firstlabel,$secondlabel)
Function: checks if SECONDlabel follows FIRSTlabel
It runs upstream the elements of the chain from FIRST searching
for SECOND.
Returns : 1 if SECOND is found /after/ FIRST; 0 otherwise (i.e. if it
reaches the end of the chain without having found it)
Errorcode -1
Args : two labels (integer)
=cut
sub is_upstream {
_is_updownstream("up",@_);
}
=head2 check_chain
Title : check_chain
Usage : @errorcodes = Bio::LiveSeq::Chain::check_chain()
Function: a wraparound to a series of check for consistency of the chain
It will check for boundaries, size, backlinking and forwardlinking
Returns : array of 4 warn codes, each can be 1 (all ok) or 0 (something wrong)
Errorcode: 0
Args : none
Note : this is slow and through. It is not really needed. It is mostly
a code-developer tool.
=cut
sub check_chain {
my $chain=$_[0];
unless($chain) {
warn ("Warning check_chain: no chain input"); return (-1); }
my ($warnbound,$warnsize,$warnbacklink,$warnforlink);
$warnbound=&_boundcheck; # passes on the arguments of the subroutine
$warnsize=&_sizecheck;
$warnbacklink=&_downlinkcheck;
$warnforlink=&_uplinkcheck;
return ($warnbound,$warnsize,$warnbacklink,$warnforlink);
}
# consistency check for forwardlinks walking upstream
# argument: a chain reference
# returns: 1 all OK 0 problems
sub _uplinkcheck {
_updownlinkcheck("up",@_);
}
# consistency check for backlinks walking downstream
# argument: a chain reference
# returns: 1 all OK 0 problems
sub _downlinkcheck {
_updownlinkcheck("down",@_);
}
# consistency check for links, common to _uplinkcheck and _downlinkcheck
# argument: "up"||"down", check_ref
# returns: 1 all OK 0 problems
sub _updownlinkcheck {
my $direction=$_[0] || "down"; # defaults to downstream
my ($flow,$wolf);
my $chain=$_[1];
unless($chain) {
warn ("Warning _${direction}linkcheck: no chain input"); return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the last element
my ($label,@array,$me,$it,$itpoints);
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
$wolf=1;
$label=$end; # start from end
} else {
$flow=1; # used to determine the direction of chain navigation
$wolf=2;
$label=$begin; # start from beginning
}
my $warncode=1;
while ($label) { # proceed with linked elements, checking neighbours
$me=$label;
@array=@{$chain->{$label}};
$label = $array[$flow]; # go to the next one
$it=$label;
if ($it) { # no sense in checking if next one not defined (END element)
@array=@{$chain->{$label}};
$itpoints=$array[$wolf];
unless ($me==$itpoints) {
warn "Warning: ${direction}LinkCheck: LINK wrong in $it, that doesn't point back to me ($me). It points to $itpoints\n";
$warncode=0;
}
}
}
return $warncode;
}
# consistency check for size of chain
# argument: a chain reference
# returns: 1 all OK 0 wrong size
sub _sizecheck {
my $chain=$_[0];
unless($chain) {
warn ("Warning _sizecheck: no chain input"); return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $warncode=1;
my ($label,@array);
my $size=$chain->{'size'};
my $count=0;
$label=$begin;
while ($label) { # proceed with linked elements, counting
@array=@{$chain->{$label}};
$label = $array[1]; # go to the next one
$count++;
}
if ($size != $count) {
warn "Size check reports error: assumed size: $size, real size: $count ";
$warncode=0;
}
return $warncode;
}
# consistency check for begin and end (boundaries)
# argument: a chain reference
# returns: 1 all OK 0 problems
sub _boundcheck {
my $chain=$_[0];
unless($chain) {
warn ("Warning _boundcheck: no chain input"); return (0); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the (supposedly) last element
my $warncode=1;
# check SYNC of beginning
if (($begin)&&($chain->{$begin})) { # if the BEGIN points to existing element
if ($chain->{$begin}[2]) { # if BEGIN element has PREV not undef
warn "Warning: BEGIN element has PREV field defined \n";
warn "\tWDEBUG begin: $begin\t";
warn "\tWDEBUG begin's PREV: $chain->{$begin}[2] \n";
$warncode=0;
}
} else {
warn "Warning: BEGIN key of chain does not point to existing element!\n";
warn "\tWDEBUG begin: $begin\n";
$warncode=0;
}
# check SYNC of end
if (($end)&&($chain->{$end})) { # if the END points to an existing element
if ($chain->{$end}[1]) { # if END element has NEXT not undef
warn "Warning: END element has NEXT field defined \n";
warn "\tWDEBUG end: $end\t";
warn "\tWDEBUG end's NEXT: $chain->{$end}[1] \n";
$warncode=0;
}
} else {
warn "Warning: END key of chain does not point to existing element!\n";
warn "\tWDEBUG end: $end\n";
$warncode=0;
}
return $warncode;
}
# arguments: chain_ref
# returns: the size of the chain (the number of elements)
# return code -1: unexistant chain, errors...
sub chain_length {
my $chain=$_[0];
unless($chain) {
warn ("Warning chain_length: no chain input"); return (-1); }
my $size=$chain->{'size'};
if ($size) {
return ($size);
} else {
return (-1);
}
}
# arguments: chain ref, first element name, second element name
# returns: 1 or 0 (1 ok, 0 errors)
sub _join_chain_elements {
my $chain=$_[0];
unless($chain) {
warn ("Warning _join_chain_elements: no chain input"); return (0); }
my $leftelem=$_[1];
my $rightelem=$_[2];
unless(($leftelem)&&($rightelem)) {
warn ("Warning _join_chain_elements: element arguments??"); return (0); }
if (($chain->{$leftelem})&&($chain->{$rightelem})) { # if the elements exist
$chain->{$leftelem}[1]=$rightelem;
$chain->{$rightelem}[2]=$leftelem;
return 1;
} else {
warn ("Warning _join_chain_elements: elements not defined");
return 0;
}
}
=head2 splice_chain
Title : splice_chain
Usage : @errorcodes = Bio::LiveSeq::Chain::splice_chain($chainref,$first,$length,$last)
Function: removes the elements designated by FIRST and LENGTH from a chain.
The chain shrinks accordingly. If LENGTH is omitted, removes
everything from FIRST onward.
If END is specified, LENGTH is ignored and instead the removal
occurs from FIRST to LAST.
Returns : the elements removed as a string
Errorcode: -1
Args : chainref, integer, integer, integer
=cut
sub splice_chain {
my $chain=$_[0];
unless($chain) {
warn ("Warning splice_chain: no chain input"); return (-1); }
my $begin=$chain->{'begin'}; # the name of the first element
my $end=$chain->{'end'}; # the name of the (supposedly) last element
my $first=$_[1];
unless (($first eq 0)||($first)) { $first=$begin; } # if undef, use $begin
my $len=$_[2];
my $last=$_[3];
my (@array, $string);
my ($beforecut,$aftercut);
unless($chain->{$first}) {
warn ("Warning splice_chain: first element not defined"); return (-1); }
if ($last) { # if last is defined, it gets priority and len is not used
unless($chain->{$last}) {
warn ("Warning splice_chain: last element not defined"); return (-1); }
if ($len) {
warn ("Warning splice_chain: argument LAST:$last overriding LEN:$len!");
undef $len;
}
} else {
$last=$end; # if last not defined, go 'till end (or to len, whichever 1st)
}
$beforecut=$chain->{$first}[2]; # what's the element before 1st deleted?
# if it is undef then it means we are splicing since the beginning
my $i=1;
my $label=$first;
my $afterlast=$chain->{$last}[1]; # if $last=$end $afterlast should be undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
# proceed for len elements or until the end, whichever comes first
# if len undef goes till last
while (($label)&&($label != $afterlast) && ($i <= ($len || $i + 1))) {
@array=@{$chain->{$label}};
$string .= $array[0];
$aftercut = $array[1]; # what's the element next last deleted?
# also used as savevar to change label posdeletion
delete $chain->{$label}; # this can be deleted now
$label=$aftercut; # label is updated using the savevar
$i++;
}
# Now fix the chain (sticky edges, fields)
# 4 cases: cut in the middle, cut from beginning, cut till end, cut all
#print "\n\tstickyDEBUG beforecut: $beforecut "; # DEBUG
#print "\taftercut: $aftercut \n"; # DEBUG
if ($beforecut) {
if ($aftercut) { # 1st case, middle cut
_join_chain_elements($chain,$beforecut,$aftercut);
} else { # 3rd case, end cut
$chain->{'end'}=$beforecut; # update the END field
$chain->{$beforecut}[1]=undef; # since we cut till the end
}
} else {
if ($aftercut) { # 2nd case, begin cut
$chain->{'begin'}=$aftercut; # update the BEGIN field
$chain->{$aftercut}[2]=undef; # since we cut from beginning
} else { # 4th case, all has been cut
$chain->{'begin'}=undef;
$chain->{'end'}=undef;
}
}
$chain->{'size'}=($chain->{'size'}) - $i + 1; # update the SIZE field
return $string;
}
# arguments: CHAIN_REF POSITION [FIRST]
# returns: element counting POSITION from FIRST or from START if FIRST undef
# i.e. returns the element at POSITION counting from FIRST
#sub element_at_pos {
#croak "Warning: old method name. Please update code to 'down_get_label_at_position'\n";
##&down_element_at_pos;
#}
#sub up_element_at_pos {
## old wraparound
##my @array=up_chain2string($_[0],$_[2],$_[1],undef,"elements");
##return $array[-1];
#croak "old method name. Update code to: up_get_label_at_position";
##&up_get_label_at_pos;
#}
#sub down_element_at_pos {
## old wraparound
##my @array=down_chain2string($_[0],$_[2],$_[1],undef,"elements");
##return $array[-1];
#croak "old method name. Update code to: down_get_label_at_position";
##&down_get_label_at_pos;
#}
# arguments: CHAIN_REF ELEMENT [FIRST]
# returns: the position of ELEMENT counting from FIRST or from START
#i if FIRST is undef
# i.e. returns the Number of elements between FIRST and ELEMENT
# i.e. returns the position of element taking FIRST as 1 of coordinate system
#sub pos_of_element {
#croak ("Warning: old and ambiguous method name. Please update code to 'down_get_pos_of_label'\n");
##&down_pos_of_element;
#}
#sub up_pos_of_element {
#croak ("Warning: old method name. Please update code to 'up_get_pos_of_label'\n");
##up_chain2string($_[0],$_[2],undef,$_[1],"counting");
#}
#sub down_pos_of_element {
#croak ("Warning: old method name. Please update code to 'down_get_pos_of_label'\n");
##down_chain2string($_[0],$_[2],undef,$_[1],"counting");
#}
# wraparounds to calculate length of subchain from first to last
# arguments: chain_ref [first] [last]
#sub subchain_length {
#croak "Warning: old method name. Please update code to 'down_subchain_length'\n";
##&down_subchain_length;
#}
# wraparounds to have elements output
# same arguments as chain2string
# returns label|name of every element
#sub elements {
#croak ("Warning: method no more supported. Please update code to 'down_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n");
##&down_elements;
#}
#sub up_elements {
#croak ("Warning: method no more supported. Please update code to 'up_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n");
##up_chain2string($_[0],$_[1],$_[2],$_[3],"elements");
#}
#sub down_elements {
#croak ("Warning: method no more supported. Please update code to 'down_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n");
##down_chain2string($_[0],$_[1],$_[2],$_[3],"elements");
#}
# wraparounds to have verbose output
# same arguments as chain2string
# returns the chain in a very verbose way
sub chain2string_verbose {
carp "Warning: method no more supported.\n";
&old_down_chain2string_verbose;
}
sub up_chain2string_verbose {
carp "Warning: method no more supported.\n";
old_up_chain2string($_[0],$_[1],$_[2],$_[3],"verbose");
}
sub down_chain2string_verbose {
carp "Warning: method no more supported.\n";
old_down_chain2string($_[0],$_[1],$_[2],$_[3],"verbose");
}
#sub chain2string {
#croak ("Warning: old method name. Please update code to 'down_chain2string'\n");
##&down_chain2string;
#}
sub old_up_chain2string {
old_updown_chain2string("up",@_);
}
sub old_down_chain2string {
old_updown_chain2string("down",@_);
}
# common to up_chain2string and down_chain2string
# arguments: "up"||"down" chain_ref [first] [len] [last] [option]
# [option] can be any of "verbose", "counting", "elements"
# error: return -1
# defaults: start = first element; if len undef, goes to last
# if last undef, goes to end
# if last def it overrides len (that gets undef)
# returns: a string
# example usage: down_chain2string($chain) -> all the chain from begin to end
# example usage: down_chain2string($chain,6) -> from 6 to the end
# example usage: down_chain2string($chain,6,4) -> from 6, going on 4 elements
# example usage: down_chain2string($chain,6,"",10) -> from 6 to 10
# example usage: up_chain2string($chain,10,"",6) -> from 10 to 6 upstream
sub old_updown_chain2string {
my ($direction,$chain,$first,$len,$last,$option)=@_;
unless($chain) {
warn ("Warning chain2string: no chain input"); return (-1); }
my $begin=$chain->{'begin'}; # the name of the BEGIN element
my $end=$chain->{'end'}; # the name of the END element
my $flow;
if ($direction eq "up") {
$flow=2; # used to determine the direction of chain navigation
unless ($first) { $first=$end; } # if undef or 0, use $end
} else { # defaults to "down"
$flow=1; # used to determine the direction of chain navigation
unless ($first) { $first=$begin; } # if undef or 0, use $begin
}
unless($chain->{$first}) {
warn ("Warning chain2string: first element not defined"); return (-1); }
if ($last) { # if last is defined, it gets priority and len is not used
unless($chain->{$last}) {
warn ("Warning chain2string: last element not defined"); return (-1); }
if ($len) {
warn ("Warning chain2string: argument LAST:$last overriding LEN:$len!");
undef $len;
}
} else {
if ($direction eq "up") {
$last=$begin; # if last not defined, go 'till begin (or upto len elements)
} else {
$last=$end; # if last not defined, go 'till end (or upto len elements)
}
}
my (@array, $string, $count);
# call for verbosity (by way of chain2string_verbose);
my $verbose=0; my $elements=0; my @elements; my $counting=0;
if ($option) { # keep strict happy
if ($option eq "verbose") { $verbose=1; }
if ($option eq "elements") { $elements=1; }
if ($option eq "counting") { $counting=1; }
}
if ($verbose) {
print "BEGIN=$begin"; print " END=$end"; print " SIZE=$chain->{'size'}";
print " FIRSTFREE=$chain->{'firstfree'} \n";
}
my $i=1;
my $label=$first;
my $afterlast=$chain->{$last}[$flow]; # if $last=$end $afterlast should be undef
unless (defined $afterlast) { $afterlast=0; } # keep strict happy
# proceed for len elements or until last, whichever comes first
# if $len undef goes till end
while (($label)&&($label != $afterlast) && ($i <= ($len || $i + 1))) {
@array=@{$chain->{$label}};
if ($verbose) {
$string .= "$array[2]_${label}_$array[1]=$array[0] ";
$count++;
} elsif ($elements) {
push (@elements,$label); # returning element names/references/identifiers
} elsif ($counting) {
$count++;
} else {
$string .= $array[0]; # returning element content
}
$label = $array[$flow]; # go to next||prev i.e. downstream||upstream
$i++;
}
#DEBUG#print "len: $len, first: $first, last: $last, afterlast=$afterlast \n";
if ($verbose) { print "TOTALprinted: $count\n"; }
if ($counting) {
return $count;
} elsif ($elements) {
return @elements;
} else {
return $string;
}
}
# sub string2schain
# --------> deleted, no more supported <--------
# creation of a single linked list/chain from a string
# basically could be recreated by taking the *2chain methods and
# omitting to set the 3rd field (label 2) containing the back links
# creation of a double linked list/chain from a string
# returns reference to a hash containing the chain
# arguments: STRING [OFFSET]
# defaults: OFFSET defaults to 1 if undef
# the chain will contain as elements the single characters in the string
sub string2chain {
my @string=split(//,$_[0]);
array2chain(\@string,$_[1]);
}
=head2 array2chain
Title : array2chain
Usage : $chainref = Bio::LiveSeq::Chain::array2chain($arrayref,$offset)
Function: creation of a double linked chain from an array
Returns : reference to a hash containing the chain
Defaults: OFFSET defaults to 1 if undef
Error code: 0
Args : a reference to an array containing the elements to be chainlinked
an optional integer > 0 (this will be the starting count for
the chain labels instead than having them begin from "1")
=cut
sub array2chain {
my $arrayref=$_[0];
my $array_count=scalar(@{$arrayref});
unless ($array_count) {
warn ("Warning array2chain: no elements input"); return (0); }
my $begin=$_[1];
if (defined $begin) {
if ($begin < 1) {
warn "Warning array2chain: Zero or Negative offsets not allowed"; return (0); }
} else {
$begin=1;
}
my ($element,%hash);
$hash{'begin'}=$begin;
my $i=$begin-1;
foreach $element (@{$arrayref}) {
$i++;
# hash with keys begin..end pointing to the arrays
$hash{$i}=[$element,$i+1,$i-1];
}
my $end=$i;
$hash{'end'}=$end;
$hash{firstfree}=$i+1; # what a new added element should be called
$hash{size}=$end-$begin+1; # how many elements in the chain
# eliminate pointers to unexisting elements
$hash{$begin}[2]=undef;
$hash{$end}[1]=undef;
return (\%hash);
}
1; # returns 1
| Java |
(function () {
'use strict';
angular.module('driver.tools.export', [
'ui.bootstrap',
'ui.router',
'driver.customReports',
'driver.resources',
'angular-spinkit',
]);
})();
| Java |
"use strict";
exports.__esModule = true;
var vueClient_1 = require("../../bibliotheque/vueClient");
console.log("* Chargement du script");
/* Test - déclaration d'une variable externe - Possible
cf. declare
*/
function centreNoeud() {
return JSON.parse(vueClient_1.contenuBalise(document, 'centre'));
}
function voisinsNoeud() {
var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins'));
var r = [];
var id;
for (id in v) {
r.push(v[id]);
}
return r;
}
function adresseServeur() {
return vueClient_1.contenuBalise(document, 'adresseServeur');
}
/*
type CanalChat = CanalClient<FormatMessageTchat>;
// A initialiser
var canal: CanalChat;
var noeud: Noeud<FormatSommetTchat>;
function envoyerMessage(texte: string, destinataire: Identifiant) {
let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte);
console.log("- Envoi du message brut : " + msg.brut());
console.log("- Envoi du message net : " + msg.net());
canal.envoyerMessage(msg);
initialiserEntree('message_' + destinataire, "");
}
// A exécuter après chargement de la page
function initialisation(): void {
console.log("* Initialisation après chargement du DOM ...")
noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat);
canal = new CanalClient<FormatMessageTchat>(adresseServeur());
canal.enregistrerTraitementAReception((m: FormatMessageTchat) => {
let msg = new MessageTchat(m);
console.log("- Réception du message brut : " + msg.brut());
console.log("- Réception du message net : " + msg.net());
posterNL('logChats', msg.net());
});
console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur());
// Gestion des événements pour les éléments du document.
//document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true);
let id: Identifiant;
let v = noeud.voisins();
for (id in v) {
console.log("id : " +id);
let idVal = id;
gererEvenementElement("boutonEnvoi_" + idVal, "click", e => {
console.log("id message_" + idVal);
console.log("entree : " + recupererEntree("message_" + idVal));
envoyerMessage(recupererEntree("message_" + idVal), idVal);
});
}
<form id="envoi">
<input type="text" id="message_id1">
<input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}."
onClick="envoyerMessage(this.form.message.value, "id1")">
</form>
console.log("* ... et des gestionnaires d'événements sur des éléments du document.");
}
// Gestion des événements pour le document
console.log("* Enregistrement de l'initialisation");
gererEvenementDocument('DOMContentLoaded', initialisation);
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', initialisation());
</script>
*/
//# sourceMappingURL=clientChat.js.map | Java |
(function ($) {
function FewbricksDevHelper() {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) {
return;
}
$this.initToggler();
$this.$mainElm.show();
}
/**
*
*/
this.initMainElm = function() {
$this.$mainElm = $('#fewbricks-info-pane');
if($this.$mainElm.length === 0) {
return false;
}
if(typeof fewbricksInfoPane !== 'undefined' && typeof fewbricksInfoPane.startHeight !== 'undefined') {
$this.toggleMainElm(fewbricksInfoPane.startHeight);
}
return true;
}
/**
*
*/
this.initToggler = function() {
$('[data-fewbricks-info-pane-toggler]')
.unbind('click')
.on('click', function() {
let height = $(this).attr('data-fewbricks-info-pane-height');
$this.toggleMainElm(height);
document.cookie = 'fewbricks_info_pane_height=' + height;
});
}
/**
*
*/
this.toggleMainElm = function(height) {
if(height === 'minimized') {
$this.$mainElm.attr('style', function(i, style)
{
return style && style.replace(/height[^;]+;?/g, '');
});
} else {
$this.$mainElm.height(height + 'vh');
}
}
/**
*
* @returns {*|boolean}
*/
this.mainElmIsFull = function() {
return $this.$mainElm.hasClass($this.cssClassFull);
}
}
$(document).ready(function () {
(new FewbricksDevHelper()).init();
});
})(jQuery);
| Java |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
#ifndef mozilla_dom_SVGPolylineElement_h
#define mozilla_dom_SVGPolylineElement_h
#include "nsSVGPolyElement.h"
nsresult NS_NewSVGPolylineElement(nsIContent **aResult,
already_AddRefed<nsINodeInfo> aNodeInfo);
typedef nsSVGPolyElement SVGPolylineElementBase;
namespace mozilla {
namespace dom {
class SVGPolylineElement MOZ_FINAL : public SVGPolylineElementBase
{
protected:
SVGPolylineElement(already_AddRefed<nsINodeInfo> aNodeInfo);
virtual JSObject* WrapNode(JSContext *cx, JSObject *scope) MOZ_OVERRIDE;
friend nsresult (::NS_NewSVGPolylineElement(nsIContent **aResult,
already_AddRefed<nsINodeInfo> aNodeInfo));
public:
// nsIContent interface
virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
};
} // namespace mozilla
} // namespace dom
#endif // mozilla_dom_SVGPolylineElement_h
| Java |
/**
* ...
* @author paul
*/
function initCBX(object, id, options) {
var design = "assets";
if(object == null){
jQuery.noConflict();
var cboxClass;
cboxClass = jQuery(id).attr("class");
if(jQuery.browser.msie && parseInt(jQuery.browser.version)<8 ){
jQuery(id).colorbox();
}
else{
if(cboxClass.indexOf("cboxElement") == -1){
if(options.classes.image.id){
jQuery('.'+options.classes.image.id).colorbox({transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
if(options.classes.video){
if(options.classes.video.id){
jQuery('.'+options.classes.video.id).colorbox({iframe:true, innerWidth:options.classes.video.innerWidth, innerHeight:options.classes.video.innerHeight, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
if(options.classes.swf){
if(options.classes.swf.id){
var cbxSWFSrc = jQuery('.'+options.classes.swf.id).attr("href");
var objEmbd = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" id="cbxSWF" ALIGN="">'+
'<PARAM NAME=movie VALUE="'+cbxSWFSrc+'">' +
'<PARAM NAME=quality VALUE=high>' +
'<PARAM NAME=wmode VALUE=transparent>'+
'<PARAM NAME=bgcolor VALUE=#333399>'+
'<EMBED src="'+cbxSWFSrc+'" quality=high wmode=transparent WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>'+
'</OBJECT>';
jQuery('.'+options.classes.swf.id).colorbox({html:objEmbd, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
}
}
jQuery(id).trigger('click');
return;
}
loadjQuery = function(filename) {
loadjQuery.getScript(object.path+"/"+filename);
loadjQuery.retry(0);
}
loadColorbox = function(filename) {
loadColorbox.getScript(object.path+"/"+filename);
loadColorbox.retry(0);
}
loadjQuery.getScript = function(filename) {
if(typeof jQuery == "undefined"){
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(script);
}
}
loadColorbox.getScript = function(filename) {
if(typeof jQuery.colorbox == "undefined"){
var link = document.createElement('link');
link.setAttribute('media', 'screen');
link.setAttribute('href', object.path+'/'+design+'/colorbox.css');
link.setAttribute('rel', 'stylesheet');
document.getElementsByTagName("head")[0].appendChild(link);
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(script);
}
}
loadjQuery.retry = function(time_elapsed) {
if (typeof jQuery == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadjQuery.retry(" + (time_elapsed + 200) + ")", 200);
}
}
else {
if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
}
loadColorbox.retry = function(time_elapsed) {
if (typeof jQuery.colorbox == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadColorbox.retry(" + (time_elapsed + 200) + ")", 200);
}
}
}
if(typeof jQuery == "undefined"){
loadjQuery("jquery-1.7.2.min.js");
}
else if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
| Java |
#include "gx2r_buffer.h"
#include "gx2r_displaylist.h"
#include "gx2_displaylist.h"
#include <common/log.h>
namespace gx2
{
void
GX2RBeginDisplayListEx(GX2RBuffer *displayList,
uint32_t unused,
GX2RResourceFlags flags)
{
if (!displayList || !displayList->buffer) {
return;
}
auto size = displayList->elemCount * displayList->elemSize;
GX2BeginDisplayListEx(displayList->buffer, size, TRUE);
}
uint32_t
GX2REndDisplayList(GX2RBuffer *displayList)
{
auto size = GX2EndDisplayList(displayList->buffer);
decaf_check(size < (displayList->elemCount * displayList->elemSize));
return size;
}
void
GX2RCallDisplayList(GX2RBuffer *displayList,
uint32_t size)
{
if (!displayList || !displayList->buffer) {
return;
}
GX2CallDisplayList(displayList->buffer, size);
}
void
GX2RDirectCallDisplayList(GX2RBuffer *displayList,
uint32_t size)
{
if (!displayList || !displayList->buffer) {
return;
}
GX2DirectCallDisplayList(displayList->buffer, size);
}
} // namespace gx2
| Java |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>LamPI 433Mhz controller for RaspberryPI</title>
</head>
<body>
<h1>Weather Dials/Meters </h1>
<p>This part of the documentation describes the weather screen and what you can (and sometimes cannot) do with weather sensors. Since version 1.8 LamPI does support weather station sensors. At first only the UPM WT440H (outdoor) sensor is supported and it works fine. Other sensors can be added to the LamPI-receiver/sniffer program later, but it is good to know that the LamPI-daemon offers support for receiving Json messages from weather sensors.</p>
<p>If you like to know more about te various sensors, check out their "hardware" pages. </p>
<ul>
<li><a href="../HardwareGuide/433-Sensors/wt440h/wt440h.html">WT-440H</a> for information about the WT-440H temperature and humidity sensor (433MHz unit)</li>
</ul>
<p>Of course temperature sensors can be meaningful in weather context, but also be used in energy applications. In the application I make that distinction (for the moment) as I expect most temperature, humidity and pressure sensors to be used most in context of weather. However, users are free to choose differently. As soon as I have my smart-meter up and running I will have a look at the energy sensors and their application as well.</p>
<p>Below you see a screenshot of the weather screen...</p>
<p><img src="screenshots/weather_screen_1.JPG" width="966" height="637" /></p>
<p> </p>
<h1>Weather Charts</h1>
<p>When clicking in the weather screen on one of the dials, a separate screen will open that shows historical data for the weather sensors. This function is described separately in the section for rrd graphs.</p>
<p><img src="screenshots/rrd_screen_01.JPG" width="963" height="636"></p>
<h1>Json message format for sensors</h1>
<p>The Json message that is sent to the LamPI-daemon is as follows:</p>
<p><code>message = {<br>
tcnt : integer,<br>
type : 'json',<br>
action : 'weather',<br>
brand: wt440h # or other supported brand<br>
address: integer, # (house code)<br>
channel: integer,<br>
temperature: integer.integer<br>
humidity: integer,<br>
windspeed: integer,<br>
winddirection: integer, # in degrees<br>
rainfall : char(8) # (mm per hour)</code></p>
<p><code>}; </code><br>
</p>
<h1>Adding a new wireless Weather sensor</h1>
<p>Weather sensors that are wireless 433MHz can be added to the LamPI-receiver by making a sensor function in C and including it in the receiver.c file and in the Makefile. The LamPI-receiver program in the ~/exe directory is the ONLY receiver for 433HMz messages and will handle all forwarding of successful receptions to the LamPI-daemon.</p>
<p>Next to the program itself, the sensor needs to be declared in the database.cfg file so that the LamPI-deamon knows that the incoming message for this address/channel is a source that we trust and allow access to our application.</p>
<p> </p>
<h1>Adding new wired sensors</h1>
<p>Adding wired sensors can be one of the following:</p>
<ol>
<li>A wired sensor without a bus</li>
<li>The 1-wire Dallas bus</li>
<li>A sensor with I2C support</li>
</ol>
<p>For more info on wired weather sensors, read the <a href="../HardwareGuide/Wired-Sensors/weather_sensors_msg_format.html">sensors.html</a> page </p>
<h1>Logging our Sensor data</h1>
<p>The LamPI-daemon will listen to all incoming json messages on its port 5000. Incoing messages from sensors will be matched against the configuration items in the database.cfg file for missing data such as names, location etc that are not sensor defined but defined by the user.</p>
<p>But in order to watch trends in data and analyze the collected data we need to add logging capabilities to the LamPI environment. There are several options:</p>
<ol>
<li>Make LamPI-daemon store all collected data in a logfile and use Excel to analyze the data</li>
<li>Make a logging process tat listens to port 5000 and be informed ot every json message that is processed by the daemon.</li>
<li>Use an external PAAS service provider, forward all messages received to the service provider and use its analyzing functions to make sense of your data.</li>
</ol>
<p>The third option is attractive, as it will use external storage, services etc. to look at our data and the trend graphs are accessible from anywhere on the internet. The PAAS provider carriots.com provides this service for free for small users with up to 10 data streams.</p>
<h3>re. Store in local logfile</h3>
<p>The easiest method for analysing sensor data is to store all data collected to a local logfile on the PI, and import this file into excel on regular intervals. This is simple solution, and this also how I started.</p>
<h3>re 2. Logging to rrdtool</h3>
<p>There is a tools based on a round robin database tool that can be used to store sensors data and display graphs. </p>
<h3>re 3. PAAS. Use a tool like Carriots</h3>
<p>The PAAS (Platform As A Service) provider carriots.com provides a free membership for data analysis of a limited set of sensors.</p>
<p> </p>
</body>
</html>
| Java |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'eo', {
toolbar: 'Nova Paĝo'
} );
| Java |
// $Id: ActionAddClientDependencyAction.java 41 2010-04-03 20:04:12Z marcusvnac $
// Copyright (c) 2007 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.foundation.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.argouml.i18n.Translator;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.uml.ui.AbstractActionAddModelElement2;
/**
* An Action to add client dependencies to some modelelement.
*
* @author Michiel
*/
public class ActionAddClientDependencyAction extends
AbstractActionAddModelElement2 {
/**
* The constructor.
*/
public ActionAddClientDependencyAction() {
super();
setMultiSelect(true);
}
/*
* Constraint: This code only deals with 1 supplier per dependency!
* TODO: How to support more?
*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#doIt(java.util.List)
*/
protected void doIt(Collection selected) {
Set oldSet = new HashSet(getSelected());
for (Object client : selected) {
if (oldSet.contains(client)) {
oldSet.remove(client); //to be able to remove dependencies later
} else {
Model.getCoreFactory().buildDependency(getTarget(), client);
}
}
Collection toBeDeleted = new ArrayList();
Collection dependencies = Model.getFacade().getClientDependencies(
getTarget());
for (Object dependency : dependencies) {
if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) {
toBeDeleted.add(dependency);
}
}
ProjectManager.getManager().getCurrentProject()
.moveToTrash(toBeDeleted);
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getChoices()
*/
protected List getChoices() {
List ret = new ArrayList();
Object model =
ProjectManager.getManager().getCurrentProject().getModel();
if (getTarget() != null) {
ret.addAll(Model.getModelManagementHelper()
.getAllModelElementsOfKind(model,
"org.omg.uml.foundation.core.ModelElement"));
ret.remove(getTarget());
}
return ret;
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getDialogTitle()
*/
protected String getDialogTitle() {
return Translator.localize("dialog.title.add-client-dependency");
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getSelected()
*/
protected List getSelected() {
List v = new ArrayList();
Collection c = Model.getFacade().getClientDependencies(getTarget());
for (Object cd : c) {
v.addAll(Model.getFacade().getSuppliers(cd));
}
return v;
}
}
| Java |
require 'spec_helper'
require 'rubybot/plugins/tweet'
require 'support/twitter_mock'
RSpec.describe Rubybot::Plugins::Tweet do
include Cinch::Test
describe '#commands' do
subject { described_class.new(make_bot).commands }
it('returns a single command') { is_expected.to have_exactly(1).items }
end
let(:bot) { make_bot described_class, get_plugin_configuration(described_class) }
it 'doesn\'t match an unrelated url' do
expect(get_replies make_message(bot, 'asdf')).to have_exactly(0).items
end
it 'gives tweet data for a twitter url' do
replies = get_replies make_message(bot,
'https://twitter.com/AUser/status/43212344123',
channel: 'a')
expect(replies).to have_exactly(1).items
expect(replies.first.event).to eq :message
expect(replies.first.text).to eq '@AUser: asdf'
end
end
| Java |
var searchData=
[
['transfer_20commands',['Transfer Commands',['../group___d_a_p__transfer__gr.html',1,'']]]
];
| Java |
Public Class RotationTile
Inherits Entity
Public Enum RotationTypes
StartSpin
StopSpin
End Enum
Dim RotationType As RotationTypes
Dim RotateTo As Integer = 0
Public Overrides Sub Initialize()
MyBase.Initialize()
Select Case Me.ActionValue
Case 0
Me.RotationType = RotationTypes.StartSpin
Case 1
Me.RotationType = RotationTypes.StopSpin
End Select
Me.RotateTo = CInt(Me.AdditionalValue)
Me.NeedsUpdate = True
End Sub
Public Overrides Sub Update()
If Me.RotationType = RotationTypes.StartSpin Then
If Core.CurrentScreen.Identification = Screen.Identifications.OverworldScreen Then
If CType(Core.CurrentScreen, OverworldScreen).ActionScript.IsReady = True Then
If Me.Position.X = Screen.Camera.Position.X And CInt(Me.Position.Y) = CInt(Screen.Camera.Position.Y) And Me.Position.Z = Screen.Camera.Position.Z Then
Dim steps As Integer = GetSteps()
Dim s As String = "version=2" & vbNewLine &
"@player.move(0)" & vbNewLine &
"@player.turnto(" & Me.RotateTo.ToString() & ")" & vbNewLine &
"@player.move(" & steps & ")" & vbNewLine &
":end"
CType(Core.CurrentScreen, OverworldScreen).ActionScript.StartScript(s, 2)
End If
End If
End If
End If
End Sub
Private Function GetSteps() As Integer
Dim steps As Integer = 0
Dim direction As Vector2 = New Vector2(0)
Select Case Me.RotateTo
Case 0
direction.Y = -1
Case 1
direction.X = -1
Case 2
direction.Y = 1
Case 3
direction.X = 1
End Select
Dim stepY As Integer = CInt(direction.Y)
If stepY = 0 Then
stepY = 1
End If
For x = 0 To direction.X * 100 Step direction.X
For y = 0 To direction.Y * 100 Step stepY
Dim p As Vector3 = New Vector3(x, 0, y) + Me.Position
For Each e As Entity In Screen.Level.Entities
If e.Equals(Me) = False Then
If e.EntityID.ToLower() = "rotationtile" Then
If CInt(e.Position.X) = CInt(p.X) And CInt(e.Position.Y) = CInt(p.Y) And CInt(e.Position.Z) = CInt(p.Z) Then
GoTo theend
End If
End If
End If
Next
steps += 1
Next
Next
theend:
Return steps
End Function
Public Overrides Sub Render()
Me.Draw(Me.Model, Textures, False)
End Sub
Public Overrides Function LetPlayerMove() As Boolean
Return Me.RotationType = RotationTypes.StopSpin
End Function
Public Overrides Function WalkIntoFunction() As Boolean
If Me.RotationType = RotationTypes.StartSpin Then
CType(Screen.Camera, OverworldCamera).YawLocked = True
End If
Return False
End Function
End Class | Java |
#!/bin/bash
# Butterfly root
BUTTERFLY_ROOT=$(cd "$(dirname $0)/.." && pwd)
sources="$BUTTERFLY_ROOT/api/client/client.cc \
$BUTTERFLY_ROOT/api/client/client.h \
$BUTTERFLY_ROOT/api/client/nic.cc \
$BUTTERFLY_ROOT/api/client/request.cc \
$BUTTERFLY_ROOT/api/client/sg.cc \
$BUTTERFLY_ROOT/api/client/shutdown.cc \
$BUTTERFLY_ROOT/api/client/status.cc \
$BUTTERFLY_ROOT/api/client/dump.cc \
$BUTTERFLY_ROOT/api/server/app.cc \
$BUTTERFLY_ROOT/api/server/app.h \
$BUTTERFLY_ROOT/api/server/server.cc \
$BUTTERFLY_ROOT/api/server/server.h \
$BUTTERFLY_ROOT/api/server/model.cc \
$BUTTERFLY_ROOT/api/server/model.h \
$BUTTERFLY_ROOT/api/server/api.cc \
$BUTTERFLY_ROOT/api/server/api.h \
$BUTTERFLY_ROOT/api/server/api_0.cc \
$BUTTERFLY_ROOT/api/server/graph.cc \
$BUTTERFLY_ROOT/api/server/graph.h \
$BUTTERFLY_ROOT/api/common/crypto.cc \
$BUTTERFLY_ROOT/api/common/crypto.h"
$BUTTERFLY_ROOT/scripts/cpplint.py --filter=-build/c++11 --root=$BUTTERFLY_ROOT $sources
if [ $? != 0 ]; then
echo "${RED}API style test failed${NORMAL}"
exit 1
fi
cppcheck &> /dev/null
if [ $? != 0 ]; then
echo "cppcheck is not installed, some tests will be skipped"
else
cppcheck --check-config --error-exitcode=1 --enable=all -I $BUTTERFLY_ROOT $sources &> /tmp/cppcheck.log
if [ $? != 0 ]; then
cat /tmp/cppcheck.log
echo "${RED}API style test failed${NORMAL}"
rm /tmp/cppcheck.log
exit 1
fi
fi
rm /tmp/cppcheck.log
rm /tmp/has_tabs &> /dev/null || true
for f in api benchmarks doc scripts tests; do
find $BUTTERFLY_ROOT/$f -name *.sh | while read a; do
if [ "-$(cat $a | grep -P '\t')" != "-" ]; then
echo found tab in $a
touch /tmp/has_tabs
fi
done
done
if test -f /tmp/has_tabs; then
rm /tmp/has_tabs &> /dev/null || true
echo "-- tabs found in scripts"
exit 1
else
echo "-- no tab found in scripts"
fi
exit 0
| Java |
"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
| Java |
/* armor.c - Armor filters
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2007, 2008, 2010
* Free Software Foundation, Inc.
*
* Author: Timo Schulz
*
* This file is part of OpenCDK.
*
* The OpenCDK library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* ChangeLog for basic BASE64 code (base64_encode, base64_decode):
* Original author: Eric S. Raymond (Fetchmail)
* Heavily modified by Brendan Cully <[email protected]> (Mutt)
* Modify the code for generic use by Timo Schulz <[email protected]>
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include "opencdk.h"
#include "main.h"
#include "filters.h"
#ifdef __MINGW32__
#define LF "\r\n"
#define ALTLF "\n"
#else
#define LF "\n"
#define ALTLF "\r\n"
#endif
#define CRCINIT 0xB704CE
#define BAD -1
#define b64val(c) index64[(unsigned int)(c)]
static u32 crc_table[] = {
0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC,
0x9F7F17,
0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5,
0x3EFE2E,
0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65,
0x5A319E,
0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C,
0xFBB0A7,
0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205,
0x93AEFE,
0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C,
0x322FC7,
0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C,
0x56E077,
0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5,
0xF7614E,
0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E,
0x86DCC5,
0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107,
0x275DFC,
0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7,
0x43924C,
0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E,
0xE21375,
0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7,
0x8A0D2C,
0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE,
0x2B8C15,
0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E,
0x4F43A5,
0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67,
0xEEC29C,
0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448,
0xAC38B3,
0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571,
0x0DB98A,
0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1,
0x69763A,
0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8,
0xC8F703,
0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1,
0xA0E95A,
0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498,
0x016863,
0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28,
0x65A7D3,
0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11,
0xC426EA,
0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A,
0xB59B61,
0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3,
0x141A58,
0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913,
0x70D5E8,
0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A,
0xD154D1,
0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673,
0xB94A88,
0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A,
0x18CBB1,
0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA,
0x7C0401,
0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3,
0xDD8538
};
static const char *armor_begin[] = {
"BEGIN PGP MESSAGE",
"BEGIN PGP PUBLIC KEY BLOCK",
"BEGIN PGP PRIVATE KEY BLOCK",
"BEGIN PGP SIGNATURE",
NULL
};
static const char *armor_end[] = {
"END PGP MESSAGE",
"END PGP PUBLIC KEY BLOCK",
"END PGP PRIVATE KEY BLOCK",
"END PGP SIGNATURE",
NULL
};
static const char *valid_headers[] = {
"Comment",
"Version",
"MessageID",
"Hash",
"Charset",
NULL
};
static char b64chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static int index64[128] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
};
/* encode a raw binary buffer to a null-terminated base64 strings */
static int
base64_encode (char *out, const byte * in, size_t len, size_t olen)
{
if (!out || !in)
{
gnutls_assert ();
return CDK_Inv_Value;
}
while (len >= 3 && olen > 10)
{
*out++ = b64chars[in[0] >> 2];
*out++ = b64chars[((in[0] << 4) & 0x30) | (in[1] >> 4)];
*out++ = b64chars[((in[1] << 2) & 0x3c) | (in[2] >> 6)];
*out++ = b64chars[in[2] & 0x3f];
olen -= 4;
len -= 3;
in += 3;
}
/* clean up remainder */
if (len > 0 && olen > 4)
{
byte fragment = 0;
*out++ = b64chars[in[0] >> 2];
fragment = (in[0] << 4) & 0x30;
if (len > 1)
fragment |= in[1] >> 4;
*out++ = b64chars[fragment];
*out++ = (len < 2) ? '=' : b64chars[(in[1] << 2) & 0x3c];
*out++ = '=';
}
*out = '\0';
return 0;
}
/* Convert '\0'-terminated base64 string to raw byte buffer.
Returns length of returned buffer, or -1 on error. */
static int
base64_decode (byte * out, const char *in)
{
size_t len;
byte digit1, digit2, digit3, digit4;
if (!out || !in)
{
gnutls_assert ();
return -1;
}
len = 0;
do
{
digit1 = in[0];
if (digit1 > 127 || b64val (digit1) == BAD)
{
gnutls_assert ();
return -1;
}
digit2 = in[1];
if (digit2 > 127 || b64val (digit2) == BAD)
{
gnutls_assert ();
return -1;
}
digit3 = in[2];
if (digit3 > 127 || ((digit3 != '=') && (b64val (digit3) == BAD)))
{
gnutls_assert ();
return -1;
}
digit4 = in[3];
if (digit4 > 127 || ((digit4 != '=') && (b64val (digit4) == BAD)))
{
gnutls_assert ();
return -1;
}
in += 4;
/* digits are already sanity-checked */
*out++ = (b64val (digit1) << 2) | (b64val (digit2) >> 4);
len++;
if (digit3 != '=')
{
*out++ = ((b64val (digit2) << 4) & 0xf0) | (b64val (digit3) >> 2);
len++;
if (digit4 != '=')
{
*out++ = ((b64val (digit3) << 6) & 0xc0) | b64val (digit4);
len++;
}
}
}
while (*in && digit4 != '=');
return len;
}
/* Return the compression algorithm in @r_zipalgo.
If the parameter is not set after execution,
the stream is not compressed. */
static int
compress_get_algo (cdk_stream_t inp, int *r_zipalgo)
{
byte plain[512];
char buf[128];
int nread, pkttype;
*r_zipalgo = 0;
cdk_stream_seek (inp, 0);
while (!cdk_stream_eof (inp))
{
nread = _cdk_stream_gets (inp, buf, DIM (buf) - 1);
if (!nread || nread == -1)
break;
if (nread == 1 && !cdk_stream_eof (inp)
&& (nread = _cdk_stream_gets (inp, buf, DIM (buf) - 1)) > 0)
{
base64_decode (plain, buf);
if (!(*plain & 0x80))
break;
pkttype = *plain & 0x40 ? (*plain & 0x3f) : ((*plain >> 2) & 0xf);
if (pkttype == CDK_PKT_COMPRESSED && r_zipalgo)
{
_gnutls_buffers_log ("armor compressed (algo=%d)\n",
*(plain + 1));
*r_zipalgo = *(plain + 1);
}
break;
}
}
return 0;
}
static int
check_armor (cdk_stream_t inp, int *r_zipalgo)
{
char buf[4096];
size_t nread;
int check;
check = 0;
nread = cdk_stream_read (inp, buf, DIM (buf) - 1);
if (nread > 0)
{
buf[nread] = '\0';
if (strstr (buf, "-----BEGIN PGP"))
{
compress_get_algo (inp, r_zipalgo);
check = 1;
}
cdk_stream_seek (inp, 0);
}
return check;
}
static int
is_armored (int ctb)
{
int pkttype = 0;
if (!(ctb & 0x80))
{
gnutls_assert ();
return 1; /* invalid packet: assume it is armored */
}
pkttype = ctb & 0x40 ? (ctb & 0x3f) : ((ctb >> 2) & 0xf);
switch (pkttype)
{
case CDK_PKT_MARKER:
case CDK_PKT_ONEPASS_SIG:
case CDK_PKT_PUBLIC_KEY:
case CDK_PKT_SECRET_KEY:
case CDK_PKT_PUBKEY_ENC:
case CDK_PKT_SIGNATURE:
case CDK_PKT_LITERAL:
case CDK_PKT_COMPRESSED:
return 0; /* seems to be a regular packet: not armored */
}
return 1;
}
static u32
update_crc (u32 crc, const byte * buf, size_t buflen)
{
unsigned int j;
if (!crc)
crc = CRCINIT;
for (j = 0; j < buflen; j++)
crc = (crc << 8) ^ crc_table[0xff & ((crc >> 16) ^ buf[j])];
crc &= 0xffffff;
return crc;
}
static cdk_error_t
armor_encode (void *data, FILE * in, FILE * out)
{
armor_filter_t *afx = data;
struct stat statbuf;
char crcbuf[5], buf[128], raw[49];
byte crcbuf2[3];
size_t nread = 0;
const char *lf;
if (!afx)
{
gnutls_assert ();
return CDK_Inv_Value;
}
if (afx->idx < 0 || afx->idx > (int) DIM (armor_begin) ||
afx->idx2 < 0 || afx->idx2 > (int) DIM (armor_end))
{
gnutls_assert ();
return CDK_Inv_Value;
}
_gnutls_buffers_log ("armor filter: encode\n");
memset (crcbuf, 0, sizeof (crcbuf));
lf = afx->le ? afx->le : LF;
fprintf (out, "-----%s-----%s", armor_begin[afx->idx], lf);
fprintf (out, "Version: OpenPrivacy " PACKAGE_VERSION "%s", lf);
if (afx->hdrlines)
fwrite (afx->hdrlines, 1, strlen (afx->hdrlines), out);
fprintf (out, "%s", lf);
if (fstat (fileno (in), &statbuf))
{
gnutls_assert ();
return CDK_General_Error;
}
while (!feof (in))
{
nread = fread (raw, 1, DIM (raw) - 1, in);
if (!nread)
break;
if (ferror (in))
{
gnutls_assert ();
return CDK_File_Error;
}
afx->crc = update_crc (afx->crc, (byte *) raw, nread);
base64_encode (buf, (byte *) raw, nread, DIM (buf) - 1);
fprintf (out, "%s%s", buf, lf);
}
crcbuf2[0] = afx->crc >> 16;
crcbuf2[1] = afx->crc >> 8;
crcbuf2[2] = afx->crc;
crcbuf[0] = b64chars[crcbuf2[0] >> 2];
crcbuf[1] = b64chars[((crcbuf2[0] << 4) & 0x30) | (crcbuf2[1] >> 4)];
crcbuf[2] = b64chars[((crcbuf2[1] << 2) & 0x3c) | (crcbuf2[2] >> 6)];
crcbuf[3] = b64chars[crcbuf2[2] & 0x3f];
fprintf (out, "=%s%s", crcbuf, lf);
fprintf (out, "-----%s-----%s", armor_end[afx->idx2], lf);
return 0;
}
/**
* cdk_armor_filter_use:
* @inp: the stream to check
*
* Check if the stream contains armored data.
**/
int
cdk_armor_filter_use (cdk_stream_t inp)
{
int c, check;
int zipalgo;
zipalgo = 0;
c = cdk_stream_getc (inp);
if (c == EOF)
return 0; /* EOF, doesn't matter whether armored or not */
cdk_stream_seek (inp, 0);
check = is_armored (c);
if (check)
{
check = check_armor (inp, &zipalgo);
if (zipalgo)
_cdk_stream_set_compress_algo (inp, zipalgo);
}
return check;
}
static int
search_header (const char *buf, const char **array)
{
const char *s;
int i;
if (strlen (buf) < 5 || strncmp (buf, "-----", 5))
{
gnutls_assert ();
return -1;
}
for (i = 0; (s = array[i]); i++)
{
if (!strncmp (s, buf + 5, strlen (s)))
return i;
}
return -1;
}
const char *
_cdk_armor_get_lineend (void)
{
return LF;
}
static cdk_error_t
armor_decode (void *data, FILE * in, FILE * out)
{
armor_filter_t *afx = data;
const char *s;
char buf[127];
byte raw[128], crcbuf[4];
u32 crc2 = 0;
ssize_t nread = 0;
int i, pgp_data = 0;
cdk_error_t rc = 0;
int len;
if (!afx)
{
gnutls_assert ();
return CDK_Inv_Value;
}
_gnutls_buffers_log ("armor filter: decode\n");
fseek (in, 0, SEEK_SET);
/* Search the begin of the message */
while (!feof (in) && !pgp_data)
{
s = fgets (buf, DIM (buf) - 1, in);
if (!s)
break;
afx->idx = search_header (buf, armor_begin);
if (afx->idx >= 0)
pgp_data = 1;
}
if (feof (in) || !pgp_data)
{
gnutls_assert ();
return CDK_Armor_Error; /* no data found */
}
/* Parse header until the empty line is reached */
while (!feof (in))
{
s = fgets (buf, DIM (buf) - 1, in);
if (!s)
return CDK_EOF;
if (strcmp (s, LF) == 0 || strcmp (s, ALTLF) == 0)
{
rc = 0;
break; /* empty line */
}
/* From RFC2440: OpenPGP should consider improperly formatted Armor
Headers to be corruption of the ASCII Armor. A colon and a single
space separate the key and value. */
if (!strstr (buf, ": "))
{
gnutls_assert ();
return CDK_Armor_Error;
}
rc = CDK_General_Error;
for (i = 0; (s = valid_headers[i]); i++)
{
if (!strncmp (s, buf, strlen (s)))
rc = 0;
}
if (rc)
{
/* From RFC2440: Unknown keys should be reported to the user,
but OpenPGP should continue to process the message. */
_cdk_log_info ("unknown header: `%s'\n", buf);
rc = 0;
}
}
/* Read the data body */
while (!feof (in))
{
s = fgets (buf, DIM (buf) - 1, in);
if (!s)
break;
len = strlen(buf);
if (buf[len - 1] == '\n')
buf[len - 1] = '\0';
if (buf[len - 1] == '\r')
buf[len - 1] = '\0';
if (buf[0] == '=' && strlen (s) == 5)
{ /* CRC */
memset (crcbuf, 0, sizeof (crcbuf));
base64_decode (crcbuf, buf + 1);
crc2 = (crcbuf[0] << 16) | (crcbuf[1] << 8) | crcbuf[2];
break; /* stop here */
}
else
{
nread = base64_decode (raw, buf);
if (nread == -1 || nread == 0)
break;
afx->crc = update_crc (afx->crc, raw, nread);
fwrite (raw, 1, nread, out);
}
}
/* Search the tail of the message */
s = fgets (buf, DIM (buf) - 1, in);
if (s)
{
int len = strlen(buf);
if (buf[len - 1] == '\n')
buf[len - 1] = '\0';
if (buf[len - 1] == '\r')
buf[len - 1] = '\0';
rc = CDK_General_Error;
afx->idx2 = search_header (buf, armor_end);
if (afx->idx2 >= 0)
rc = 0;
}
/* This catches error when no tail was found or the header is
different then the tail line. */
if (rc || afx->idx != afx->idx2)
rc = CDK_Armor_Error;
afx->crc_okay = (afx->crc == crc2) ? 1 : 0;
if (!afx->crc_okay && !rc)
{
_gnutls_buffers_log ("file crc=%08X afx_crc=%08X\n",
(unsigned int) crc2, (unsigned int) afx->crc);
rc = CDK_Armor_CRC_Error;
}
return rc;
}
/**
* cdk_file_armor:
* @hd: Handle
* @file: Name of the file to protect.
* @output: Output filename.
*
* Protect a file with ASCII armor.
**/
cdk_error_t
cdk_file_armor (cdk_ctx_t hd, const char *file, const char *output)
{
cdk_stream_t inp, out;
cdk_error_t rc;
rc = _cdk_check_args (hd->opt.overwrite, file, output);
if (rc)
return rc;
rc = cdk_stream_open (file, &inp);
if (rc)
{
gnutls_assert ();
return rc;
}
rc = cdk_stream_new (output, &out);
if (rc)
{
cdk_stream_close (inp);
gnutls_assert ();
return rc;
}
cdk_stream_set_armor_flag (out, CDK_ARMOR_MESSAGE);
if (hd->opt.compress)
rc = cdk_stream_set_compress_flag (out, hd->compress.algo,
hd->compress.level);
if (!rc)
rc = cdk_stream_set_literal_flag (out, 0, file);
if (!rc)
rc = cdk_stream_kick_off (inp, out);
if (!rc)
rc = _cdk_stream_get_errno (out);
cdk_stream_close (out);
cdk_stream_close (inp);
return rc;
}
/**
* cdk_file_dearmor:
* @file: Name of the file to unprotect.
* @output: Output filename.
*
* Remove ASCII armor from a file.
**/
cdk_error_t
cdk_file_dearmor (const char *file, const char *output)
{
cdk_stream_t inp, out;
cdk_error_t rc;
int zipalgo;
rc = _cdk_check_args (1, file, output);
if (rc)
{
gnutls_assert ();
return rc;
}
rc = cdk_stream_open (file, &inp);
if (rc)
{
gnutls_assert ();
return rc;
}
rc = cdk_stream_create (output, &out);
if (rc)
{
cdk_stream_close (inp);
gnutls_assert ();
return rc;
}
if (cdk_armor_filter_use (inp))
{
rc = cdk_stream_set_literal_flag (inp, 0, NULL);
zipalgo = cdk_stream_is_compressed (inp);
if (zipalgo)
rc = cdk_stream_set_compress_flag (inp, zipalgo, 0);
if (!rc)
rc = cdk_stream_set_armor_flag (inp, 0);
if (!rc)
rc = cdk_stream_kick_off (inp, out);
if (!rc)
rc = _cdk_stream_get_errno (inp);
}
cdk_stream_close (inp);
cdk_stream_close (out);
gnutls_assert ();
return rc;
}
int
_cdk_filter_armor (void *data, int ctl, FILE * in, FILE * out)
{
if (ctl == STREAMCTL_READ)
return armor_decode (data, in, out);
else if (ctl == STREAMCTL_WRITE)
return armor_encode (data, in, out);
else if (ctl == STREAMCTL_FREE)
{
armor_filter_t *afx = data;
if (afx)
{
_gnutls_buffers_log ("free armor filter\n");
afx->idx = afx->idx2 = 0;
afx->crc = afx->crc_okay = 0;
return 0;
}
}
gnutls_assert ();
return CDK_Inv_Mode;
}
/**
* cdk_armor_encode_buffer:
* @inbuf: the raw input buffer
* @inlen: raw buffer len
* @outbuf: the destination buffer for the base64 output
* @outlen: destination buffer len
* @nwritten: actual length of the base64 data
* @type: the base64 file type.
*
* Encode the given buffer into base64 format. The base64
* string will be null terminated but the null will
* not be contained in the size.
**/
cdk_error_t
cdk_armor_encode_buffer (const byte * inbuf, size_t inlen,
char *outbuf, size_t outlen,
size_t * nwritten, int type)
{
const char *head, *tail, *le;
byte tempbuf[48];
char tempout[128];
size_t pos, off, len, rest;
if (!inbuf || !nwritten)
{
gnutls_assert ();
return CDK_Inv_Value;
}
if (type > CDK_ARMOR_SIGNATURE)
{
gnutls_assert ();
return CDK_Inv_Mode;
}
head = armor_begin[type];
tail = armor_end[type];
le = _cdk_armor_get_lineend ();
pos = strlen (head) + 10 + 2 + 2 + strlen (tail) + 10 + 2 + 5 + 2 + 1;
/* The output data is 4/3 times larger, plus a line end for each line. */
pos += (4 * inlen / 3) + 2 * (4 * inlen / 3 / 64) + 1;
if (outbuf && outlen < pos)
{
gnutls_assert ();
*nwritten = pos;
return CDK_Too_Short;
}
/* Only return the size of the output. */
if (!outbuf)
{
*nwritten = pos;
return 0;
}
pos = 0;
memset (outbuf, 0, outlen);
memcpy (outbuf + pos, "-----", 5);
pos += 5;
memcpy (outbuf + pos, head, strlen (head));
pos += strlen (head);
memcpy (outbuf + pos, "-----", 5);
pos += 5;
memcpy (outbuf + pos, le, strlen (le));
pos += strlen (le);
memcpy (outbuf + pos, le, strlen (le));
pos += strlen (le);
rest = inlen;
for (off = 0; off < inlen;)
{
if (rest > 48)
{
memcpy (tempbuf, inbuf + off, 48);
off += 48;
len = 48;
}
else
{
memcpy (tempbuf, inbuf + off, rest);
off += rest;
len = rest;
}
rest -= len;
base64_encode (tempout, tempbuf, len, DIM (tempout) - 1);
memcpy (outbuf + pos, tempout, strlen (tempout));
pos += strlen (tempout);
memcpy (outbuf + pos, le, strlen (le));
pos += strlen (le);
}
memcpy (outbuf + pos, "-----", 5);
pos += 5;
memcpy (outbuf + pos, tail, strlen (tail));
pos += strlen (tail);
memcpy (outbuf + pos, "-----", 5);
pos += 5;
memcpy (outbuf + pos, le, strlen (le));
pos += strlen (le);
outbuf[pos] = 0;
*nwritten = pos - 1;
return 0;
}
| Java |
//# MatrixInverse.cc: The inverse of an expression returning a Jones matrix.
//#
//# Copyright (C) 2005
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite 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.
//#
//# The LOFAR software suite 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 the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id$
#include <lofar_config.h>
#include <BBSKernel/Expr/MatrixInverse.h>
// Inverse of a 2x2 matrix:
//
// (a b) ( d -b)
// If A = ( ) then inverse(A) = ( ) / (ad - bc)
// (c d) (-c a)
namespace LOFAR
{
namespace BBS
{
MatrixInverse::MatrixInverse(const Expr<JonesMatrix>::ConstPtr &expr)
: BasicUnaryExpr<JonesMatrix, JonesMatrix>(expr)
{
}
const JonesMatrix::View MatrixInverse::evaluateImpl(const Grid&,
const JonesMatrix::View &arg0) const
{
JonesMatrix::View result;
Matrix invDet(1.0 / (arg0(0, 0) * arg0(1, 1) - arg0(0, 1) * arg0(1, 0)));
result.assign(0, 0, arg0(1, 1) * invDet);
result.assign(0, 1, arg0(0, 1) * -invDet);
result.assign(1, 0, arg0(1, 0) * -invDet);
result.assign(1, 1, arg0(0, 0) * invDet);
return result;
}
} // namespace BBS
} // namespace LOFAR
| Java |
###########################################################################
#
# This file is partially auto-generated by the DateTime::Locale generator
# tools (v0.10). This code generator comes with the DateTime::Locale
# distribution in the tools/ directory, and is called generate-modules.
#
# This file was generated from the CLDR JSON locale data. See the LICENSE.cldr
# file included in this distribution for license details.
#
# Do not edit this file directly unless you are sure the part you are editing
# is not created by the generator.
#
###########################################################################
=pod
=encoding UTF-8
=head1 NAME
DateTime::Locale::rwk - Locale data examples for the Rwa (rwk) locale
=head1 DESCRIPTION
This pod file contains examples of the locale data available for the
Rwa locale.
=head2 Days
=head3 Wide (format)
Jumatatuu
Jumanne
Jumatanu
Alhamisi
Ijumaa
Jumamosi
Jumapilyi
=head3 Abbreviated (format)
Jtt
Jnn
Jtn
Alh
Iju
Jmo
Jpi
=head3 Narrow (format)
J
J
J
A
I
J
J
=head3 Wide (stand-alone)
Jumatatuu
Jumanne
Jumatanu
Alhamisi
Ijumaa
Jumamosi
Jumapilyi
=head3 Abbreviated (stand-alone)
Jtt
Jnn
Jtn
Alh
Iju
Jmo
Jpi
=head3 Narrow (stand-alone)
J
J
J
A
I
J
J
=head2 Months
=head3 Wide (format)
Januari
Februari
Machi
Aprilyi
Mei
Junyi
Julyai
Agusti
Septemba
Oktoba
Novemba
Desemba
=head3 Abbreviated (format)
Jan
Feb
Mac
Apr
Mei
Jun
Jul
Ago
Sep
Okt
Nov
Des
=head3 Narrow (format)
J
F
M
A
M
J
J
A
S
O
N
D
=head3 Wide (stand-alone)
Januari
Februari
Machi
Aprilyi
Mei
Junyi
Julyai
Agusti
Septemba
Oktoba
Novemba
Desemba
=head3 Abbreviated (stand-alone)
Jan
Feb
Mac
Apr
Mei
Jun
Jul
Ago
Sep
Okt
Nov
Des
=head3 Narrow (stand-alone)
J
F
M
A
M
J
J
A
S
O
N
D
=head2 Quarters
=head3 Wide (format)
Robo 1
Robo 2
Robo 3
Robo 4
=head3 Abbreviated (format)
R1
R2
R3
R4
=head3 Narrow (format)
1
2
3
4
=head3 Wide (stand-alone)
Robo 1
Robo 2
Robo 3
Robo 4
=head3 Abbreviated (stand-alone)
R1
R2
R3
R4
=head3 Narrow (stand-alone)
1
2
3
4
=head2 Eras
=head3 Wide (format)
Kabla ya Kristu
Baada ya Kristu
=head3 Abbreviated (format)
KK
BK
=head3 Narrow (format)
KK
BK
=head2 Date Formats
=head3 Full
2008-02-05T18:30:30 = Jumanne, 5 Februari 2008
1995-12-22T09:05:02 = Ijumaa, 22 Desemba 1995
-0010-09-15T04:44:23 = Jumamosi, 15 Septemba -10
=head3 Long
2008-02-05T18:30:30 = 5 Februari 2008
1995-12-22T09:05:02 = 22 Desemba 1995
-0010-09-15T04:44:23 = 15 Septemba -10
=head3 Medium
2008-02-05T18:30:30 = 5 Feb 2008
1995-12-22T09:05:02 = 22 Des 1995
-0010-09-15T04:44:23 = 15 Sep -10
=head3 Short
2008-02-05T18:30:30 = 05/02/2008
1995-12-22T09:05:02 = 22/12/1995
-0010-09-15T04:44:23 = 15/09/-10
=head2 Time Formats
=head3 Full
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Long
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Medium
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 Short
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head2 Datetime Formats
=head3 Full
2008-02-05T18:30:30 = Jumanne, 5 Februari 2008 18:30:30 UTC
1995-12-22T09:05:02 = Ijumaa, 22 Desemba 1995 09:05:02 UTC
-0010-09-15T04:44:23 = Jumamosi, 15 Septemba -10 04:44:23 UTC
=head3 Long
2008-02-05T18:30:30 = 5 Februari 2008 18:30:30 UTC
1995-12-22T09:05:02 = 22 Desemba 1995 09:05:02 UTC
-0010-09-15T04:44:23 = 15 Septemba -10 04:44:23 UTC
=head3 Medium
2008-02-05T18:30:30 = 5 Feb 2008 18:30:30
1995-12-22T09:05:02 = 22 Des 1995 09:05:02
-0010-09-15T04:44:23 = 15 Sep -10 04:44:23
=head3 Short
2008-02-05T18:30:30 = 05/02/2008 18:30
1995-12-22T09:05:02 = 22/12/1995 09:05
-0010-09-15T04:44:23 = 15/09/-10 04:44
=head2 Available Formats
=head3 Bh (h B)
2008-02-05T18:30:30 = 6 B
1995-12-22T09:05:02 = 9 B
-0010-09-15T04:44:23 = 4 B
=head3 Bhm (h:mm B)
2008-02-05T18:30:30 = 6:30 B
1995-12-22T09:05:02 = 9:05 B
-0010-09-15T04:44:23 = 4:44 B
=head3 Bhms (h:mm:ss B)
2008-02-05T18:30:30 = 6:30:30 B
1995-12-22T09:05:02 = 9:05:02 B
-0010-09-15T04:44:23 = 4:44:23 B
=head3 E (ccc)
2008-02-05T18:30:30 = Jnn
1995-12-22T09:05:02 = Iju
-0010-09-15T04:44:23 = Jmo
=head3 EBhm (E h:mm B)
2008-02-05T18:30:30 = Jnn 6:30 B
1995-12-22T09:05:02 = Iju 9:05 B
-0010-09-15T04:44:23 = Jmo 4:44 B
=head3 EBhms (E h:mm:ss B)
2008-02-05T18:30:30 = Jnn 6:30:30 B
1995-12-22T09:05:02 = Iju 9:05:02 B
-0010-09-15T04:44:23 = Jmo 4:44:23 B
=head3 EHm (E HH:mm)
2008-02-05T18:30:30 = Jnn 18:30
1995-12-22T09:05:02 = Iju 09:05
-0010-09-15T04:44:23 = Jmo 04:44
=head3 EHms (E HH:mm:ss)
2008-02-05T18:30:30 = Jnn 18:30:30
1995-12-22T09:05:02 = Iju 09:05:02
-0010-09-15T04:44:23 = Jmo 04:44:23
=head3 Ed (d, E)
2008-02-05T18:30:30 = 5, Jnn
1995-12-22T09:05:02 = 22, Iju
-0010-09-15T04:44:23 = 15, Jmo
=head3 Ehm (E h:mm a)
2008-02-05T18:30:30 = Jnn 6:30 kyiukonyi
1995-12-22T09:05:02 = Iju 9:05 utuko
-0010-09-15T04:44:23 = Jmo 4:44 utuko
=head3 Ehms (E h:mm:ss a)
2008-02-05T18:30:30 = Jnn 6:30:30 kyiukonyi
1995-12-22T09:05:02 = Iju 9:05:02 utuko
-0010-09-15T04:44:23 = Jmo 4:44:23 utuko
=head3 Gy (G y)
2008-02-05T18:30:30 = BK 2008
1995-12-22T09:05:02 = BK 1995
-0010-09-15T04:44:23 = KK -10
=head3 GyMMM (G y MMM)
2008-02-05T18:30:30 = BK 2008 Feb
1995-12-22T09:05:02 = BK 1995 Des
-0010-09-15T04:44:23 = KK -10 Sep
=head3 GyMMMEd (G y MMM d, E)
2008-02-05T18:30:30 = BK 2008 Feb 5, Jnn
1995-12-22T09:05:02 = BK 1995 Des 22, Iju
-0010-09-15T04:44:23 = KK -10 Sep 15, Jmo
=head3 GyMMMd (G y MMM d)
2008-02-05T18:30:30 = BK 2008 Feb 5
1995-12-22T09:05:02 = BK 1995 Des 22
-0010-09-15T04:44:23 = KK -10 Sep 15
=head3 H (HH)
2008-02-05T18:30:30 = 18
1995-12-22T09:05:02 = 09
-0010-09-15T04:44:23 = 04
=head3 Hm (HH:mm)
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head3 Hms (HH:mm:ss)
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 Hmsv (HH:mm:ss v)
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Hmv (HH:mm v)
2008-02-05T18:30:30 = 18:30 UTC
1995-12-22T09:05:02 = 09:05 UTC
-0010-09-15T04:44:23 = 04:44 UTC
=head3 M (L)
2008-02-05T18:30:30 = 2
1995-12-22T09:05:02 = 12
-0010-09-15T04:44:23 = 9
=head3 MEd (E, M/d)
2008-02-05T18:30:30 = Jnn, 2/5
1995-12-22T09:05:02 = Iju, 12/22
-0010-09-15T04:44:23 = Jmo, 9/15
=head3 MMM (LLL)
2008-02-05T18:30:30 = Feb
1995-12-22T09:05:02 = Des
-0010-09-15T04:44:23 = Sep
=head3 MMMEd (E, MMM d)
2008-02-05T18:30:30 = Jnn, Feb 5
1995-12-22T09:05:02 = Iju, Des 22
-0010-09-15T04:44:23 = Jmo, Sep 15
=head3 MMMMEd (E, MMMM d)
2008-02-05T18:30:30 = Jnn, Februari 5
1995-12-22T09:05:02 = Iju, Desemba 22
-0010-09-15T04:44:23 = Jmo, Septemba 15
=head3 MMMMW-count-other ('week' W 'of' MMMM)
2008-02-05T18:30:30 = week 1 of Februari
1995-12-22T09:05:02 = week 3 of Desemba
-0010-09-15T04:44:23 = week 2 of Septemba
=head3 MMMMd (MMMM d)
2008-02-05T18:30:30 = Februari 5
1995-12-22T09:05:02 = Desemba 22
-0010-09-15T04:44:23 = Septemba 15
=head3 MMMd (MMM d)
2008-02-05T18:30:30 = Feb 5
1995-12-22T09:05:02 = Des 22
-0010-09-15T04:44:23 = Sep 15
=head3 Md (M/d)
2008-02-05T18:30:30 = 2/5
1995-12-22T09:05:02 = 12/22
-0010-09-15T04:44:23 = 9/15
=head3 d (d)
2008-02-05T18:30:30 = 5
1995-12-22T09:05:02 = 22
-0010-09-15T04:44:23 = 15
=head3 h (h a)
2008-02-05T18:30:30 = 6 kyiukonyi
1995-12-22T09:05:02 = 9 utuko
-0010-09-15T04:44:23 = 4 utuko
=head3 hm (h:mm a)
2008-02-05T18:30:30 = 6:30 kyiukonyi
1995-12-22T09:05:02 = 9:05 utuko
-0010-09-15T04:44:23 = 4:44 utuko
=head3 hms (h:mm:ss a)
2008-02-05T18:30:30 = 6:30:30 kyiukonyi
1995-12-22T09:05:02 = 9:05:02 utuko
-0010-09-15T04:44:23 = 4:44:23 utuko
=head3 hmsv (h:mm:ss a v)
2008-02-05T18:30:30 = 6:30:30 kyiukonyi UTC
1995-12-22T09:05:02 = 9:05:02 utuko UTC
-0010-09-15T04:44:23 = 4:44:23 utuko UTC
=head3 hmv (h:mm a v)
2008-02-05T18:30:30 = 6:30 kyiukonyi UTC
1995-12-22T09:05:02 = 9:05 utuko UTC
-0010-09-15T04:44:23 = 4:44 utuko UTC
=head3 ms (mm:ss)
2008-02-05T18:30:30 = 30:30
1995-12-22T09:05:02 = 05:02
-0010-09-15T04:44:23 = 44:23
=head3 y (y)
2008-02-05T18:30:30 = 2008
1995-12-22T09:05:02 = 1995
-0010-09-15T04:44:23 = -10
=head3 yM (M/y)
2008-02-05T18:30:30 = 2/2008
1995-12-22T09:05:02 = 12/1995
-0010-09-15T04:44:23 = 9/-10
=head3 yMEd (E, M/d/y)
2008-02-05T18:30:30 = Jnn, 2/5/2008
1995-12-22T09:05:02 = Iju, 12/22/1995
-0010-09-15T04:44:23 = Jmo, 9/15/-10
=head3 yMMM (MMM y)
2008-02-05T18:30:30 = Feb 2008
1995-12-22T09:05:02 = Des 1995
-0010-09-15T04:44:23 = Sep -10
=head3 yMMMEd (E, MMM d, y)
2008-02-05T18:30:30 = Jnn, Feb 5, 2008
1995-12-22T09:05:02 = Iju, Des 22, 1995
-0010-09-15T04:44:23 = Jmo, Sep 15, -10
=head3 yMMMM (MMMM y)
2008-02-05T18:30:30 = Februari 2008
1995-12-22T09:05:02 = Desemba 1995
-0010-09-15T04:44:23 = Septemba -10
=head3 yMMMd (y MMM d)
2008-02-05T18:30:30 = 2008 Feb 5
1995-12-22T09:05:02 = 1995 Des 22
-0010-09-15T04:44:23 = -10 Sep 15
=head3 yMd (y-MM-dd)
2008-02-05T18:30:30 = 2008-02-05
1995-12-22T09:05:02 = 1995-12-22
-0010-09-15T04:44:23 = -10-09-15
=head3 yQQQ (QQQ y)
2008-02-05T18:30:30 = R1 2008
1995-12-22T09:05:02 = R4 1995
-0010-09-15T04:44:23 = R3 -10
=head3 yQQQQ (QQQQ y)
2008-02-05T18:30:30 = Robo 1 2008
1995-12-22T09:05:02 = Robo 4 1995
-0010-09-15T04:44:23 = Robo 3 -10
=head3 yw-count-other ('week' w 'of' Y)
2008-02-05T18:30:30 = week 6 of 2008
1995-12-22T09:05:02 = week 51 of 1995
-0010-09-15T04:44:23 = week 37 of -10
=head2 Miscellaneous
=head3 Prefers 24 hour time?
Yes
=head3 Local first day of the week
1 (Jumatatuu)
=head1 SUPPORT
See L<DateTime::Locale>.
=cut
| Java |
// @flow
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import Profile from 'models/Profile'
import IconButton from 'material-ui/IconButton'
import Typography from 'material-ui/Typography'
import FontAwesome from 'react-fontawesome'
import Avatar from 'components/common/Avatar'
import Pubkey from 'components/common/Pubkey'
import InsetText from 'components/common/InsetText'
class ShowProfile extends Component {
props: {
profile: Profile,
onEditClick: () => any
}
render() {
const { classes, profile } = this.props
return (
<div>
<div className={classes.header}>
<div className={classes.lateral} />
<Typography className={classes.identity}>{profile.identity}</Typography>
<IconButton className={classes.lateral} onClick={this.props.onEditClick}><FontAwesome name="pencil" /></IconButton>
</div>
{ profile.avatarUrl
? <Avatar person={profile} className={classes.avatar} />
: <div className={classes.noAvatar}><Typography>No avatar</Typography></div>
}
<InsetText text={profile.bio} placeholder='No biography' />
<Typography align="center" variant="body2">
Share your Arbore ID
</Typography>
<Pubkey pubkey={profile.pubkey} />
</div>
)
}
}
const style = theme => ({
header: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
margin: '10px 0 20px',
},
avatar: {
width: '200px !important',
height: '200px !important',
margin: 'auto',
userSelect: 'none',
pointerEvents: 'none',
},
noAvatar: {
width: 200,
height: 200,
borderRadius: '50%',
backgroundColor: theme.palette.background.dark,
margin: 'auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
identity: {
margin: '0 10px 0 !important',
fontSize: '2em !important',
textAlign: 'center',
flexGrow: 1,
},
lateral: {
width: '20px !important',
},
})
export default withStyles(style)(ShowProfile)
| Java |
-----------------------------------
-- Area: North Gustaberg (S) (88)
-- Mob: Five_Moons
-----------------------------------
-- require("scripts/zones/North_Gustaberg_[S]/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
| Java |
package fr.ybo.transportscommun.activity.commun;
import android.widget.ImageButton;
public interface ChangeIconActionBar {
public void changeIconActionBar(ImageButton imageButton);
}
| Java |
/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "prefix.h"
#include "globdefs.h"
#include "png.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
#include "uidc.h"
#include "util.h"
#include "image.h"
#include "globals.h"
#include "imageloader.h"
#define NATIVE_ALPHA_BEFORE ((kMCGPixelFormatNative & kMCGPixelAlphaPositionFirst) == kMCGPixelAlphaPositionFirst)
#define NATIVE_ORDER_BGR ((kMCGPixelFormatNative & kMCGPixelOrderRGB) == 0)
#if NATIVE_ALPHA_BEFORE
#define MCPNG_FILLER_POSITION PNG_FILLER_BEFORE
#else
#define MCPNG_FILLER_POSITION PNG_FILLER_AFTER
#endif
extern "C" void fakeread(png_structp png_ptr, png_bytep data, png_size_t length)
{
uint8_t **t_data_ptr = (uint8_t**)png_get_io_ptr(png_ptr);
memcpy(data, *t_data_ptr, length);
*t_data_ptr += length;
}
extern "C" void fakeflush(png_structp png_ptr)
{}
bool MCImageValidatePng(const void *p_data, uint32_t p_length, uint16_t& r_width, uint16_t& r_height)
{
png_structp png_ptr;
png_ptr = png_create_read_struct((char *)PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info_ptr;
info_ptr = png_create_info_struct(png_ptr);
png_infop end_info_ptr;
end_info_ptr = png_create_info_struct(png_ptr);
// If we return to this point, its an error.
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr);
return false;
}
png_set_read_fn(png_ptr, &p_data, fakeread);
png_read_info(png_ptr, info_ptr);
png_uint_32 width, height;
int interlace_type, compression_type, filter_type, bit_depth, color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr);
r_width = (uint16_t)width;
r_height = (uint16_t)height;
return true;
}
////////////////////////////////////////////////////////////////////////////////
extern "C" void stream_read(png_structp png_ptr, png_bytep data, png_size_t length)
{
IO_handle t_stream = (IO_handle)png_get_io_ptr(png_ptr);
uint4 t_length;
t_length = length;
if (IO_read(data, length, t_stream) != IO_NORMAL)
png_error(png_ptr, (char *)"pnglib read error");
}
static void MCPNGSetNativePixelFormat(png_structp p_png)
{
#if NATIVE_ORDER_BGR
png_set_bgr(p_png);
#endif
#if NATIVE_ALPHA_BEFORE
png_set_swap_alpha(p_png);
#endif
}
class MCPNGImageLoader : public MCImageLoader
{
public:
MCPNGImageLoader(IO_handle p_stream);
virtual ~MCPNGImageLoader();
virtual MCImageLoaderFormat GetFormat() { return kMCImageFormatPNG; }
protected:
virtual bool LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata);
virtual bool LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count);
private:
png_structp m_png;
png_infop m_info;
png_infop m_end_info;
int m_bit_depth;
int m_color_type;
};
MCPNGImageLoader::MCPNGImageLoader(IO_handle p_stream) : MCImageLoader(p_stream)
{
m_png = nil;
m_info = nil;
m_end_info = nil;
}
MCPNGImageLoader::~MCPNGImageLoader()
{
if (m_png != nil)
png_destroy_read_struct(&m_png, &m_info, &m_end_info);
}
bool MCPNGImageLoader::LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata)
{
bool t_success = true;
t_success = nil != (m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL));
if (t_success)
t_success = nil != (m_info = png_create_info_struct(m_png));
if (t_success)
t_success = nil != (m_end_info = png_create_info_struct(m_png));
if (t_success)
{
if (setjmp(png_jmpbuf(m_png)))
{
t_success = false;
}
}
if (t_success)
{
png_set_read_fn(m_png, GetStream(), stream_read);
png_read_info(m_png, m_info);
}
png_uint_32 t_width, t_height;
int t_interlace_method, t_compression_method, t_filter_method;
if (t_success)
{
png_get_IHDR(m_png, m_info, &t_width, &t_height,
&m_bit_depth, &m_color_type,
&t_interlace_method, &t_compression_method, &t_filter_method);
}
// MERG-2014-09-12: [[ ImageMetadata ]] load image metatadata
if (t_success)
{
uint32_t t_X;
uint32_t t_Y;
int t_units;
if (png_get_pHYs(m_png, m_info, &t_X, &t_Y, &t_units) && t_units != PNG_RESOLUTION_UNKNOWN)
{
MCImageMetadata t_metadata;
MCMemoryClear(&t_metadata, sizeof(t_metadata));
t_metadata.has_density = true;
t_metadata.density = floor(t_X * 0.0254 + 0.5);
r_metadata = t_metadata;
}
}
if (t_success)
{
r_width = t_width;
r_height = t_height;
r_xhot = r_yhot = 0;
r_name = MCValueRetain(kMCEmptyString);
r_frame_count = 1;
}
return t_success;
}
bool MCPNGImageLoader::LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count)
{
bool t_success = true;
MCBitmapFrame *t_frame;
t_frame = nil;
MCColorTransformRef t_color_xform;
t_color_xform = nil;
if (setjmp(png_jmpbuf(m_png)))
{
t_success = false;
}
int t_interlace_passes;
uint32_t t_width, t_height;
if (t_success)
t_success = GetGeometry(t_width, t_height);
if (t_success)
t_success = MCMemoryNew(t_frame);
if (t_success)
t_success = MCImageBitmapCreate(t_width, t_height, t_frame->image);
if (t_success)
{
bool t_need_alpha = false;
t_interlace_passes = png_set_interlace_handling(m_png);
if (m_color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(m_png);
if (m_color_type == PNG_COLOR_TYPE_GRAY || m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(m_png);
if (png_get_valid(m_png, m_info, PNG_INFO_tRNS))
{
png_set_tRNS_to_alpha(m_png);
t_need_alpha = true;
/* OVERHAUL - REVISIT - assume image has transparent pixels if tRNS is present */
t_frame->image->has_transparency = true;
}
if (m_color_type & PNG_COLOR_MASK_ALPHA)
{
t_need_alpha = true;
/* OVERHAUL - REVISIT - assume image has alpha if color type allows it */
t_frame->image->has_alpha = t_frame->image->has_transparency = true;
}
else if (!t_need_alpha)
png_set_add_alpha(m_png, 0xFF, MCPNG_FILLER_POSITION);
if (m_bit_depth == 16)
png_set_strip_16(m_png);
MCPNGSetNativePixelFormat(m_png);
}
// MW-2009-12-10: Support for color profiles
// Try to get an embedded ICC profile...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_iCCP))
{
png_charp t_ccp_name;
png_bytep t_ccp_profile;
int t_ccp_compression_type;
png_uint_32 t_ccp_profile_length;
png_get_iCCP(m_png, m_info, &t_ccp_name, &t_ccp_compression_type, &t_ccp_profile, &t_ccp_profile_length);
MCColorSpaceInfo t_csinfo;
t_csinfo . type = kMCColorSpaceEmbedded;
t_csinfo . embedded . data = t_ccp_profile;
t_csinfo . embedded . data_size = t_ccp_profile_length;
t_color_xform = MCscreen -> createcolortransform(t_csinfo);
}
// Next try an sRGB style profile...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_sRGB))
{
int t_intent;
png_get_sRGB(m_png, m_info, &t_intent);
MCColorSpaceInfo t_csinfo;
t_csinfo . type = kMCColorSpaceStandardRGB;
t_csinfo . standard . intent = (MCColorSpaceIntent)t_intent;
t_color_xform = MCscreen -> createcolortransform(t_csinfo);
}
// Finally try for cHRM + gAMA...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_cHRM) &&
png_get_valid(m_png, m_info, PNG_INFO_gAMA))
{
MCColorSpaceInfo t_csinfo;
t_csinfo . type = kMCColorSpaceCalibratedRGB;
png_get_cHRM(m_png, m_info,
&t_csinfo . calibrated . white_x, &t_csinfo . calibrated . white_y,
&t_csinfo . calibrated . red_x, &t_csinfo . calibrated . red_y,
&t_csinfo . calibrated . green_x, &t_csinfo . calibrated . green_y,
&t_csinfo . calibrated . blue_x, &t_csinfo . calibrated . blue_y);
png_get_gAMA(m_png, m_info, &t_csinfo . calibrated . gamma);
t_color_xform = MCscreen -> createcolortransform(t_csinfo);
}
// Could not create any kind, so fallback to gamma transform.
if (t_success && t_color_xform == nil)
{
double image_gamma;
if (png_get_gAMA(m_png, m_info, &image_gamma))
png_set_gamma(m_png, MCgamma, image_gamma);
else
png_set_gamma(m_png, MCgamma, 0.45);
}
if (t_success)
{
for (uindex_t t_pass = 0; t_pass < t_interlace_passes; t_pass++)
{
png_bytep t_data_ptr = (png_bytep)t_frame->image->data;
for (uindex_t i = 0; i < t_height; i++)
{
png_read_row(m_png, t_data_ptr, nil);
t_data_ptr += t_frame->image->stride;
}
}
}
if (t_success)
png_read_end(m_png, m_end_info);
// transform colours using extracted colour profile
if (t_success && t_color_xform != nil)
MCImageBitmapApplyColorTransform(t_frame->image, t_color_xform);
if (t_color_xform != nil)
MCscreen -> destroycolortransform(t_color_xform);
if (t_success)
{
r_frames = t_frame;
r_count = 1;
}
else
MCImageFreeFrames(t_frame, 1);
return t_success;
}
bool MCImageLoaderCreateForPNGStream(IO_handle p_stream, MCImageLoader *&r_loader)
{
MCPNGImageLoader *t_loader;
t_loader = new MCPNGImageLoader(p_stream);
if (t_loader == nil)
return false;
r_loader = t_loader;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// embed stream within wrapper struct containing byte count
// so we can update byte_count as we go
struct MCPNGWriteContext
{
IO_handle stream;
uindex_t byte_count;
};
extern "C" void fakewrite(png_structp png_ptr, png_bytep data, png_size_t length)
{
MCPNGWriteContext *t_context = (MCPNGWriteContext*)png_get_io_ptr(png_ptr);
if (IO_write(data, sizeof(uint1), length, t_context->stream) != IO_NORMAL)
png_error(png_ptr, (char *)"pnglib write error");
t_context->byte_count += length;
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
static void parsemetadata(png_structp png_ptr, png_infop info_ptr, MCImageMetadata *p_metadata)
{
if (p_metadata == nil)
return;
if (p_metadata -> has_density)
{
real64_t t_ppi = p_metadata -> density;
if (t_ppi > 0)
{
// Convert to pixels per metre from pixels per inch
png_set_pHYs(png_ptr, info_ptr, t_ppi / 0.0254, t_ppi / 0.0254, PNG_RESOLUTION_METER);
}
}
}
bool MCImageEncodePNG(MCImageIndexedBitmap *p_indexed, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written)
{
bool t_success = true;
MCPNGWriteContext t_context;
t_context.stream = p_stream;
t_context.byte_count = 0;
png_structp t_png_ptr = nil;
png_infop t_info_ptr = nil;
png_color *t_png_palette = nil;
png_byte *t_png_transparency = nil;
png_bytep t_data_ptr = nil;
uindex_t t_stride = 0;
/*init png stuff*/
if (t_success)
{
t_success = nil != (t_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp)NULL, (png_error_ptr)NULL,
(png_error_ptr)NULL));
}
if (t_success)
t_success = nil != (t_info_ptr = png_create_info_struct(t_png_ptr));
/*in case of png error*/
if (setjmp(png_jmpbuf(t_png_ptr)))
t_success = false;
if (t_success)
png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush);
if (t_success)
{
png_set_IHDR(t_png_ptr, t_info_ptr, p_indexed->width, p_indexed->height, 8,
PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma);
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
if (t_success)
parsemetadata(t_png_ptr, t_info_ptr, p_metadata);
if (t_success)
t_success = MCMemoryNewArray(p_indexed->palette_size, t_png_palette);
/*create palette for 8 bit*/
if (t_success)
{
for (uindex_t i = 0; i < p_indexed->palette_size ; i++)
{
t_png_palette[i].red = p_indexed->palette[i].red >> 8;
t_png_palette[i].green = p_indexed->palette[i].green >> 8;
t_png_palette[i].blue = p_indexed->palette[i].blue >> 8;
}
png_set_PLTE(t_png_ptr, t_info_ptr, t_png_palette, p_indexed->palette_size);
}
if (MCImageIndexedBitmapHasTransparency(p_indexed))
{
if (t_success)
t_success = MCMemoryAllocate(p_indexed->palette_size, t_png_transparency);
if (t_success)
{
memset(t_png_transparency, 0xFF, p_indexed->palette_size);
t_png_transparency[p_indexed->transparent_index] = 0x00;
png_set_tRNS(t_png_ptr, t_info_ptr, t_png_transparency, p_indexed->palette_size, NULL);
}
}
if (t_success)
png_write_info(t_png_ptr, t_info_ptr);
if (t_success)
{
t_data_ptr = (png_bytep)p_indexed->data;
t_stride = p_indexed->stride;
}
if (t_success)
{
for (uindex_t i = 0; i < p_indexed->height; i++)
{
png_write_row(t_png_ptr, t_data_ptr);
t_data_ptr += t_stride;
}
}
if (t_success)
png_write_end(t_png_ptr, t_info_ptr);
if (t_png_ptr != nil)
png_destroy_write_struct(&t_png_ptr, &t_info_ptr);
if (t_png_palette != nil)
MCMemoryDeleteArray(t_png_palette);
if (t_png_transparency != nil)
MCMemoryDeallocate(t_png_transparency);
if (t_success)
r_bytes_written = t_context.byte_count;
return t_success;
}
bool MCImageEncodePNG(MCImageBitmap *p_bitmap, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written)
{
bool t_success = true;
MCPNGWriteContext t_context;
t_context.stream = p_stream;
t_context.byte_count = 0;
png_structp t_png_ptr = nil;
png_infop t_info_ptr = nil;
png_color *t_png_palette = nil;
png_byte *t_png_transparency = nil;
png_bytep t_data_ptr = nil;
uindex_t t_stride = 0;
MCImageIndexedBitmap *t_indexed = nil;
if (MCImageConvertBitmapToIndexed(p_bitmap, false, t_indexed))
{
t_success = MCImageEncodePNG(t_indexed, p_metadata, p_stream, r_bytes_written);
MCImageFreeIndexedBitmap(t_indexed);
return t_success;
}
/*init png stuff*/
if (t_success)
{
t_success = nil != (t_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp)NULL, (png_error_ptr)NULL,
(png_error_ptr)NULL));
}
if (t_success)
t_success = nil != (t_info_ptr = png_create_info_struct(t_png_ptr));
/*in case of png error*/
if (setjmp(png_jmpbuf(t_png_ptr)))
t_success = false;
if (t_success)
png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush);
bool t_fully_opaque = true;
if (t_success)
{
t_fully_opaque = !MCImageBitmapHasTransparency(p_bitmap);
png_set_IHDR(t_png_ptr, t_info_ptr, p_bitmap->width, p_bitmap->height, 8,
t_fully_opaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma);
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
if (t_success)
parsemetadata(t_png_ptr, t_info_ptr, p_metadata);
if (t_success)
{
png_write_info(t_png_ptr, t_info_ptr);
if (t_fully_opaque)
png_set_filler(t_png_ptr, 0, MCPNG_FILLER_POSITION);
MCPNGSetNativePixelFormat(t_png_ptr);
}
if (t_success)
{
t_data_ptr = (png_bytep)p_bitmap->data;
t_stride = p_bitmap->stride;
}
if (t_success)
{
for (uindex_t i = 0; i < p_bitmap->height; i++)
{
png_write_row(t_png_ptr, t_data_ptr);
t_data_ptr += t_stride;
}
}
if (t_success)
png_write_end(t_png_ptr, t_info_ptr);
if (t_png_ptr != nil)
png_destroy_write_struct(&t_png_ptr, &t_info_ptr);
if (t_png_palette != nil)
MCMemoryDeleteArray(t_png_palette);
if (t_png_transparency != nil)
MCMemoryDeallocate(t_png_transparency);
if (t_success)
r_bytes_written = t_context.byte_count;
return t_success;
}
////////////////////////////////////////////////////////////////////////////////
| Java |
<?php
ob_start();
session_start();
if (session_status() == PHP_SESSION_NONE) {
require_once('index.php');
header($uri . '/index.php');
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Creates a new University by a Super Admin">
<title>Create University</title>
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container form-sigin">
<?php
//HTML tags for error messages
$err = "<h4 class=\"form-signin-error\">";
$suc = "<h4 class=\"form-signin-success\">";
$end = "</h4>";
$success = $rso = "";
$rsoErr = "";
$missing_data = [];
$name = [];
//Populates dropdown
require_once('connect.php');
$queryDB = "SELECT * FROM rso";
$result = mysqli_query($database, $queryDB);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
array_push($name,$row['name']);
}
}
if (empty($_POST["rsoSel"]))
{
$missing_data[] = "RSO";
$rsoErr = $err."RSO is required".$end;
}
else {
$rso = trim_input($_POST["rsoSel"]);
}
// Check for each required input data that has been POSTed through Request Method
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($missing_data)) {
require_once('connect.php');
$query = "INSERT INTO member (student_id, rso) VALUES (?, ?)";
$stmt = mysqli_prepare($database, $query);
mysqli_stmt_bind_param($stmt, "ss", $_SESSION['username'], $rso);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if ($affected_rows == 1) {
mysqli_stmt_close($stmt);
mysqli_close($database);
$success = $suc."You've join an RSO".$end;
}
else {
$success = $err."Please reselect a RSO".$end;
mysqli_stmt_close($stmt);
mysqli_close($database);
}
}
}
//process input data
function trim_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</div>
<div class="flex-container">
<header>
<h1> JOIN RSO </h1>
<span><b><?php echo "Welcome ". $_SESSION['username'] . "<br />";
if($_SESSION['user_type']=='s'){ echo "Student Account";}
elseif($_SESSION['user_type']=='a'){ echo "Admin Account";}
elseif($_SESSION['user_type']=='sa'){ echo "Super Admin Account";}?></b></span><br />
<a href="LOGOUT.php" target="_self"> Log Out</a><br />
</header>
<nav class="nav">
<ul>
<?php
if($_SESSION['user_type']== 's'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>";
}
elseif($_SESSION['user_type']== 'a'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createEvent.html\" target=\"_self\"> Create Event</a><br /></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>";
}
elseif($_SESSION['user_type']== 'sa'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createuniversity.php\" target=\"_self\"> Create University</a></b></li>";
}
?>
</ul>
</nav>
<article class="article">
<div class="container">
<form class="form-signin" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php echo $success; ?>
<?php echo $rsoErr ?>
<select class="form-control" name="rsoSel">
<?php
for($x = 0; $x <= count($name); $x++){
echo "<option value=" . $name[$x] . ">" . $name[$x] . "</option>";
}
?>
<input class = "btn btn-lg btn-primary btn-block" type="submit" value="Join"></input><br />
</form>
</div>
</article>
<div>
</body>
</html>
| Java |
<?php
/**
* Class for the definition of a widget that is
* called by the class of the main module
*
* @package SZGoogle
* @subpackage Widgets
* @author Massimo Della Rovere
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
if (!defined('SZ_PLUGIN_GOOGLE') or !SZ_PLUGIN_GOOGLE) die();
// Before the definition of the class, check if there is a definition
// with the same name or the same as previously defined in other script
if (!class_exists('SZGoogleWidgetDriveSaveButton'))
{
class SZGoogleWidgetDriveSaveButton extends SZGoogleWidget
{
/**
* Definition the constructor function, which is called
* at the time of the creation of an instance of this class
*/
function __construct()
{
parent::__construct('SZ-Google-Drive-Save-Button',__('SZ-Google - Drive Save Button','szgoogleadmin'),array(
'classname' => 'sz-widget-google sz-widget-google-drive sz-widget-google-drive-save-button',
'description' => ucfirst(__('google drive save button.','szgoogleadmin'))
));
}
/**
* Generation of the HTML code of the widget
* for the full display in the sidebar associated
*/
function widget($args,$instance)
{
// Checking whether there are the variables that are used during the processing
// the script and check the default values in case they were not specified
$options = $this->common_empty(array(
'url' => '', // default value
'filename' => '', // default value
'sitename' => '', // default value
'text' => '', // default value
'img' => '', // default value
'position' => '', // default value
'align' => '', // default value
'margintop' => '', // default value
'marginright' => '', // default value
'marginbottom' => '', // default value
'marginleft' => '', // default value
'marginunit' => '', // default value
),$instance);
// Definition of the control variables of the widget, these values
// do not affect the items of basic but affect some aspects
$controls = $this->common_empty(array(
'badge' => '', // default value
),$instance);
// If the widget I excluded from the badge button I reset
// the variables of the badge possibly set and saved
if ($controls['badge'] != '1') {
$options['img'] = '';
$options['text'] = '';
$options['position'] = '';
}
// Create the HTML code for the current widget recalling the basic
// function which is also invoked by the corresponding shortcode
$OBJC = new SZGoogleActionDriveSave();
$HTML = $OBJC->getHTMLCode($options);
// Output HTML code linked to the widget to
// display call to the general standard for wrap
echo $this->common_widget($args,$instance,$HTML);
}
/**
* Changing parameters related to the widget FORM
* with storing the values directly in the database
*/
function update($new_instance,$old_instance)
{
// Performing additional operations on fields of the
// form widget before it is stored in the database
return $this->common_update(array(
'title' => '0', // strip_tags
'badge' => '1', // strip_tags
'url' => '0', // strip_tags
'text' => '0', // strip_tags
'img' => '1', // strip_tags
'align' => '1', // strip_tags
'position' => '1', // strip_tags
),$new_instance,$old_instance);
}
/**
* FORM display the widget in the management of
* sidebar in the administration panel of wordpress
*/
function form($instance)
{
// Creating arrays for list fields that must be
// present in the form before calling wp_parse_args()
$array = array(
'title' => '', // default value
'badge' => '', // default value
'url' => '', // default value
'text' => '', // default value
'img' => '', // default value
'align' => '', // default value
'position' => '', // default value
);
// Creating arrays for list of fields to be retrieved FORM
// and loading the file with the HTML template to display
extract(wp_parse_args($instance,$array),EXTR_OVERWRITE);
// Calling the template for displaying the part
// that concerns the administration panel (admin)
@include(dirname(SZ_PLUGIN_GOOGLE_MAIN).'/admin/widgets/SZGoogleWidget.php');
@include(dirname(SZ_PLUGIN_GOOGLE_MAIN).'/admin/widgets/' .__CLASS__.'.php');
}
}
} | Java |
// tutorial06.c
// A pedagogical video player that really works!
//
// Code based on FFplay, Copyright (c) 2003 Fabrice Bellard,
// and a tutorial by Martin Bohme ([email protected])
// Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1
// Use
//
// gcc -o tutorial02 tutorial02.c -lavutil -lavformat -lavcodec -lz -lm `sdl-config --cflags --libs`
// to build (assuming libavformat and libavcodec are correctly installed,
// and assuming you have sdl-config. Please refer to SDL docs for your installation.)
//
// Run using
// tutorial06 myvideofile.mpg
//
// to play the video.
#include <ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>
#include <SDL.h>
#include <SDL_thread.h>
#ifdef __MINGW32__
#undef main /* Prevents SDL from overriding main() */
#endif
#include <stdio.h>
#include <math.h>
#define SDL_AUDIO_BUFFER_SIZE 1024
#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
#define AV_SYNC_THRESHOLD 0.01
#define AV_NOSYNC_THRESHOLD 10.0
#define SAMPLE_CORRECTION_PERCENT_MAX 10
#define AUDIO_DIFF_AVG_NB 20
#define FF_ALLOC_EVENT (SDL_USEREVENT)
#define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
#define FF_QUIT_EVENT (SDL_USEREVENT + 2)
#define VIDEO_PICTURE_QUEUE_SIZE 1
#define DEFAULT_AV_SYNC_TYPE AV_SYNC_VIDEO_MASTER
typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutex;
SDL_cond *cond;
} PacketQueue;
typedef struct VideoPicture {
SDL_Overlay *bmp;
int width, height; /* source height & width */
int allocated;
double pts;
} VideoPicture;
typedef struct VideoState {
AVFormatContext *pFormatCtx;
int videoStream, audioStream;
int av_sync_type;
double external_clock; /* external clock base */
int64_t external_clock_time;
double audio_clock;
AVStream *audio_st;
PacketQueue audioq;
uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2];
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVPacket audio_pkt;
uint8_t *audio_pkt_data;
int audio_pkt_size;
int audio_hw_buf_size;
double audio_diff_cum; /* used for AV difference average computation */
double audio_diff_avg_coef;
double audio_diff_threshold;
int audio_diff_avg_count;
double frame_timer;
double frame_last_pts;
double frame_last_delay;
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used)
int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts
AVStream *video_st;
PacketQueue videoq;
VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
int pictq_size, pictq_rindex, pictq_windex;
SDL_mutex *pictq_mutex;
SDL_cond *pictq_cond;
SDL_Thread *parse_tid;
SDL_Thread *video_tid;
char filename[1024];
int quit;
} VideoState;
enum {
AV_SYNC_AUDIO_MASTER,
AV_SYNC_VIDEO_MASTER,
AV_SYNC_EXTERNAL_MASTER,
};
SDL_Surface *screen;
/* Since we only have one decoding thread, the Big Struct
can be global in case we need it. */
VideoState *global_video_state;
void packet_queue_init(PacketQueue *q) {
memset(q, 0, sizeof(PacketQueue));
q->mutex = SDL_CreateMutex();
q->cond = SDL_CreateCond();
}
int packet_queue_put(PacketQueue *q, AVPacket *pkt) {
AVPacketList *pkt1;
if(av_dup_packet(pkt) < 0) {
return -1;
}
pkt1 = av_malloc(sizeof(AVPacketList));
if (!pkt1)
return -1;
pkt1->pkt = *pkt;
pkt1->next = NULL;
SDL_LockMutex(q->mutex);
if (!q->last_pkt)
q->first_pkt = pkt1;
else
q->last_pkt->next = pkt1;
q->last_pkt = pkt1;
q->nb_packets++;
q->size += pkt1->pkt.size;
SDL_CondSignal(q->cond);
SDL_UnlockMutex(q->mutex);
return 0;
}
static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
{
AVPacketList *pkt1;
int ret;
SDL_LockMutex(q->mutex);
for(;;) {
if(global_video_state->quit) {
ret = -1;
break;
}
pkt1 = q->first_pkt;
if (pkt1) {
q->first_pkt = pkt1->next;
if (!q->first_pkt)
q->last_pkt = NULL;
q->nb_packets--;
q->size -= pkt1->pkt.size;
*pkt = pkt1->pkt;
av_free(pkt1);
ret = 1;
break;
} else if (!block) {
ret = 0;
break;
} else {
SDL_CondWait(q->cond, q->mutex);
}
}
SDL_UnlockMutex(q->mutex);
return ret;
}
double get_audio_clock(VideoState *is) {
double pts;
int hw_buf_size, bytes_per_sec, n;
pts = is->audio_clock; /* maintained in the audio thread */
hw_buf_size = is->audio_buf_size - is->audio_buf_index;
bytes_per_sec = 0;
n = is->audio_st->codec->channels * 2;
if(is->audio_st) {
bytes_per_sec = is->audio_st->codec->sample_rate * n;
}
if(bytes_per_sec) {
pts -= (double)hw_buf_size / bytes_per_sec;
}
return pts;
}
double get_video_clock(VideoState *is) {
double delta;
delta = (av_gettime() - is->video_current_pts_time) / 1000000.0;
return is->video_current_pts + delta;
}
double get_external_clock(VideoState *is) {
return av_gettime() / 1000000.0;
}
double get_master_clock(VideoState *is) {
if(is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
return get_video_clock(is);
} else if(is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
return get_audio_clock(is);
} else {
return get_external_clock(is);
}
}
/* Add or subtract samples to get a better sync, return new
audio buffer size */
int synchronize_audio(VideoState *is, short *samples,
int samples_size, double pts) {
int n;
double ref_clock;
n = 2 * is->audio_st->codec->channels;
if(is->av_sync_type != AV_SYNC_AUDIO_MASTER) {
double diff, avg_diff;
int wanted_size, min_size, max_size, nb_samples;
ref_clock = get_master_clock(is);
diff = get_audio_clock(is) - ref_clock;
if(diff < AV_NOSYNC_THRESHOLD) {
// accumulate the diffs
is->audio_diff_cum = diff + is->audio_diff_avg_coef
* is->audio_diff_cum;
if(is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
is->audio_diff_avg_count++;
} else {
avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
if(fabs(avg_diff) >= is->audio_diff_threshold) {
wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n);
min_size = samples_size * ((100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100);
max_size = samples_size * ((100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100);
if(wanted_size < min_size) {
wanted_size = min_size;
} else if (wanted_size > max_size) {
wanted_size = max_size;
}
if(wanted_size < samples_size) {
/* remove samples */
samples_size = wanted_size;
} else if(wanted_size > samples_size) {
uint8_t *samples_end, *q;
int nb;
/* add samples by copying final sample*/
nb = (samples_size - wanted_size);
samples_end = (uint8_t *)samples + samples_size - n;
q = samples_end + n;
while(nb > 0) {
memcpy(q, samples_end, n);
q += n;
nb -= n;
}
samples_size = wanted_size;
}
}
}
} else {
/* difference is TOO big; reset diff stuff */
is->audio_diff_avg_count = 0;
is->audio_diff_cum = 0;
}
}
return samples_size;
}
int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) {
int len1, data_size, n;
AVPacket *pkt = &is->audio_pkt;
double pts;
for(;;) {
while(is->audio_pkt_size > 0) {
data_size = buf_size;
len1 = avcodec_decode_audio2(is->audio_st->codec,
(int16_t *)audio_buf, &data_size,
is->audio_pkt_data, is->audio_pkt_size);
if(len1 < 0) {
/* if error, skip frame */
is->audio_pkt_size = 0;
break;
}
is->audio_pkt_data += len1;
is->audio_pkt_size -= len1;
if(data_size <= 0) {
/* No data yet, get more frames */
continue;
}
pts = is->audio_clock;
*pts_ptr = pts;
n = 2 * is->audio_st->codec->channels;
is->audio_clock += (double)data_size /
(double)(n * is->audio_st->codec->sample_rate);
/* We have data, return it and come back for more later */
return data_size;
}
if(pkt->data)
av_free_packet(pkt);
if(is->quit) {
return -1;
}
/* next packet */
if(packet_queue_get(&is->audioq, pkt, 1) < 0) {
return -1;
}
is->audio_pkt_data = pkt->data;
is->audio_pkt_size = pkt->size;
/* if update, update the audio clock w/pts */
if(pkt->pts != AV_NOPTS_VALUE) {
is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
}
}
}
void audio_callback(void *userdata, Uint8 *stream, int len) {
VideoState *is = (VideoState *)userdata;
int len1, audio_size;
double pts;
while(len > 0) {
if(is->audio_buf_index >= is->audio_buf_size) {
/* We have already sent all our data; get more */
audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts);
if(audio_size < 0) {
/* If error, output silence */
is->audio_buf_size = 1024;
memset(is->audio_buf, 0, is->audio_buf_size);
} else {
audio_size = synchronize_audio(is, (int16_t *)is->audio_buf,
audio_size, pts);
is->audio_buf_size = audio_size;
}
is->audio_buf_index = 0;
}
len1 = is->audio_buf_size - is->audio_buf_index;
if(len1 > len)
len1 = len;
memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
len -= len1;
stream += len1;
is->audio_buf_index += len1;
}
}
static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) {
SDL_Event event;
event.type = FF_REFRESH_EVENT;
event.user.data1 = opaque;
SDL_PushEvent(&event);
return 0; /* 0 means stop timer */
}
/* schedule a video refresh in 'delay' ms */
static void schedule_refresh(VideoState *is, int delay) {
SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
}
void video_display(VideoState *is) {
SDL_Rect rect;
VideoPicture *vp;
AVPicture pict;
float aspect_ratio;
int w, h, x, y;
int i;
vp = &is->pictq[is->pictq_rindex];
if(vp->bmp) {
if(is->video_st->codec->sample_aspect_ratio.num == 0) {
aspect_ratio = 0;
} else {
aspect_ratio = av_q2d(is->video_st->codec->sample_aspect_ratio) *
is->video_st->codec->width / is->video_st->codec->height;
}
if(aspect_ratio <= 0.0) {
aspect_ratio = (float)is->video_st->codec->width /
(float)is->video_st->codec->height;
}
h = screen->h;
w = ((int)rint(h * aspect_ratio)) & -3;
if(w > screen->w) {
w = screen->w;
h = ((int)rint(w / aspect_ratio)) & -3;
}
x = (screen->w - w) / 2;
y = (screen->h - h) / 2;
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
SDL_DisplayYUVOverlay(vp->bmp, &rect);
}
}
void video_refresh_timer(void *userdata) {
VideoState *is = (VideoState *)userdata;
VideoPicture *vp;
double actual_delay, delay, sync_threshold, ref_clock, diff;
if(is->video_st) {
if(is->pictq_size == 0) {
schedule_refresh(is, 1);
} else {
vp = &is->pictq[is->pictq_rindex];
is->video_current_pts = vp->pts;
is->video_current_pts_time = av_gettime();
delay = vp->pts - is->frame_last_pts; /* the pts from last time */
if(delay <= 0 || delay >= 1.0) {
/* if incorrect delay, use previous one */
delay = is->frame_last_delay;
}
/* save for next time */
is->frame_last_delay = delay;
is->frame_last_pts = vp->pts;
/* update delay to sync to audio if not master source */
if(is->av_sync_type != AV_SYNC_VIDEO_MASTER) {
ref_clock = get_master_clock(is);
diff = vp->pts - ref_clock;
/* Skip or repeat the frame. Take delay into account
FFPlay still doesn't "know if this is the best guess." */
sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD;
if(fabs(diff) < AV_NOSYNC_THRESHOLD) {
if(diff <= -sync_threshold) {
delay = 0;
} else if(diff >= sync_threshold) {
delay = 2 * delay;
}
}
}
is->frame_timer += delay;
/* computer the REAL delay */
actual_delay = is->frame_timer - (av_gettime() / 1000000.0);
if(actual_delay < 0.010) {
/* Really it should skip the picture instead */
actual_delay = 0.010;
}
schedule_refresh(is, (int)(actual_delay * 1000 + 0.5));
/* show the picture! */
video_display(is);
/* update queue for next picture! */
if(++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) {
is->pictq_rindex = 0;
}
SDL_LockMutex(is->pictq_mutex);
is->pictq_size--;
SDL_CondSignal(is->pictq_cond);
SDL_UnlockMutex(is->pictq_mutex);
}
} else {
schedule_refresh(is, 100);
}
}
void alloc_picture(void *userdata) {
VideoState *is = (VideoState *)userdata;
VideoPicture *vp;
vp = &is->pictq[is->pictq_windex];
if(vp->bmp) {
// we already have one make another, bigger/smaller
SDL_FreeYUVOverlay(vp->bmp);
}
// Allocate a place to put our YUV image on that screen
vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec->width,
is->video_st->codec->height,
SDL_YV12_OVERLAY,
screen);
vp->width = is->video_st->codec->width;
vp->height = is->video_st->codec->height;
SDL_LockMutex(is->pictq_mutex);
vp->allocated = 1;
SDL_CondSignal(is->pictq_cond);
SDL_UnlockMutex(is->pictq_mutex);
}
int queue_picture(VideoState *is, AVFrame *pFrame, double pts) {
VideoPicture *vp;
int dst_pix_fmt;
AVPicture pict;
/* wait until we have space for a new pic */
SDL_LockMutex(is->pictq_mutex);
while(is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
!is->quit) {
SDL_CondWait(is->pictq_cond, is->pictq_mutex);
}
SDL_UnlockMutex(is->pictq_mutex);
if(is->quit)
return -1;
// windex is set to 0 initially
vp = &is->pictq[is->pictq_windex];
/* allocate or resize the buffer! */
if(!vp->bmp ||
vp->width != is->video_st->codec->width ||
vp->height != is->video_st->codec->height) {
SDL_Event event;
vp->allocated = 0;
/* we have to do it in the main thread */
event.type = FF_ALLOC_EVENT;
event.user.data1 = is;
SDL_PushEvent(&event);
/* wait until we have a picture allocated */
SDL_LockMutex(is->pictq_mutex);
while(!vp->allocated && !is->quit) {
SDL_CondWait(is->pictq_cond, is->pictq_mutex);
}
SDL_UnlockMutex(is->pictq_mutex);
if(is->quit) {
return -1;
}
}
/* We have a place to put our picture on the queue */
/* If we are skipping a frame, do we set this to null
but still return vp->allocated = 1? */
if(vp->bmp) {
SDL_LockYUVOverlay(vp->bmp);
dst_pix_fmt = PIX_FMT_YUV420P;
/* point pict at the queue */
pict.data[0] = vp->bmp->pixels[0];
pict.data[1] = vp->bmp->pixels[2];
pict.data[2] = vp->bmp->pixels[1];
pict.linesize[0] = vp->bmp->pitches[0];
pict.linesize[1] = vp->bmp->pitches[2];
pict.linesize[2] = vp->bmp->pitches[1];
// Convert the image into YUV format that SDL uses
img_convert(&pict, dst_pix_fmt,
(AVPicture *)pFrame, is->video_st->codec->pix_fmt,
is->video_st->codec->width, is->video_st->codec->height);
SDL_UnlockYUVOverlay(vp->bmp);
vp->pts = pts;
/* now we inform our display thread that we have a pic ready */
if(++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) {
is->pictq_windex = 0;
}
SDL_LockMutex(is->pictq_mutex);
is->pictq_size++;
SDL_UnlockMutex(is->pictq_mutex);
}
return 0;
}
double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) {
double frame_delay;
if(pts != 0) {
/* if we have pts, set video clock to it */
is->video_clock = pts;
} else {
/* if we aren't given a pts, set it to the clock */
pts = is->video_clock;
}
/* update the video clock */
frame_delay = av_q2d(is->video_st->codec->time_base);
/* if we are repeating a frame, adjust clock accordingly */
frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
is->video_clock += frame_delay;
return pts;
}
uint64_t global_video_pkt_pts = AV_NOPTS_VALUE;
/* These are called whenever we allocate a frame
* buffer. We use this to store the global_pts in
* a frame at the time it is allocated.
*/
int our_get_buffer(struct AVCodecContext *c, AVFrame *pic) {
int ret = avcodec_default_get_buffer(c, pic);
uint64_t *pts = av_malloc(sizeof(uint64_t));
*pts = global_video_pkt_pts;
pic->opaque = pts;
return ret;
}
void our_release_buffer(struct AVCodecContext *c, AVFrame *pic) {
if(pic) av_freep(&pic->opaque);
avcodec_default_release_buffer(c, pic);
}
int video_thread(void *arg) {
VideoState *is = (VideoState *)arg;
AVPacket pkt1, *packet = &pkt1;
int len1, frameFinished;
AVFrame *pFrame;
double pts;
pFrame = avcodec_alloc_frame();
for(;;) {
if(packet_queue_get(&is->videoq, packet, 1) < 0) {
// means we quit getting packets
break;
}
pts = 0;
// Save global pts to be stored in pFrame in first call
global_video_pkt_pts = packet->pts;
// Decode video frame
len1 = avcodec_decode_video(is->video_st->codec, pFrame, &frameFinished,
packet->data, packet->size);
if(packet->dts == AV_NOPTS_VALUE
&& pFrame->opaque && *(uint64_t*)pFrame->opaque != AV_NOPTS_VALUE) {
pts = *(uint64_t *)pFrame->opaque;
} else if(packet->dts != AV_NOPTS_VALUE) {
pts = packet->dts;
} else {
pts = 0;
}
pts *= av_q2d(is->video_st->time_base);
// Did we get a video frame?
if(frameFinished) {
pts = synchronize_video(is, pFrame, pts);
if(queue_picture(is, pFrame, pts) < 0) {
break;
}
}
av_free_packet(packet);
}
av_free(pFrame);
return 0;
}
int stream_component_open(VideoState *is, int stream_index) {
AVFormatContext *pFormatCtx = is->pFormatCtx;
AVCodecContext *codecCtx;
AVCodec *codec;
SDL_AudioSpec wanted_spec, spec;
if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) {
return -1;
}
// Get a pointer to the codec context for the video stream
codecCtx = pFormatCtx->streams[stream_index]->codec;
if(codecCtx->codec_type == CODEC_TYPE_AUDIO) {
// Set audio settings from codec info
wanted_spec.freq = codecCtx->sample_rate;
wanted_spec.format = AUDIO_S16SYS;
wanted_spec.channels = codecCtx->channels;
wanted_spec.silence = 0;
wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
wanted_spec.callback = audio_callback;
wanted_spec.userdata = is;
if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
return -1;
}
is->audio_hw_buf_size = spec.size;
}
codec = avcodec_find_decoder(codecCtx->codec_id);
if(!codec || (avcodec_open(codecCtx, codec) < 0)) {
fprintf(stderr, "Unsupported codec!\n");
return -1;
}
switch(codecCtx->codec_type) {
case CODEC_TYPE_AUDIO:
is->audioStream = stream_index;
is->audio_st = pFormatCtx->streams[stream_index];
is->audio_buf_size = 0;
is->audio_buf_index = 0;
/* averaging filter for audio sync */
is->audio_diff_avg_coef = exp(log(0.01 / AUDIO_DIFF_AVG_NB));
is->audio_diff_avg_count = 0;
/* Correct audio only if larger error than this */
is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / codecCtx->sample_rate;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
packet_queue_init(&is->audioq);
SDL_PauseAudio(0);
break;
case CODEC_TYPE_VIDEO:
is->videoStream = stream_index;
is->video_st = pFormatCtx->streams[stream_index];
is->frame_timer = (double)av_gettime() / 1000000.0;
is->frame_last_delay = 40e-3;
is->video_current_pts_time = av_gettime();
packet_queue_init(&is->videoq);
is->video_tid = SDL_CreateThread(video_thread, is);
codecCtx->get_buffer = our_get_buffer;
codecCtx->release_buffer = our_release_buffer;
break;
default:
break;
}
}
int decode_interrupt_cb(void) {
return (global_video_state && global_video_state->quit);
}
int decode_thread(void *arg) {
VideoState *is = (VideoState *)arg;
AVFormatContext *pFormatCtx;
AVPacket pkt1, *packet = &pkt1;
int video_index = -1;
int audio_index = -1;
int i;
is->videoStream=-1;
is->audioStream=-1;
global_video_state = is;
// will interrupt blocking functions if we quit!
url_set_interrupt_cb(decode_interrupt_cb);
// Open video file
if(av_open_input_file(&pFormatCtx, is->filename, NULL, 0, NULL)!=0)
return -1; // Couldn't open file
is->pFormatCtx = pFormatCtx;
// Retrieve stream information
if(av_find_stream_info(pFormatCtx)<0)
return -1; // Couldn't find stream information
// Dump information about file onto standard error
dump_format(pFormatCtx, 0, is->filename, 0);
// Find the first video stream
for(i=0; i<pFormatCtx->nb_streams; i++) {
if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO &&
video_index < 0) {
video_index=i;
}
if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO &&
audio_index < 0) {
audio_index=i;
}
}
if(audio_index >= 0) {
stream_component_open(is, audio_index);
}
if(video_index >= 0) {
stream_component_open(is, video_index);
}
if(is->videoStream < 0 || is->audioStream < 0) {
fprintf(stderr, "%s: could not open codecs\n", is->filename);
goto fail;
}
// main decode loop
for(;;) {
if(is->quit) {
break;
}
// seek stuff goes here
if(is->audioq.size > MAX_AUDIOQ_SIZE ||
is->videoq.size > MAX_VIDEOQ_SIZE) {
SDL_Delay(10);
continue;
}
if(av_read_frame(is->pFormatCtx, packet) < 0) {
if(url_ferror(&pFormatCtx->pb) == 0) {
SDL_Delay(100); /* no error; wait for user input */
continue;
} else {
break;
}
}
// Is this a packet from the video stream?
if(packet->stream_index == is->videoStream) {
packet_queue_put(&is->videoq, packet);
} else if(packet->stream_index == is->audioStream) {
packet_queue_put(&is->audioq, packet);
} else {
av_free_packet(packet);
}
}
/* all done - wait for it */
while(!is->quit) {
SDL_Delay(100);
}
fail:
{
SDL_Event event;
event.type = FF_QUIT_EVENT;
event.user.data1 = is;
SDL_PushEvent(&event);
}
return 0;
}
int main(int argc, char *argv[]) {
SDL_Event event;
VideoState *is;
is = av_mallocz(sizeof(VideoState));
if(argc < 2) {
fprintf(stderr, "Usage: test <file>\n");
exit(1);
}
// Register all formats and codecs
av_register_all();
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
exit(1);
}
// Make a screen to put our video
#ifndef __DARWIN__
screen = SDL_SetVideoMode(640, 480, 0, 0);
#else
screen = SDL_SetVideoMode(640, 480, 24, 0);
#endif
if(!screen) {
fprintf(stderr, "SDL: could not set video mode - exiting\n");
exit(1);
}
pstrcpy(is->filename, sizeof(is->filename), argv[1]);
is->pictq_mutex = SDL_CreateMutex();
is->pictq_cond = SDL_CreateCond();
schedule_refresh(is, 40);
is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
is->parse_tid = SDL_CreateThread(decode_thread, is);
if(!is->parse_tid) {
av_free(is);
return -1;
}
for(;;) {
SDL_WaitEvent(&event);
switch(event.type) {
case FF_QUIT_EVENT:
case SDL_QUIT:
is->quit = 1;
SDL_Quit();
exit(0);
break;
case FF_ALLOC_EVENT:
alloc_picture(event.user.data1);
break;
case FF_REFRESH_EVENT:
video_refresh_timer(event.user.data1);
break;
default:
break;
}
}
return 0;
}
| Java |
/*
* Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM)
*
* Copyright (C) 2013 Open Education Foundation
*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
* l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of OpenBoard.
*
* OpenBoard 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* OpenBoard 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 OpenBoard. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UBIDLETIMER_H_
#define UBIDLETIMER_H_
#include <QObject>
#include <QDateTime>
class QEvent;
class UBIdleTimer : public QObject
{
Q_OBJECT
public:
UBIdleTimer(QObject *parent = 0);
virtual ~UBIdleTimer();
protected:
bool eventFilter(QObject *obj, QEvent *event);
virtual void timerEvent(QTimerEvent *event);
private:
QDateTime mLastInputEventTime;
bool mCursorIsHidden;
};
#endif /* UBIDLETIMER_H_ */
| Java |
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: mods/deathmatch/logic/CPlayerStats.h
* PURPOSE: Player statistics class
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
class CPlayerStats;
#pragma once
#include <vector>
using namespace std;
struct sStat
{
unsigned short id;
float value;
};
class CPlayerStats
{
public:
~CPlayerStats();
bool GetStat(unsigned short usID, float& fValue);
void SetStat(unsigned short usID, float fValue);
vector<sStat*>::const_iterator IterBegin() { return m_List.begin(); }
vector<sStat*>::const_iterator IterEnd() { return m_List.end(); }
unsigned short GetSize() { return static_cast<unsigned short>(m_List.size()); }
private:
vector<sStat*> m_List;
};
| Java |
'''Test the analysis.signal module.'''
from __future__ import absolute_import, print_function, division
import pytest
import numpy as np
import gridcells.analysis.signal as asignal
from gridcells.analysis.signal import (local_extrema, local_maxima,
local_minima, ExtremumTypes,
LocalExtrema)
RTOL = 1e-10
def _data_generator(n_items, sz):
'''Generate pairs of test vectors.'''
it = 0
while it < n_items:
N1 = np.random.randint(sz) + 1
N2 = np.random.randint(sz) + 1
if N1 == 0 and N2 == 0:
continue
a1 = np.random.rand(N1)
a2 = np.random.rand(N2)
yield (a1, a2)
it += 1
class TestCorrelation(object):
'''
Test the analysis.signal.corr function (and effectively the core of the
autoCorrelation) function.
'''
maxN = 500
maxLoops = 1000
def test_onesided(self):
'''Test the one-sided version of ``corr``.'''
for a1, a2 in _data_generator(self.maxLoops, self.maxN):
c_cpp = asignal.corr(a1, a2, mode='onesided')
c_np = np.correlate(a1, a2, mode='full')[::-1][a1.size - 1:]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_twosided(self):
'''Test the two-sided version of ``corr``.'''
for a1, a2 in _data_generator(self.maxLoops, self.maxN):
c_cpp = asignal.corr(a1, a2, mode='twosided')
c_np = np.correlate(a1, a2, mode='full')[::-1]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_range(self):
'''Test the ranged version of ``corr``.'''
# Half the range of both signals
for a1, a2 in _data_generator(self.maxLoops, self.maxN):
if a1.size <= 1 or a2.size <= 1:
continue
lag_start = - (a1.size // 2)
lag_end = a2.size // 2
c_np_centre = a1.size - 1
c_cpp = asignal.corr(a1, a2, mode='range', lag_start=lag_start,
lag_end=lag_end)
c_np = np.correlate(a1, a2, mode='full')[::-1]
np.testing.assert_allclose(
c_cpp,
c_np[c_np_centre + lag_start:c_np_centre + lag_end + 1],
rtol=RTOL)
def test_zero_len(self):
'''Test that an exception is raised when inputs have zero length.'''
a1 = np.array([])
a2 = np.arange(10)
# corr(a1, a2)
lag_start = 0
lag_end = 0
for mode in ("onesided", "twosided", "range"):
with pytest.raises(TypeError):
asignal.corr(a1, a2, mode, lag_start, lag_end)
with pytest.raises(TypeError):
asignal.corr(a2, a1, mode, lag_start, lag_end)
with pytest.raises(TypeError):
asignal.corr(a1, a1, mode, lag_start, lag_end)
def test_non_double(self):
'''Test the corr function when dtype is not double.'''
a1 = np.array([1, 2, 3], dtype=int)
asignal.corr(a1, a1, mode='twosided')
class TestAutoCorrelation(object):
'''Test the acorr function.'''
maxN = 500
maxLoops = 1000
def test_default_params(self):
'''Test default parameters.'''
a = np.arange(10)
c_cpp = asignal.acorr(a)
c_np = np.correlate(a, a, mode='full')[::-1][a.size - 1:]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_onesided(self):
'''Test the one-sided version of ``corr``.'''
a = np.arange(10)
c_cpp = asignal.acorr(a, mode='onesided', max_lag=5)
c_np = np.correlate(a, a, mode='full')[::-1][a.size - 1:a.size - 1 + 6]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_twosided(self):
'''Test the two-sided version of ``corr``.'''
a = np.arange(10)
c_cpp = asignal.acorr(a, mode='twosided', max_lag=5)
c_np = np.correlate(a, a, mode='full')[::-1][a.size - 6:a.size + 5]
np.testing.assert_allclose(c_cpp, c_np, rtol=RTOL)
def test_norm(self):
'''Test normalization.'''
# Simple array
a = np.arange(10)
c_cpp = asignal.acorr(a, mode='twosided', norm=True)
c_np = np.correlate(a, a, mode='full')[::-1]
np.testing.assert_allclose(c_cpp, c_np / np.max(c_np), rtol=RTOL)
# A zero array will return zero
zero_array = np.zeros(13)
c_cpp = asignal.acorr(zero_array, mode='twosided', norm=True)
assert np.all(c_cpp == 0.)
def generate_sin(n_half_cycles, resolution=100):
'''Generate a sine function with a number of (full) half cycles.
Note that the positions of the extrema might be shifted +/- 1 with respect
to the actual real sin because of possible rounding errors.
Parameters
----------
n_half_cycles : int
Number of half cycles to generate. Does not have to be even.
resolution : int
Number of data points for each half cycle.
'''
if n_half_cycles < 1:
raise ValueError()
if resolution < 1:
raise ValueError()
f = 1. / (2 * resolution)
t = np.arange(n_half_cycles * resolution, dtype=float)
sig = np.sin(2 * np.pi * f * t)
extrema_positions = np.array(np.arange(n_half_cycles) * resolution +
resolution / 2,
dtype=int)
extrema_types = []
current_type = ExtremumTypes.MAX
for _ in range(n_half_cycles):
extrema_types.append(current_type)
if current_type is ExtremumTypes.MAX:
current_type = ExtremumTypes.MIN
else:
current_type = ExtremumTypes.MAX
return (sig, extrema_positions, np.array(extrema_types))
class TestLocalExtrema(object):
'''Test computation of local extrema.'''
def test_local_extrema(self):
for n_extrema in [1, 2, 51]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
extrema = local_extrema(sig)
assert len(extrema) == n_extrema
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
extrema.get_type(ExtremumTypes.MIN))
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] ==
extrema.get_type(ExtremumTypes.MAX))
def test_zero_array(self):
for func in [local_extrema, local_maxima, local_minima]:
extrema = func(np.empty(0))
assert len(extrema) == 0
def test_single_item(self):
'''This should return a zero length array.'''
for func in [local_extrema, local_maxima, local_minima]:
extrema = func(np.array([1.]))
assert len(extrema) == 0
def test_maxima(self):
# One maximum only
for n_extrema in [1, 2]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
maxima = local_maxima(sig)
assert len(maxima) == 1
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] ==
maxima)
# 2 maxima
for n_extrema in [3, 4]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
maxima = local_maxima(sig)
assert len(maxima) == 2
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MAX] ==
maxima)
def test_minima(self):
# Only one maximum so should return empty
n_extrema = 1
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
minima = local_minima(sig)
assert len(minima) == 0
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
minima)
# One maximum and minimum
n_extrema = 2
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
minima = local_minima(sig)
assert len(minima) == 1
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
minima)
# 2 minima
for n_extrema in [4, 5]:
sig, extrema_idx, extrema_types = generate_sin(n_extrema)
minima = local_minima(sig)
assert len(minima) == 2
assert np.all(extrema_idx[extrema_types == ExtremumTypes.MIN] ==
minima)
class TestLocalExtremaClass(object):
'''Test the local extremum object.'''
def test_empty(self):
extrema = LocalExtrema([], [])
assert len(extrema) == 0
assert len(extrema.get_type(ExtremumTypes.MIN)) == 0 # FIXME
def test_inconsistent_inputs(self):
with pytest.raises(IndexError):
extrema = LocalExtrema([], [1])
with pytest.raises(IndexError):
extrema = LocalExtrema(np.arange(10), [1])
def test_single_type(self):
N = 10
test_vector = np.arange(N)
for tested_type in ExtremumTypes:
extrema = LocalExtrema(test_vector, [tested_type] * N)
assert len(extrema) == N
for current_type in ExtremumTypes:
retrieved = extrema.get_type(current_type)
if current_type is tested_type:
assert len(retrieved) == N
assert np.all(retrieved == test_vector)
else:
assert len(retrieved) == 0
def test_mixed_types(self):
N = 10
test_vector = np.arange(10)
test_types = np.ones(N) * ExtremumTypes.MIN
test_types[0:10:2] = ExtremumTypes.MAX
extrema = LocalExtrema(test_vector, test_types)
assert len(extrema) == N
retrieved_min = extrema.get_type(ExtremumTypes.MIN)
assert np.all(retrieved_min == test_vector[1:10:2])
retrieved_max = extrema.get_type(ExtremumTypes.MAX)
assert np.all(retrieved_max == test_vector[0:10:2])
# Should not find any other types
for current_type in ExtremumTypes:
if (current_type is not ExtremumTypes.MIN and current_type is not
ExtremumTypes.MAX):
assert len(extrema.get_type(current_type)) == 0
| Java |
<?php
//require_once 'PEAR.php';
// commented by yogatama for use in gtfw
//require_once 'oleread.inc';
///////
//define('Spreadsheet_Excel_Reader_HAVE_ICONV', function_exists('iconv'));
//define('Spreadsheet_Excel_Reader_HAVE_MB', function_exists('mb_convert_encoding'));
define('Spreadsheet_Excel_Reader_BIFF8', 0x600);
define('Spreadsheet_Excel_Reader_BIFF7', 0x500);
define('Spreadsheet_Excel_Reader_WorkbookGlobals', 0x5);
define('Spreadsheet_Excel_Reader_Worksheet', 0x10);
define('Spreadsheet_Excel_Reader_Type_BOF', 0x809);
define('Spreadsheet_Excel_Reader_Type_EOF', 0x0a);
define('Spreadsheet_Excel_Reader_Type_BOUNDSHEET', 0x85);
define('Spreadsheet_Excel_Reader_Type_DIMENSION', 0x200);
define('Spreadsheet_Excel_Reader_Type_ROW', 0x208);
define('Spreadsheet_Excel_Reader_Type_DBCELL', 0xd7);
define('Spreadsheet_Excel_Reader_Type_FILEPASS', 0x2f);
define('Spreadsheet_Excel_Reader_Type_NOTE', 0x1c);
define('Spreadsheet_Excel_Reader_Type_TXO', 0x1b6);
define('Spreadsheet_Excel_Reader_Type_RK', 0x7e);
define('Spreadsheet_Excel_Reader_Type_RK2', 0x27e);
define('Spreadsheet_Excel_Reader_Type_MULRK', 0xbd);
define('Spreadsheet_Excel_Reader_Type_MULBLANK', 0xbe);
define('Spreadsheet_Excel_Reader_Type_INDEX', 0x20b);
define('Spreadsheet_Excel_Reader_Type_SST', 0xfc);
define('Spreadsheet_Excel_Reader_Type_EXTSST', 0xff);
define('Spreadsheet_Excel_Reader_Type_CONTINUE', 0x3c);
define('Spreadsheet_Excel_Reader_Type_LABEL', 0x204);
define('Spreadsheet_Excel_Reader_Type_LABELSST', 0xfd);
define('Spreadsheet_Excel_Reader_Type_NUMBER', 0x203);
define('Spreadsheet_Excel_Reader_Type_NAME', 0x18);
define('Spreadsheet_Excel_Reader_Type_ARRAY', 0x221);
define('Spreadsheet_Excel_Reader_Type_STRING', 0x207);
define('Spreadsheet_Excel_Reader_Type_FORMULA', 0x406);
define('Spreadsheet_Excel_Reader_Type_FORMULA2', 0x6);
define('Spreadsheet_Excel_Reader_Type_FORMAT', 0x41e);
define('Spreadsheet_Excel_Reader_Type_XF', 0xe0);
define('Spreadsheet_Excel_Reader_Type_BOOLERR', 0x205);
define('Spreadsheet_Excel_Reader_Type_UNKNOWN', 0xffff);
define('Spreadsheet_Excel_Reader_Type_NINETEENFOUR', 0x22);
define('Spreadsheet_Excel_Reader_Type_MERGEDCELLS', 0xE5);
define('Spreadsheet_Excel_Reader_utcOffsetDays' , 25569);
define('Spreadsheet_Excel_Reader_utcOffsetDays1904', 24107);
define('Spreadsheet_Excel_Reader_msInADay', 24 * 60 * 60);
//define('Spreadsheet_Excel_Reader_DEF_NUM_FORMAT', "%.2f");
define('Spreadsheet_Excel_Reader_DEF_NUM_FORMAT', "%s");
// function file_get_contents for PHP < 4.3.0
// Thanks Marian Steinbach for this function
if (!function_exists('file_get_contents')) {
function file_get_contents($filename, $use_include_path = 0) {
$data = '';
$file = @fopen($filename, "rb", $use_include_path);
if ($file) {
while (!feof($file)) $data .= fread($file, 1024);
fclose($file);
} else {
// There was a problem opening the file
$data = FALSE;
}
return $data;
}
}
//class Spreadsheet_Excel_Reader extends PEAR {
class Spreadsheet_Excel_Reader {
var $boundsheets = array();
var $formatRecords = array();
var $sst = array();
var $sheets = array();
var $data;
var $pos;
var $_ole;
var $_defaultEncoding;
var $_defaultFormat = Spreadsheet_Excel_Reader_DEF_NUM_FORMAT;
var $_columnsFormat = array();
var $_rowoffset = 1;
var $_coloffset = 1;
var $dateFormats = array (
0xe => "d/m/Y",
0xf => "d-M-Y",
0x10 => "d-M",
0x11 => "M-Y",
0x12 => "h:i a",
0x13 => "h:i:s a",
0x14 => "H:i",
0x15 => "H:i:s",
0x16 => "d/m/Y H:i",
0x2d => "i:s",
0x2e => "H:i:s",
0x2f => "i:s.S");
var $numberFormats = array(
0x1 => "%1.0f", // "0"
0x2 => "%1.2f", // "0.00",
0x3 => "%1.0f", //"#,##0",
0x4 => "%1.2f", //"#,##0.00",
0x5 => "%1.0f", /*"$#,##0;($#,##0)",*/
0x6 => '$%1.0f', /*"$#,##0;($#,##0)",*/
0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x9 => '%1.0f%%', // "0%"
0xa => '%1.2f%%', // "0.00%"
0xb => '%1.2f', // 0.00E00",
0x25 => '%1.0f', // "#,##0;(#,##0)",
0x26 => '%1.0f', //"#,##0;(#,##0)",
0x27 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x28 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x29 => '%1.0f', //"#,##0;(#,##0)",
0x2a => '$%1.0f', //"$#,##0;($#,##0)",
0x2b => '%1.2f', //"#,##0.00;(#,##0.00)",
0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x30 => '%1.0f'); //"##0.0E0";
function Spreadsheet_Excel_Reader(){
$this->_ole =& new OLERead();
$this->setUTFEncoder('iconv');
}
function setOutputEncoding($Encoding){
$this->_defaultEncoding = $Encoding;
}
/**
* $encoder = 'iconv' or 'mb'
* set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding
* set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding
*/
function setUTFEncoder($encoder = 'iconv'){
$this->_encoderFunction = '';
if ($encoder == 'iconv'){
$this->_encoderFunction = function_exists('iconv') ? 'iconv' : '';
}elseif ($encoder == 'mb') {
$this->_encoderFunction = function_exists('mb_convert_encoding') ? 'mb_convert_encoding' : '';
}
}
function setRowColOffset($iOffset){
$this->_rowoffset = $iOffset;
$this->_coloffset = $iOffset;
}
function setDefaultFormat($sFormat){
$this->_defaultFormat = $sFormat;
}
function setColumnFormat($column, $sFormat){
$this->_columnsFormat[$column] = $sFormat;
}
function read($sFileName) {
$errlevel = error_reporting();
//error_reporting($errlevel ^ E_NOTICE);
$res = $this->_ole->read($sFileName);
// oops, something goes wrong (Darko Miljanovic)
if($res === false) {
// check error code
if($this->_ole->error == 1) {
// bad file
die('The filename ' . $sFileName . ' is not readable');
}
// check other error codes here (eg bad fileformat, etc...)
}
$this->data = $this->_ole->getWorkBook();
/*
$res = $this->_ole->read($sFileName);
if ($this->isError($res)) {
// var_dump($res);
return $this->raiseError($res);
}
$total = $this->_ole->ppsTotal();
for ($i = 0; $i < $total; $i++) {
if ($this->_ole->isFile($i)) {
$type = unpack("v", $this->_ole->getData($i, 0, 2));
if ($type[''] == 0x0809) { // check if it's a BIFF stream
$this->_index = $i;
$this->data = $this->_ole->getData($i, 0, $this->_ole->getDataLength($i));
break;
}
}
}
if ($this->_index === null) {
return $this->raiseError("$file doesn't seem to be an Excel file");
}
*/
//var_dump($this->data);
//echo "data =".$this->data;
$this->pos = 0;
//$this->readRecords();
$this->_parse();
error_reporting($errlevel);
}
function _parse(){
$pos = 0;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
$version = ord($this->data[$pos + 4]) | ord($this->data[$pos + 5])<<8;
$substreamType = ord($this->data[$pos + 6]) | ord($this->data[$pos + 7])<<8;
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
if (($version != Spreadsheet_Excel_Reader_BIFF8) && ($version != Spreadsheet_Excel_Reader_BIFF7)) {
return false;
}
if ($substreamType != Spreadsheet_Excel_Reader_WorkbookGlobals){
return false;
}
//print_r($rec);
$pos += $length + 4;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
while ($code != Spreadsheet_Excel_Reader_Type_EOF){
switch ($code) {
case Spreadsheet_Excel_Reader_Type_SST:
//echo "Type_SST\n";
$spos = $pos + 4;
$limitpos = $spos + $length;
$uniqueStrings = $this->_GetInt4d($this->data, $spos+4);
$spos += 8;
for ($i = 0; $i < $uniqueStrings; $i++) {
// Read in the number of characters
if ($spos == $limitpos) {
$opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ($opcode != 0x3c) {
return -1;
}
$spos += 4;
$limitpos = $spos + $conlength;
}
$numChars = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8);
//echo "i = $i pos = $pos numChars = $numChars ";
$spos += 2;
$optionFlags = ord($this->data[$spos]);
$spos++;
$asciiEncoding = (($optionFlags & 0x01) == 0) ;
$extendedString = ( ($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = ( ($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8);
$spos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d($this->data, $spos);
$spos += 4;
}
$len = ($asciiEncoding)? $numChars : $numChars*2;
if ($spos + $len < $limitpos) {
$retstr = substr($this->data, $spos, $len);
$spos += $len;
}else{
// found countinue
$retstr = substr($this->data, $spos, $limitpos - $spos);
$bytesRead = $limitpos - $spos;
$charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2));
$spos = $limitpos;
while ($charsLeft > 0){
$opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ($opcode != 0x3c) {
return -1;
}
$spos += 4;
$limitpos = $spos + $conlength;
$option = ord($this->data[$spos]);
$spos += 1;
if ($asciiEncoding && ($option == 0)) {
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len;
$asciiEncoding = true;
}elseif (!$asciiEncoding && ($option != 0)){
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len/2;
$asciiEncoding = false;
}elseif (!$asciiEncoding && ($option == 0)) {
// Bummer - the string starts off as Unicode, but after the
// continuation it is in straightforward ASCII encoding
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
for ($j = 0; $j < $len; $j++) {
$retstr .= $this->data[$spos + $j].chr(0);
}
$charsLeft -= $len;
$asciiEncoding = false;
}else{
$newstr = '';
for ($j = 0; $j < strlen($retstr); $j++) {
$newstr = $retstr[$j].chr(0);
}
$retstr = $newstr;
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len/2;
$asciiEncoding = false;
//echo "Izavrat\n";
}
$spos += $len;
}
}
$retstr = ($asciiEncoding) ? $retstr : $this->_encodeUTF16($retstr);
// echo "Str $i = $retstr\n";
if ($richString){
$spos += 4 * $formattingRuns;
}
// For extended strings, skip over the extended string data
if ($extendedString) {
$spos += $extendedRunLength;
}
//if ($retstr == 'Derby'){
// echo "bb\n";
//}
$this->sst[]=$retstr;
}
/*$continueRecords = array();
while ($this->getNextCode() == Type_CONTINUE) {
$continueRecords[] = &$this->nextRecord();
}
//echo " 1 Type_SST\n";
$this->shareStrings = new SSTRecord($r, $continueRecords);
//print_r($this->shareStrings->strings);
*/
// echo 'SST read: '.($time_end-$time_start)."\n";
break;
case Spreadsheet_Excel_Reader_Type_FILEPASS:
return false;
break;
case Spreadsheet_Excel_Reader_Type_NAME:
//echo "Type_NAME\n";
break;
case Spreadsheet_Excel_Reader_Type_FORMAT:
$indexCode = ord($this->data[$pos+4]) | ord($this->data[$pos+5]) << 8;
if ($version == Spreadsheet_Excel_Reader_BIFF8) {
$numchars = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8;
if (ord($this->data[$pos+8]) == 0){
$formatString = substr($this->data, $pos+9, $numchars);
} else {
$formatString = substr($this->data, $pos+9, $numchars*2);
}
} else {
$numchars = ord($this->data[$pos+6]);
$formatString = substr($this->data, $pos+7, $numchars*2);
}
$this->formatRecords[$indexCode] = $formatString;
// echo "Type.FORMAT\n";
break;
case Spreadsheet_Excel_Reader_Type_XF:
//global $dateFormats, $numberFormats;
$indexCode = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8;
//echo "\nType.XF ".count($this->formatRecords['xfrecords'])." $indexCode ";
if (array_key_exists($indexCode, $this->dateFormats)) {
//echo "isdate ".$dateFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $this->dateFormats[$indexCode]
);
}elseif (array_key_exists($indexCode, $this->numberFormats)) {
//echo "isnumber ".$this->numberFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'number',
'format' => $this->numberFormats[$indexCode]
);
}else{
$isdate = FALSE;
if ($indexCode > 0){
if (isset($this->formatRecords[$indexCode]))
$formatstr = $this->formatRecords[$indexCode];
//echo '.other.';
//echo "\ndate-time=$formatstr=\n";
if ($formatstr)
if (preg_match("/[^hmsday\/\-:\s]/i", $formatstr) == 0) { // found day and time format
$isdate = TRUE;
$formatstr = str_replace('mm', 'i', $formatstr);
$formatstr = str_replace('h', 'H', $formatstr);
//echo "\ndate-time $formatstr \n";
}
}
if ($isdate){
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $formatstr,
);
}else{
$this->formatRecords['xfrecords'][] = array(
'type' => 'other',
'format' => '',
'code' => $indexCode
);
}
}
//echo "\n";
break;
case Spreadsheet_Excel_Reader_Type_NINETEENFOUR:
//echo "Type.NINETEENFOUR\n";
$this->nineteenFour = (ord($this->data[$pos+4]) == 1);
break;
case Spreadsheet_Excel_Reader_Type_BOUNDSHEET:
//echo "Type.BOUNDSHEET\n";
$rec_offset = $this->_GetInt4d($this->data, $pos+4);
$rec_typeFlag = ord($this->data[$pos+8]);
$rec_visibilityFlag = ord($this->data[$pos+9]);
$rec_length = ord($this->data[$pos+10]);
if ($version == Spreadsheet_Excel_Reader_BIFF8){
$chartype = ord($this->data[$pos+11]);
if ($chartype == 0){
$rec_name = substr($this->data, $pos+12, $rec_length);
} else {
$rec_name = $this->_encodeUTF16(substr($this->data, $pos+12, $rec_length*2));
}
}elseif ($version == Spreadsheet_Excel_Reader_BIFF7){
$rec_name = substr($this->data, $pos+11, $rec_length);
}
$this->boundsheets[] = array('name'=>$rec_name,
'offset'=>$rec_offset);
break;
}
//echo "Code = ".base_convert($r['code'],10,16)."\n";
$pos += $length + 4;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
//$r = &$this->nextRecord();
//echo "1 Code = ".base_convert($r['code'],10,16)."\n";
}
foreach ($this->boundsheets as $key=>$val){
$this->sn = $key;
$this->_parsesheet($val['offset']);
}
return true;
}
function _parsesheet($spos){
$cont = true;
// read BOF
$code = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$version = ord($this->data[$spos + 4]) | ord($this->data[$spos + 5])<<8;
$substreamType = ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8;
if (($version != Spreadsheet_Excel_Reader_BIFF8) && ($version != Spreadsheet_Excel_Reader_BIFF7)) {
return -1;
}
if ($substreamType != Spreadsheet_Excel_Reader_Worksheet){
return -2;
}
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
$spos += $length + 4;
//var_dump($this->formatRecords);
//echo "code $code $length";
while($cont) {
//echo "mem= ".memory_get_usage()."\n";
// $r = &$this->file->nextRecord();
$lowcode = ord($this->data[$spos]);
if ($lowcode == Spreadsheet_Excel_Reader_Type_EOF) break;
$code = $lowcode | ord($this->data[$spos+1])<<8;
$length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$spos += 4;
$this->sheets[$this->sn]['maxrow'] = $this->_rowoffset - 1;
$this->sheets[$this->sn]['maxcol'] = $this->_coloffset - 1;
//echo "Code=".base_convert($code,10,16)." $code\n";
unset($this->rectype);
$this->multiplier = 1; // need for format with %
switch ($code) {
case Spreadsheet_Excel_Reader_Type_DIMENSION:
//echo 'Type_DIMENSION ';
if (!isset($this->numRows)) {
if (($length == 10) || ($version == Spreadsheet_Excel_Reader_BIFF7)){
$this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+2]) | ord($this->data[$spos+3]) << 8;
$this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+6]) | ord($this->data[$spos+7]) << 8;
} else {
$this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8;
$this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+10]) | ord($this->data[$spos+11]) << 8;
}
}
//echo 'numRows '.$this->numRows.' '.$this->numCols."\n";
break;
case Spreadsheet_Excel_Reader_Type_MERGEDCELLS:
$cellRanges = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
for ($i = 0; $i < $cellRanges; $i++) {
$fr = ord($this->data[$spos + 8*$i + 2]) | ord($this->data[$spos + 8*$i + 3])<<8;
$lr = ord($this->data[$spos + 8*$i + 4]) | ord($this->data[$spos + 8*$i + 5])<<8;
$fc = ord($this->data[$spos + 8*$i + 6]) | ord($this->data[$spos + 8*$i + 7])<<8;
$lc = ord($this->data[$spos + 8*$i + 8]) | ord($this->data[$spos + 8*$i + 9])<<8;
//$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1);
if ($lr - $fr > 0) {
$this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['rowspan'] = $lr - $fr + 1;
}
if ($lc - $fc > 0) {
$this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['colspan'] = $lc - $fc + 1;
}
}
//echo "Merged Cells $cellRanges $lr $fr $lc $fc\n";
break;
case Spreadsheet_Excel_Reader_Type_RK:
case Spreadsheet_Excel_Reader_Type_RK2:
//echo 'Spreadsheet_Excel_Reader_Type_RK'."\n";
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$rknum = $this->_GetInt4d($this->data, $spos + 6);
$numValue = $this->_GetIEEE754($rknum);
//echo $numValue." ";
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($numValue);
}else{
$raw = $numValue;
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$string = sprintf($this->curformat, $numValue * $this->multiplier);
//$this->addcell(RKRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Type_RK $row $column $string $raw {$this->curformat}\n";
break;
case Spreadsheet_Excel_Reader_Type_LABELSST:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5])<<8;
$index = $this->_GetInt4d($this->data, $spos + 6);
//var_dump($this->sst);
$this->addcell($row, $column, $this->sst[$index]);
//echo "LabelSST $row $column $string\n";
break;
case Spreadsheet_Excel_Reader_Type_MULRK:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$colFirst = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$colLast = ord($this->data[$spos + $length - 2]) | ord($this->data[$spos + $length - 1])<<8;
$columns = $colLast - $colFirst + 1;
$tmppos = $spos+4;
for ($i = 0; $i < $columns; $i++) {
$numValue = $this->_GetIEEE754($this->_GetInt4d($this->data, $tmppos + 2));
if ($this->isDate($tmppos-4)) {
list($string, $raw) = $this->createDate($numValue);
}else{
$raw = $numValue;
if (isset($this->_columnsFormat[$colFirst + $i + 1])){
$this->curformat = $this->_columnsFormat[$colFirst + $i + 1];
}
$string = sprintf($this->curformat, $numValue * $this->multiplier);
}
//$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8;
$tmppos += 6;
$this->addcell($row, $colFirst + $i, $string, $raw);
//echo "MULRK $row ".($colFirst + $i)." $string\n";
}
//MulRKRecord($r);
// Get the individual cell records from the multiple record
//$num = ;
break;
case Spreadsheet_Excel_Reader_Type_NUMBER:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($tmp['double']);
// $this->addcell(DateRecord($r, 1));
}else{
//$raw = $tmp[''];
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$raw = $this->createNumber($spos);
$string = sprintf($this->curformat, $raw * $this->multiplier);
// $this->addcell(NumberRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Number $row $column $string\n";
break;
case Spreadsheet_Excel_Reader_Type_FORMULA:
case Spreadsheet_Excel_Reader_Type_FORMULA2:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ((ord($this->data[$spos+6])==0) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//String formula. Result follows in a STRING record
//echo "FORMULA $row $column Formula with a string<br>\n";
} elseif ((ord($this->data[$spos+6])==1) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Boolean formula. Result is in +2; 0=false,1=true
} elseif ((ord($this->data[$spos+6])==2) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Error formula. Error code is in +2;
} elseif ((ord($this->data[$spos+6])==3) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Formula result is a null string.
} else {
// result is a number, so first 14 bytes are just like a _NUMBER record
$tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($tmp['double']);
// $this->addcell(DateRecord($r, 1));
}else{
//$raw = $tmp[''];
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$raw = $this->createNumber($spos);
$string = sprintf($this->curformat, $raw * $this->multiplier);
// $this->addcell(NumberRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Number $row $column $string\n";
}
break;
case Spreadsheet_Excel_Reader_Type_BOOLERR:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$string = ord($this->data[$spos+6]);
$this->addcell($row, $column, $string);
//echo 'Type_BOOLERR '."\n";
break;
case Spreadsheet_Excel_Reader_Type_ROW:
case Spreadsheet_Excel_Reader_Type_DBCELL:
case Spreadsheet_Excel_Reader_Type_MULBLANK:
break;
case Spreadsheet_Excel_Reader_Type_LABEL:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$this->addcell($row, $column, substr($this->data, $spos + 8, ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8));
// $this->addcell(LabelRecord($r));
break;
case Spreadsheet_Excel_Reader_Type_EOF:
$cont = false;
break;
default:
//echo ' unknown :'.base_convert($r['code'],10,16)."\n";
break;
}
$spos += $length;
}
if (!isset($this->sheets[$this->sn]['numRows']))
$this->sheets[$this->sn]['numRows'] = $this->sheets[$this->sn]['maxrow'];
if (!isset($this->sheets[$this->sn]['numCols']))
$this->sheets[$this->sn]['numCols'] = $this->sheets[$this->sn]['maxcol'];
}
function isDate($spos){
//$xfindex = GetInt2d(, 4);
$xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8;
//echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']."\n";
//var_dump($this->formatRecords['xfrecords'][$xfindex]);
if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'date') {
$this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format'];
$this->rectype = 'date';
return true;
} else {
if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'number') {
$this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format'];
$this->rectype = 'number';
if (($xfindex == 0x9) || ($xfindex == 0xa)){
$this->multiplier = 100;
}
}else{
$this->curformat = $this->_defaultFormat;
$this->rectype = 'unknown';
}
return false;
}
}
function createDate($numValue){
if ($numValue > 1){
$utcDays = $numValue - ($this->nineteenFour ? Spreadsheet_Excel_Reader_utcOffsetDays1904 : Spreadsheet_Excel_Reader_utcOffsetDays);
$utcValue = round($utcDays * Spreadsheet_Excel_Reader_msInADay);
$string = date ($this->curformat, $utcValue);
$raw = $utcValue;
}else{
$raw = $numValue;
$hours = floor($numValue * 24);
$mins = floor($numValue * 24 * 60) - $hours * 60;
$secs = floor($numValue * Spreadsheet_Excel_Reader_msInADay) - $hours * 60 * 60 - $mins * 60;
$string = date ($this->curformat, mktime($hours, $mins, $secs));
}
return array($string, $raw);
}
function createNumber($spos){
$rknumhigh = $this->_GetInt4d($this->data, $spos + 10);
$rknumlow = $this->_GetInt4d($this->data, $spos + 6);
//for ($i=0; $i<8; $i++) { echo ord($this->data[$i+$spos+6]) . " "; } echo "<br>";
$sign = ($rknumhigh & 0x80000000) >> 31;
$exp = ($rknumhigh & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
$mantissalow1 = ($rknumlow & 0x80000000) >> 31;
$mantissalow2 = ($rknumlow & 0x7fffffff);
$value = $mantissa / pow( 2 , (20- ($exp - 1023)));
if ($mantissalow1 != 0) $value += 1 / pow (2 , (21 - ($exp - 1023)));
$value += $mantissalow2 / pow (2 , (52 - ($exp - 1023)));
//echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2<br>\n";
if ($sign) {$value = -1 * $value;}
return $value;
}
function addcell($row, $col, $string, $raw = ''){
//echo "ADD cel $row-$col $string\n";
$this->sheets[$this->sn]['maxrow'] = max($this->sheets[$this->sn]['maxrow'], $row + $this->_rowoffset);
$this->sheets[$this->sn]['maxcol'] = max($this->sheets[$this->sn]['maxcol'], $col + $this->_coloffset);
$this->sheets[$this->sn]['cells'][$row + $this->_rowoffset][$col + $this->_coloffset] = $string;
if ($raw)
$this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['raw'] = $raw;
if (isset($this->rectype))
$this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['type'] = $this->rectype;
}
function _GetIEEE754($rknum){
if (($rknum & 0x02) != 0) {
$value = $rknum >> 2;
} else {
//mmp
// first comment out the previously existing 7 lines of code here
// $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc)));
// //$value = $tmp[''];
// if (array_key_exists(1, $tmp)) {
// $value = $tmp[1];
// } else {
// $value = $tmp[''];
// }
// I got my info on IEEE754 encoding from
// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
// The RK format calls for using only the most significant 30 bits of the
// 64 bit floating point value. The other 34 bits are assumed to be 0
// So, we use the upper 30 bits of $rknum as follows...
$sign = ($rknum & 0x80000000) >> 31;
$exp = ($rknum & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknum & 0x000ffffc));
$value = $mantissa / pow( 2 , (20- ($exp - 1023)));
if ($sign) {$value = -1 * $value;}
//end of changes by mmp
}
if (($rknum & 0x01) != 0) {
$value /= 100;
}
return $value;
}
function _encodeUTF16($string){
$result = $string;
if ($this->_defaultEncoding){
switch ($this->_encoderFunction){
case 'iconv' : $result = iconv('UTF-16LE', $this->_defaultEncoding, $string);
break;
case 'mb_convert_encoding' : $result = mb_convert_encoding($string, $this->_defaultEncoding, 'UTF-16LE' );
break;
}
}
return $result;
}
function _GetInt4d($data, $pos) {
$value = ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24);
if ($value>=4294967294) {
$value=-2;
}
if ($value >= 4000000000 && $value < 4294967294) // Add these lines
{
$value = -2 - 4294967294 + $value;
} // End add lines
return $value;
}
}
?>
| Java |
<?php
/** ---------------------------------------------------------------------
* app/helpers/htmlFormHelpers.php : miscellaneous functions
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2008-2019 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* @package CollectiveAccess
* @subpackage utils
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*
* ----------------------------------------------------------------------
*/
/**
*
*/
# ------------------------------------------------------------------------------------------------
/**
* Creates an HTML <select> form element
*
* @param string $ps_name Name of the element
* @param array $pa_content Associative array with keys as display options and values as option values. If the 'contentArrayUsesKeysForValues' is set then keys use interpreted as option values and values as display options.
* @param array $pa_attributes Optional associative array of <select> tag options; keys are attribute names and values are attribute values
* @param array $pa_options Optional associative array of options. Valid options are:
* value = the default value of the element
* values = an array of values for the element, when the <select> allows multiple selections
* disabledOptions = an associative array indicating whether options are disabled or not; keys are option *values*, values are boolean (true=disabled; false=enabled)
* contentArrayUsesKeysForValues = normally the keys of the $pa_content array are used as display options and the values as option values. Setting 'contentArrayUsesKeysForValues' to true will reverse the interpretation, using keys as option values.
* useOptionsForValues = set values to be the same as option text. [Default is false]
* width = width of select in characters or pixels. If specifying pixels use "px" as the units (eg. 100px)
* colors =
* @return string HTML code representing the drop-down list
*/
function caHTMLSelect($ps_name, $pa_content, $pa_attributes=null, $pa_options=null) {
if (!is_array($pa_content)) { $pa_content = array(); }
if (is_array($va_dim = caParseFormElementDimension(isset($pa_options['width']) ? $pa_options['width'] : null))) {
if ($va_dim['type'] == 'pixels') {
$pa_attributes['style'] = "width: ".$va_dim['dimension']."px; ".$pa_attributes['style'];
} else {
// Approximate character width using 1 character = 6 pixels of width
$pa_attributes['style'] = "width: ".($va_dim['dimension'] * 6)."px; ".$pa_attributes['style'];
}
}
if (is_array($va_dim = caParseFormElementDimension(isset($pa_options['height']) ? $pa_options['height'] : null))) {
if ($va_dim['type'] == 'pixels') {
$pa_attributes['style'] = "height: ".$va_dim['dimension']."px; ".$pa_attributes['style'];
} else {
// Approximate character width using 1 character = 6 pixels of width
$pa_attributes['size'] = $va_dim['dimension'];
}
}
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<select name='{$ps_name}' {$vs_attr_string}>\n";
$vs_selected_val = isset($pa_options['value']) ? $pa_options['value'] : null;
if (is_array($pa_options['values']) && $vs_selected_val) { $vs_selected_val = null; }
$va_selected_vals = isset($pa_options['values']) ? $pa_options['values'] : array();
$va_disabled_options = isset($pa_options['disabledOptions']) ? $pa_options['disabledOptions'] : array();
$vb_content_is_list = caIsIndexedArray($pa_content);
$va_colors = array();
if (isset($pa_options['colors']) && is_array($pa_options['colors'])) {
$va_colors = $pa_options['colors'];
}
$vb_use_options_for_values = caGetOption('useOptionsForValues', $pa_options, false);
$vb_uses_color = false;
if (isset($pa_options['contentArrayUsesKeysForValues']) && $pa_options['contentArrayUsesKeysForValues']) {
foreach($pa_content as $vs_val => $vs_opt) {
if ($vb_use_options_for_values) { $vs_val = preg_replace("!^[\s]+!", "", preg_replace("![\s]+$!", "", str_replace(" ", "", $vs_opt))); }
if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; }
if (is_null($vs_selected_val) || !($SELECTED = (((string)$vs_selected_val === (string)$vs_val) && strlen($vs_selected_val)) ? ' selected="1"' : '')) {
$SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : '';
}
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_opt."</option>\n";
}
} else {
if ($vb_content_is_list) {
foreach($pa_content as $vs_val) {
if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; }
if (is_null($vs_selected_val) || !($SELECTED = ((string)$vs_selected_val === (string)$vs_val) ? ' selected="1"' : '')) {
$SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : '';
}
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_val."</option>\n";
}
} else {
foreach($pa_content as $vs_opt => $vs_val) {
if ($vb_use_options_for_values) { $vs_val = preg_replace("!^[\s]+!", "", preg_replace("![\s]+$!", "", str_replace(" ", "", $vs_opt))); }
if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; }
if (is_null($vs_selected_val) || !($SELECTED = ((string)$vs_selected_val === (string)$vs_val) ? ' selected="1"' : '')) {
$SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : '';
}
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_opt."</option>\n";
}
}
}
$vs_element .= "</select>\n";
if ($vb_uses_color && isset($pa_attributes['id']) && $pa_attributes['id']) {
$vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { var f; jQuery('#".$pa_attributes['id']."').on('change', f=function() { var c = jQuery('#".$pa_attributes['id']."').find('option:selected').data('color'); jQuery('#".$pa_attributes['id']."').css('background-color', c ? c : '#fff'); return false;}); f(); });</script>";
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Render an HTML text form element (<input type="text"> or <textarea> depending upon height).
*
* @param string $ps_name The name of the rendered form element
* @param array $pa_attributes An array of attributes to include in the rendered HTML form element. If you need to set class, id, alt or other attributes, set them here.
* @param array Options include:
* width = Width of element in pixels (number with "px" suffix) or characters (number with no suffix) [Default is null]
* height = Height of element in pixels (number with "px" suffix) or characters (number with no suffix) [Default is null]
* usewysiwygeditor = Use rich text editor (CKEditor) for text element. Only available when the height of the text element is multi-line. [Default is false]
* cktoolbar = app.conf directive name to pull CKEditor toolbar spec from. [Default is wysiwyg_editor_toolbar]
* contentUrl = URL to use to load content when CKEditor is use with CA-specific plugins. [Default is null]
* textAreaTagName =
* @return string
*/
function caHTMLTextInput($ps_name, $pa_attributes=null, $pa_options=null) {
$vb_is_textarea = false;
$va_styles = array();
$vb_use_wysiwyg_editor = caGetOption('usewysiwygeditor', $pa_options, false);
$vn_width = $vn_height = null;
if (is_array($va_dim = caParseFormElementDimension(
(isset($pa_options['width']) ? $pa_options['width'] :
(isset($pa_attributes['size']) ? $pa_attributes['size'] :
(isset($pa_attributes['width']) ? $pa_attributes['width'] : null)
)
)
))) {
if ($va_dim['type'] == 'pixels') {
$va_styles[] = "width: ".($vn_width = $va_dim['dimension'])."px;";
unset($pa_attributes['width']);
unset($pa_attributes['size']);
unset($pa_attributes['cols']);
} else {
// width is in characters
$pa_attributes['size'] = $va_dim['dimension'];
$vn_width = $va_dim['dimension'] * 6;
}
}
if (!$vn_width) $vn_width = 300;
if (is_array($va_dim = caParseFormElementDimension(
(isset($pa_options['height']) ? $pa_options['height'] :
(isset($pa_attributes['height']) ? $pa_attributes['height'] : null)
)
))) {
if ($va_dim['type'] == 'pixels') {
$va_styles[] = "height: ".($vn_height = $va_dim['dimension'])."px;";
unset($pa_attributes['height']);
unset($pa_attributes['rows']);
$vb_is_textarea = true;
} else {
// height is in characters
if (($pa_attributes['rows'] = $va_dim['dimension']) > 1) {
$vb_is_textarea = true;
}
$vn_height = $va_dim['dimension'] * 12;
}
} else {
if (($pa_attributes['rows'] = (isset($pa_attributes['height']) && $pa_attributes['height']) ? $pa_attributes['height'] : 1) > 1) {
$vb_is_textarea = true;
}
}
if (!$vn_height) $vn_height = 300;
$pa_attributes['style'] = join(" ", $va_styles);
// WYSIWYG editor requires an DOM ID so generate one if none is explicitly set
if ($vb_use_wysiwyg_editor && !isset($pa_attributes['id'])) {
$pa_attributes['id'] = "{$ps_name}_element";
}
if ($vb_is_textarea) {
$tag_name = caGetOption('textAreaTagName', $pa_options, 'textarea');
$vs_value = $pa_attributes['value'];
if ($pa_attributes['size']) { $pa_attributes['cols'] = $pa_attributes['size']; }
unset($pa_attributes['size']);
unset($pa_attributes['value']);
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<{$tag_name} name='{$ps_name}' wrap='soft' {$vs_attr_string}>".$vs_value."</{$tag_name}>\n";
} else {
$pa_attributes['size'] = !$pa_attributes['size'] ? $pa_attributes['width'] : $pa_attributes['size'];
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='text'/>\n";
}
if ($vb_use_wysiwyg_editor) {
AssetLoadManager::register("ckeditor");
$o_config = Configuration::load();
if(!is_array($va_toolbar_config = $o_config->getAssoc(caGetOption('cktoolbar', $pa_options, 'wysiwyg_editor_toolbar')))) { $va_toolbar_config = []; }
$vs_content_url = caGetOption('contentUrl', $pa_options, '');
$va_lookup_urls = caGetOption('lookupUrls', $pa_options, null);
$vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() {
var ckEditor = CKEDITOR.replace( '".$pa_attributes['id']."',
{
toolbar : ".json_encode(array_values($va_toolbar_config)).",
width: '{$vn_width}px',
height: '{$vn_height}px',
toolbarLocation: 'top',
enterMode: CKEDITOR.ENTER_BR,
contentUrl: '{$vs_content_url}',
lookupUrls: ".json_encode($va_lookup_urls)."
});
ckEditor.on('instanceReady', function(){
ckEditor.document.on( 'keydown', function(e) {if (caUI && caUI.utils) { caUI.utils.showUnsavedChangesWarning(true); } });
});
});
</script>";
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
function caHTMLHiddenInput($ps_name, $pa_attributes=null, $pa_options=null) {
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='hidden'/>\n";
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Creates set of radio buttons
*
* $ps_name - name of the element
* $pa_content - associative array with keys as display options and values as option values
* $pa_attributes - optional associative array of <input> tag options applied to each radio button; keys are attribute names and values are attribute values
* $pa_options - optional associative array of options. Valid options are:
* value = the default value of the element
* disabledOptions = an associative array indicating whether options are disabled or not; keys are option *values*, values are boolean (true=disabled; false=enabled)
*/
function caHTMLRadioButtonsInput($ps_name, $pa_content, $pa_attributes=null, $pa_options=null) {
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_selected_val = isset($pa_options['value']) ? $pa_options['value'] : null;
$va_disabled_options = isset($pa_options['disabledOptions']) ? $pa_options['disabledOptions'] : array();
$vb_content_is_list = (array_key_exists(0, $pa_content)) ? true : false;
$vs_id = isset($pa_attributes['id']) ? $pa_attributes['id'] : null;
unset($pa_attributes['id']);
$vn_i = 0;
if ($vb_content_is_list) {
foreach($pa_content as $vs_val) {
$vs_id_attr = ($vs_id) ? 'id="'.$vs_id.'_'.$vn_i.'"' : '';
$SELECTED = ($vs_selected_val == $vs_val) ? ' selected="1"' : '';
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<input type='radio' name='{$ps_name}' {$vs_id_attr} value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}> ".$vs_val."\n";
$vn_i++;
}
} else {
foreach($pa_content as $vs_opt => $vs_val) {
$vs_id_attr = ($vs_id) ? 'id="'.$vs_id.'_'.$vn_i.'"' : '';
$SELECTED = ($vs_selected_val == $vs_val) ? ' selected="1"' : '';
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<input type='radio' name='{$ps_name}' {$vs_id_attr} value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}> ".$vs_opt."\n";
$vn_i++;
}
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Create a single radio button
*
* $ps_name - name of the element
* $pa_attributes - optional associative array of <input> tag options applied to the radio button; keys are attribute names and values are attribute values
* $pa_options - optional associative array of options. Valid options are:
* checked = if true, value will be selected by default
* disabled = boolean indicating if radio button is enabled or not (true=disabled; false=enabled)
*/
function caHTMLRadioButtonInput($ps_name, $pa_attributes=null, $pa_options=null) {
if(caGetOption('checked', $pa_options, false)) { $pa_attributes['checked'] = 1; }
if(caGetOption('disabled', $pa_options, false)) { $pa_attributes['disabled'] = 1; }
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes);
// standard check box
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='radio'/>\n";
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Creates a checkbox
*
* $ps_name - name of the element
* $pa_attributes - optional associative array of <input> tag options applied to the checkbox; keys are attribute names and values are attribute values
* $pa_options - optional associative array of options. Valid options are:
* value = the default value of the element
* disabled = boolean indicating if checkbox is enabled or not (true=disabled; false=enabled)
* returnValueIfUnchecked = boolean indicating if checkbox should return value in request if unchecked; default is false
*/
function caHTMLCheckboxInput($ps_name, $pa_attributes=null, $pa_options=null) {
if (array_key_exists('checked', $pa_attributes) && !$pa_attributes['checked']) { unset($pa_attributes['checked']); }
if (array_key_exists('CHECKED', $pa_attributes) && !$pa_attributes['CHECKED']) { unset($pa_attributes['CHECKED']); }
if(caGetOption('disabled', $pa_options, false)) { $pa_attributes['disabled'] = 1; }
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
if (isset($pa_options['returnValueIfUnchecked']) && $pa_options['returnValueIfUnchecked']) {
// javascript-y check box that returns form value even if unchecked
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='checkbox'/>\n";
unset($pa_attributes['id']);
$pa_attributes['value'] = $pa_options['returnValueIfUnchecked'];
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='hidden'/>\n". $vs_element;
} else {
// standard check box
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='checkbox'/>\n";
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
function caHTMLLink($ps_content, $pa_attributes=null, $pa_options=null) {
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<a {$vs_attr_string}>{$ps_content}</a>";
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Generates an HTML <img> or Tilepic embed tag with supplied URL and attributes
*
* @param $ps_url string The image URL
* @param $pa_options array Options include:
* scaleCSSWidthTo = width in pixels to *style* via CSS the returned image to. Does not actually alter the image. Aspect ratio of the image is preserved, with the combination of scaleCSSWidthTo and scaleCSSHeightTo being taken as a bounding box for the image. Only applicable to standard <img> tags. Tilepic display size cannot be styled using CSS; use the "width" and "height" options instead.
* scaleCSSHeightTo = height in pixels to *style* via CSS the returned image to.
*
* @return string
*/
function caHTMLImage($ps_url, $pa_options=null) {
if (!is_array($pa_options)) { $pa_options = array(); }
$va_attributes = array('src' => $ps_url);
foreach(array('name', 'id',
'width', 'height',
'vspace', 'hspace', 'alt', 'title', 'usemap', 'align', 'border', 'class', 'style') as $vs_attr) {
if (isset($pa_options[$vs_attr])) { $va_attributes[$vs_attr] = $pa_options[$vs_attr]; }
}
// Allow data-* attributes
foreach($pa_options as $vs_k => $vs_v) {
if (substr($vs_k, 0, 5) == 'data-') { $va_attributes[$vs_k] = $vs_v; }
}
$vn_scale_css_width_to = caGetOption('scaleCSSWidthTo', $pa_options, null);
$vn_scale_css_height_to = caGetOption('scaleCSSHeightTo', $pa_options, null);
if ($vn_scale_css_width_to || $vn_scale_css_height_to) {
if (!$vn_scale_css_width_to) { $vn_scale_css_width_to = $vn_scale_css_height_to; }
if (!$vn_scale_css_height_to) { $vn_scale_css_height_to = $vn_scale_css_width_to; }
$va_scaled_dimensions = caFitImageDimensions($va_attributes['width'], $va_attributes['height'], $vn_scale_css_width_to, $vn_scale_css_height_to);
$va_attributes['width'] = $va_scaled_dimensions['width'].'px';
$va_attributes['height'] = $va_scaled_dimensions['height'].'px';
}
$vs_attr_string = _caHTMLMakeAttributeString($va_attributes, $pa_options);
if(preg_match("/\.tpc\$/", $ps_url)) {
#
# Tilepic
#
$vn_width = (int)$pa_options["width"];
$vn_height = (int)$pa_options["height"];
$vn_tile_width = caGetOption('tile_width', $pa_options, 256, array('castTo'=>'int'));
$vn_tile_height = caGetOption('tile_height', $pa_options, 256, array('castTo'=>'int'));
// Tiles must be square.
if ($vn_tile_width != $vn_tile_height){
$vn_tile_height = $vn_tile_width;
}
$vn_layers = (int)$pa_options["layers"];
if (!($vs_id_name = (string)$pa_options["idname"])) {
$vs_id_name = (string)$pa_options["id"];
}
$vn_viewer_width = $pa_options["viewer_width"];
$vn_viewer_height = $pa_options["viewer_height"];
$vs_annotation_load_url = caGetOption("annotation_load_url", $pa_options, null);
$vs_annotation_save_url = caGetOption("annotation_save_url", $pa_options, null);
$vs_help_load_url = caGetOption("help_load_url", $pa_options, null);
$vb_read_only = caGetOption("read_only", $pa_options, null);
$vs_annotation_editor_panel = caGetOption("annotationEditorPanel", $pa_options, null);
$vs_annotation_editor_url = caGetOption("annotationEditorUrl", $pa_options, null);
$vs_viewer_base_url = caGetOption("viewer_base_url", $pa_options, __CA_URL_ROOT__);
$o_config = Configuration::load();
if (!$vn_viewer_width || !$vn_viewer_height) {
$vn_viewer_width = (int)$o_config->get("tilepic_viewer_width");
if (!$vn_viewer_width) { $vn_viewer_width = 500; }
$vn_viewer_height = (int)$o_config->get("tilepic_viewer_height");
if (!$vn_viewer_height) { $vn_viewer_height = 500; }
}
$vs_error_tag = caGetOption("alt_image_tag", $pa_options, '');
$vn_viewer_width_with_units = $vn_viewer_width;
$vn_viewer_height_with_units = $vn_viewer_height;
if (preg_match('!^[\d]+$!', $vn_viewer_width)) { $vn_viewer_width_with_units .= 'px'; }
if (preg_match('!^[\d]+$!', $vn_viewer_height)) { $vn_viewer_height_with_units .= 'px'; }
if(!is_array($va_viewer_opts_from_app_config = $o_config->getAssoc('image_viewer_options'))) { $va_viewer_opts_from_app_config = array(); }
$va_opts = array_merge(array(
'id' => "{$vs_id_name}_viewer",
'src' => "{$vs_viewer_base_url}/viewers/apps/tilepic.php?p={$ps_url}&t=",
'annotationLoadUrl' => $vs_annotation_load_url,
'annotationSaveUrl' => $vs_annotation_save_url,
'annotationEditorPanel' => $vs_annotation_editor_panel,
'annotationEditorUrl' => $vs_annotation_editor_url,
'annotationEditorLink' => _t('More...'),
'helpLoadUrl' => $vs_help_load_url,
'lockAnnotations' => ($vb_read_only ? true : false),
'showAnnotationTools' => ($vb_read_only ? false : true)
), $va_viewer_opts_from_app_config);
$va_opts['info'] = array(
'width' => $vn_width,
'height' => $vn_height,
// Set tile size using function options.
'tilesize'=> $vn_tile_width,
'levels' => $vn_layers
);
$vs_tag = "
<div id='{$vs_id_name}' style='width:{$vn_viewer_width_with_units}; height: {$vn_viewer_height_with_units}; position: relative; z-index: 0;'>
{$vs_error_tag}
</div>
<script type='text/javascript'>
var elem = document.createElement('canvas');
if (elem.getContext && elem.getContext('2d')) {
jQuery(document).ready(function() {
jQuery('#{$vs_id_name}').tileviewer(".json_encode($va_opts).");
});
}
</script>\n";
return $vs_tag;
} else {
#
# Standard image
#
if (!isset($pa_options["width"])) $pa_options["width"] = 100;
if (!isset($pa_options["height"])) $pa_options["height"] = 100;
if (($ps_url) && ($pa_options["width"] > 0) && ($pa_options["height"] > 0)) {
$vs_element = "<img {$vs_attr_string} />";
} else {
$vs_element = "";
}
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Create string for use in HTML tags out of attribute array.
*
* @param array $pa_attributes
* @param array $pa_options Optional array of options. Supported options are:
* dontConvertAttributeQuotesToEntities = if true, attribute values are not passed through htmlspecialchars(); if you set this be sure to only use single quotes in your attribute values or escape all double quotes since double quotes are used to enclose tem
*/
function _caHTMLMakeAttributeString($pa_attributes, $pa_options=null) {
$va_attr_settings = array();
if (is_array($pa_attributes)) {
foreach($pa_attributes as $vs_attr => $vs_attr_val) {
if (is_array($vs_attr_val)) { $vs_attr_val = join(" ", $vs_attr_val); }
if (is_object($vs_attr_val)) { continue; }
if (isset($pa_options['dontConvertAttributeQuotesToEntities']) && $pa_options['dontConvertAttributeQuotesToEntities']) {
$va_attr_settings[] = $vs_attr.'="'.$vs_attr_val.'"';
} else {
$va_attr_settings[] = $vs_attr.'=\''.htmlspecialchars($vs_attr_val, ENT_QUOTES, 'UTF-8').'\'';
}
}
}
return join(' ', $va_attr_settings);
}
# ------------------------------------------------------------------------------------------------
/**
* Takes an HTML form field ($ps_field), a text label ($ps_table), and DOM ID to wrap the label in ($ps_id)
* and a block of help/descriptive text ($ps_description) and returns a formatted block of HTML with
* a jQuery-based tool tip attached. Formatting is performed using the format defined in app.conf
* by the 'form_element_display_format' config directive unless overridden by a format passed in
* the optional $ps_format parameter.
*
* Note that $ps_description is also optional. If it is omitted or passed blank then no tooltip is attached
*/
function caHTMLMakeLabeledFormElement($ps_field, $ps_label, $ps_id, $ps_description='', $ps_format='', $pb_emit_tooltip=true) {
$o_config = Configuration::load();
if (!$ps_format) {
$ps_format = $o_config->get('form_element_display_format');
}
$vs_formatted_element = str_replace("^LABEL",'<span id="'.$ps_id.'">'.$ps_label.'</span>', $ps_format);
$vs_formatted_element = str_replace("^ELEMENT", $ps_field, $vs_formatted_element);
$vs_formatted_element = str_replace("^EXTRA", '', $vs_formatted_element);
if ($ps_description && $pb_emit_tooltip) {
TooltipManager::add('#'.$ps_id, "<h3>{$ps_label}</h3>{$ps_description}");
}
return $vs_formatted_element;
}
# ------------------------------------------------------------------------------------------------
| Java |
namespace MissionPlanner.GCSViews
{
partial class InitialSetup
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InitialSetup));
this.backstageView = new MissionPlanner.Controls.BackstageView.BackstageView();
this.backstageViewPagefw = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.initialSetupBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.configFirmware1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFirmware();
this.backstageViewPagefwdisabled = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFirmwareDisabled1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFirmwareDisabled();
this.backstageViewPagewizard = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configWizard1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigWizard();
this.backstageViewPagemand = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configMandatory1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMandatory();
this.backstageViewPagetradheli = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configTradHeli1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigTradHeli();
this.backstageViewPageframetype = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFrameType1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFrameType();
this.backstageViewPageaccel = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configAccelerometerCalibration = new MissionPlanner.GCSViews.ConfigurationView.ConfigAccelerometerCalibration();
this.backstageViewPagecompass = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWCompass1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWCompass();
this.backstageViewPageradio = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configRadioInput1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigRadioInput();
this.backstageViewPageESC = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configESC1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigESCCalibration();
this.backstageViewPageflmode = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFlightModes1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFlightModes();
this.backstageViewPagefs = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configFailSafe1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigFailSafe();
this.backstageViewPageopt = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configOptional1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigOptional();
this.backstageViewPageSikradio = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this._3DRradio1 = new MissionPlanner.Sikradio();
this.backstageViewPagebatmon = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configBatteryMonitoring1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigBatteryMonitoring();
this.backstageViewPageBatt2 = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configBatteryMonitoring21 = new MissionPlanner.GCSViews.ConfigurationView.ConfigBatteryMonitoring2();
this.backstageViewPagecompassmot = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configCompassMot1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigCompassMot();
this.backstageViewPagesonar = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.ConfigHWRangeFinder1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWRangeFinder();
this.backstageViewPageairspeed = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWAirspeed1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWAirspeed();
this.backstageViewPageoptflow = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWOptFlow1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWOptFlow();
this.backstageViewPageosd = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWOSD1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWOSD();
this.backstageViewPagegimbal = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configMount1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMount();
this.backstageViewPageAntTrack = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.tracker1 = new MissionPlanner.Antenna.Tracker();
this.backstageViewPageMotorTest = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configMotor1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigMotorTest();
this.backstageViewPagehwbt = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWBT1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWBT();
this.backstageViewPageParachute = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
this.configHWPa1 = new MissionPlanner.GCSViews.ConfigurationView.ConfigHWParachute();
this.backstageViewPageinstfw = new MissionPlanner.Controls.BackstageView.BackstageViewPage();
((System.ComponentModel.ISupportInitialize)(this.initialSetupBindingSource)).BeginInit();
this.SuspendLayout();
//
// backstageView
//
resources.ApplyResources(this.backstageView, "backstageView");
this.backstageView.HighlightColor1 = System.Drawing.SystemColors.Highlight;
this.backstageView.HighlightColor2 = System.Drawing.SystemColors.MenuHighlight;
this.backstageView.Name = "backstageView";
this.backstageView.Pages.Add(this.backstageViewPagefw);
this.backstageView.Pages.Add(this.backstageViewPagefwdisabled);
this.backstageView.Pages.Add(this.backstageViewPagewizard);
this.backstageView.Pages.Add(this.backstageViewPagemand);
this.backstageView.Pages.Add(this.backstageViewPagetradheli);
this.backstageView.Pages.Add(this.backstageViewPageframetype);
this.backstageView.Pages.Add(this.backstageViewPageaccel);
this.backstageView.Pages.Add(this.backstageViewPagecompass);
this.backstageView.Pages.Add(this.backstageViewPageradio);
this.backstageView.Pages.Add(this.backstageViewPageESC);
this.backstageView.Pages.Add(this.backstageViewPageflmode);
this.backstageView.Pages.Add(this.backstageViewPagefs);
this.backstageView.Pages.Add(this.backstageViewPageopt);
this.backstageView.Pages.Add(this.backstageViewPageSikradio);
this.backstageView.Pages.Add(this.backstageViewPagebatmon);
this.backstageView.Pages.Add(this.backstageViewPageBatt2);
this.backstageView.Pages.Add(this.backstageViewPagecompassmot);
this.backstageView.Pages.Add(this.backstageViewPagesonar);
this.backstageView.Pages.Add(this.backstageViewPageairspeed);
this.backstageView.Pages.Add(this.backstageViewPageoptflow);
this.backstageView.Pages.Add(this.backstageViewPageosd);
this.backstageView.Pages.Add(this.backstageViewPagegimbal);
this.backstageView.Pages.Add(this.backstageViewPageAntTrack);
this.backstageView.Pages.Add(this.backstageViewPageMotorTest);
this.backstageView.Pages.Add(this.backstageViewPagehwbt);
this.backstageView.Pages.Add(this.backstageViewPageParachute);
this.backstageView.WidthMenu = 172;
//
// backstageViewPagefw
//
this.backstageViewPagefw.Advanced = false;
this.backstageViewPagefw.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isDisConnected", true));
this.backstageViewPagefw.LinkText = "Install Firmware";
this.backstageViewPagefw.Page = this.configFirmware1;
this.backstageViewPagefw.Parent = null;
this.backstageViewPagefw.Show = true;
this.backstageViewPagefw.Spacing = 30;
resources.ApplyResources(this.backstageViewPagefw, "backstageViewPagefw");
//
// initialSetupBindingSource
//
this.initialSetupBindingSource.DataSource = typeof(MissionPlanner.GCSViews.InitialSetup);
//
// configFirmware1
//
resources.ApplyResources(this.configFirmware1, "configFirmware1");
this.configFirmware1.Name = "configFirmware1";
//
// backstageViewPagefwdisabled
//
this.backstageViewPagefwdisabled.Advanced = false;
this.backstageViewPagefwdisabled.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPagefwdisabled.LinkText = "Install Firmware";
this.backstageViewPagefwdisabled.Page = this.configFirmwareDisabled1;
this.backstageViewPagefwdisabled.Parent = null;
this.backstageViewPagefwdisabled.Show = true;
this.backstageViewPagefwdisabled.Spacing = 30;
resources.ApplyResources(this.backstageViewPagefwdisabled, "backstageViewPagefwdisabled");
//
// configFirmwareDisabled1
//
resources.ApplyResources(this.configFirmwareDisabled1, "configFirmwareDisabled1");
this.configFirmwareDisabled1.Name = "configFirmwareDisabled1";
//
// backstageViewPagewizard
//
this.backstageViewPagewizard.Advanced = false;
this.backstageViewPagewizard.LinkText = "Wizard";
this.backstageViewPagewizard.Page = this.configWizard1;
this.backstageViewPagewizard.Parent = null;
this.backstageViewPagewizard.Show = true;
this.backstageViewPagewizard.Spacing = 30;
resources.ApplyResources(this.backstageViewPagewizard, "backstageViewPagewizard");
//
// configWizard1
//
resources.ApplyResources(this.configWizard1, "configWizard1");
this.configWizard1.Name = "configWizard1";
//
// backstageViewPagemand
//
this.backstageViewPagemand.Advanced = false;
this.backstageViewPagemand.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPagemand.LinkText = "Mandatory Hardware";
this.backstageViewPagemand.Page = this.configMandatory1;
this.backstageViewPagemand.Parent = null;
this.backstageViewPagemand.Show = true;
this.backstageViewPagemand.Spacing = 30;
resources.ApplyResources(this.backstageViewPagemand, "backstageViewPagemand");
//
// configMandatory1
//
resources.ApplyResources(this.configMandatory1, "configMandatory1");
this.configMandatory1.Name = "configMandatory1";
//
// backstageViewPagetradheli
//
this.backstageViewPagetradheli.Advanced = false;
this.backstageViewPagetradheli.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isHeli", true));
this.backstageViewPagetradheli.LinkText = "Heli Setup";
this.backstageViewPagetradheli.Page = this.configTradHeli1;
this.backstageViewPagetradheli.Parent = this.backstageViewPagemand;
this.backstageViewPagetradheli.Show = true;
this.backstageViewPagetradheli.Spacing = 30;
resources.ApplyResources(this.backstageViewPagetradheli, "backstageViewPagetradheli");
//
// configTradHeli1
//
resources.ApplyResources(this.configTradHeli1, "configTradHeli1");
this.configTradHeli1.Name = "configTradHeli1";
//
// backstageViewPageframetype
//
this.backstageViewPageframetype.Advanced = false;
this.backstageViewPageframetype.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true));
this.backstageViewPageframetype.LinkText = "Frame Type";
this.backstageViewPageframetype.Page = this.configFrameType1;
this.backstageViewPageframetype.Parent = this.backstageViewPagemand;
this.backstageViewPageframetype.Show = true;
this.backstageViewPageframetype.Spacing = 30;
resources.ApplyResources(this.backstageViewPageframetype, "backstageViewPageframetype");
//
// configFrameType1
//
resources.ApplyResources(this.configFrameType1, "configFrameType1");
this.configFrameType1.Name = "configFrameType1";
//
// backstageViewPageaccel
//
this.backstageViewPageaccel.Advanced = false;
this.backstageViewPageaccel.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPageaccel.LinkText = "Accel Calibration";
this.backstageViewPageaccel.Page = this.configAccelerometerCalibration;
this.backstageViewPageaccel.Parent = this.backstageViewPagemand;
this.backstageViewPageaccel.Show = true;
this.backstageViewPageaccel.Spacing = 30;
resources.ApplyResources(this.backstageViewPageaccel, "backstageViewPageaccel");
//
// configAccelerometerCalibration
//
resources.ApplyResources(this.configAccelerometerCalibration, "configAccelerometerCalibration");
this.configAccelerometerCalibration.Name = "configAccelerometerCalibration";
//
// backstageViewPagecompass
//
this.backstageViewPagecompass.Advanced = false;
this.backstageViewPagecompass.LinkText = "Compass";
this.backstageViewPagecompass.Page = this.configHWCompass1;
this.backstageViewPagecompass.Parent = this.backstageViewPagemand;
this.backstageViewPagecompass.Show = true;
this.backstageViewPagecompass.Spacing = 30;
resources.ApplyResources(this.backstageViewPagecompass, "backstageViewPagecompass");
//
// configHWCompass1
//
resources.ApplyResources(this.configHWCompass1, "configHWCompass1");
this.configHWCompass1.Name = "configHWCompass1";
//
// backstageViewPageradio
//
this.backstageViewPageradio.Advanced = false;
this.backstageViewPageradio.LinkText = "Radio Calibration";
this.backstageViewPageradio.Page = this.configRadioInput1;
this.backstageViewPageradio.Parent = this.backstageViewPagemand;
this.backstageViewPageradio.Show = true;
this.backstageViewPageradio.Spacing = 30;
resources.ApplyResources(this.backstageViewPageradio, "backstageViewPageradio");
//
// configRadioInput1
//
resources.ApplyResources(this.configRadioInput1, "configRadioInput1");
this.configRadioInput1.Name = "configRadioInput1";
//
// backstageViewPageESC
//
this.backstageViewPageESC.Advanced = false;
this.backstageViewPageESC.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true));
this.backstageViewPageESC.LinkText = "ESC Calibration";
this.backstageViewPageESC.Page = this.configESC1;
this.backstageViewPageESC.Parent = this.backstageViewPagemand;
this.backstageViewPageESC.Show = false;
this.backstageViewPageESC.Spacing = 30;
resources.ApplyResources(this.backstageViewPageESC, "backstageViewPageESC");
//
// configESC1
//
resources.ApplyResources(this.configESC1, "configESC1");
this.configESC1.Name = "configESC1";
//
// backstageViewPageflmode
//
this.backstageViewPageflmode.Advanced = false;
this.backstageViewPageflmode.LinkText = "Flight Modes";
this.backstageViewPageflmode.Page = this.configFlightModes1;
this.backstageViewPageflmode.Parent = this.backstageViewPagemand;
this.backstageViewPageflmode.Show = true;
this.backstageViewPageflmode.Spacing = 30;
resources.ApplyResources(this.backstageViewPageflmode, "backstageViewPageflmode");
//
// configFlightModes1
//
resources.ApplyResources(this.configFlightModes1, "configFlightModes1");
this.configFlightModes1.Name = "configFlightModes1";
//
// backstageViewPagefs
//
this.backstageViewPagefs.Advanced = false;
this.backstageViewPagefs.LinkText = "FailSafe";
this.backstageViewPagefs.Page = this.configFailSafe1;
this.backstageViewPagefs.Parent = this.backstageViewPagemand;
this.backstageViewPagefs.Show = true;
this.backstageViewPagefs.Spacing = 30;
resources.ApplyResources(this.backstageViewPagefs, "backstageViewPagefs");
//
// configFailSafe1
//
resources.ApplyResources(this.configFailSafe1, "configFailSafe1");
this.configFailSafe1.Name = "configFailSafe1";
//
// backstageViewPageopt
//
this.backstageViewPageopt.Advanced = false;
this.backstageViewPageopt.LinkText = "Optional Hardware";
this.backstageViewPageopt.Page = this.configOptional1;
this.backstageViewPageopt.Parent = null;
this.backstageViewPageopt.Show = true;
this.backstageViewPageopt.Spacing = 30;
resources.ApplyResources(this.backstageViewPageopt, "backstageViewPageopt");
//
// configOptional1
//
resources.ApplyResources(this.configOptional1, "configOptional1");
this.configOptional1.Name = "configOptional1";
//
// backstageViewPageSikradio
//
this.backstageViewPageSikradio.Advanced = false;
this.backstageViewPageSikradio.LinkText = "Sik Radio";
this.backstageViewPageSikradio.Page = this._3DRradio1;
this.backstageViewPageSikradio.Parent = this.backstageViewPageopt;
this.backstageViewPageSikradio.Show = true;
this.backstageViewPageSikradio.Spacing = 30;
resources.ApplyResources(this.backstageViewPageSikradio, "backstageViewPageSikradio");
//
// _3DRradio1
//
resources.ApplyResources(this._3DRradio1, "_3DRradio1");
this._3DRradio1.Name = "_3DRradio1";
//
// backstageViewPagebatmon
//
this.backstageViewPagebatmon.Advanced = false;
this.backstageViewPagebatmon.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPagebatmon.LinkText = "Battery Monitor";
this.backstageViewPagebatmon.Page = this.configBatteryMonitoring1;
this.backstageViewPagebatmon.Parent = this.backstageViewPageopt;
this.backstageViewPagebatmon.Show = true;
this.backstageViewPagebatmon.Spacing = 30;
resources.ApplyResources(this.backstageViewPagebatmon, "backstageViewPagebatmon");
//
// configBatteryMonitoring1
//
resources.ApplyResources(this.configBatteryMonitoring1, "configBatteryMonitoring1");
this.configBatteryMonitoring1.Name = "configBatteryMonitoring1";
//
// backstageViewPageBatt2
//
this.backstageViewPageBatt2.Advanced = false;
this.backstageViewPageBatt2.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPageBatt2.LinkText = "Battery Monitor 2";
this.backstageViewPageBatt2.Page = this.configBatteryMonitoring21;
this.backstageViewPageBatt2.Parent = this.backstageViewPageopt;
this.backstageViewPageBatt2.Show = true;
this.backstageViewPageBatt2.Spacing = 30;
resources.ApplyResources(this.backstageViewPageBatt2, "backstageViewPageBatt2");
//
// configBatteryMonitoring21
//
resources.ApplyResources(this.configBatteryMonitoring21, "configBatteryMonitoring21");
this.configBatteryMonitoring21.Name = "configBatteryMonitoring21";
//
// backstageViewPagecompassmot
//
this.backstageViewPagecompassmot.Advanced = false;
this.backstageViewPagecompassmot.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true));
this.backstageViewPagecompassmot.LinkText = "Compass/Motor Calib";
this.backstageViewPagecompassmot.Page = this.configCompassMot1;
this.backstageViewPagecompassmot.Parent = this.backstageViewPageopt;
this.backstageViewPagecompassmot.Show = true;
this.backstageViewPagecompassmot.Spacing = 30;
resources.ApplyResources(this.backstageViewPagecompassmot, "backstageViewPagecompassmot");
//
// configCompassMot1
//
resources.ApplyResources(this.configCompassMot1, "configCompassMot1");
this.configCompassMot1.Name = "configCompassMot1";
//
// backstageViewPagesonar
//
this.backstageViewPagesonar.Advanced = false;
this.backstageViewPagesonar.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPagesonar.LinkText = "Sonar";
this.backstageViewPagesonar.Page = this.ConfigHWRangeFinder1;
this.backstageViewPagesonar.Parent = this.backstageViewPageopt;
this.backstageViewPagesonar.Show = true;
this.backstageViewPagesonar.Spacing = 30;
resources.ApplyResources(this.backstageViewPagesonar, "backstageViewPagesonar");
//
// ConfigHWRangeFinder1
//
resources.ApplyResources(this.ConfigHWRangeFinder1, "ConfigHWRangeFinder1");
this.ConfigHWRangeFinder1.Name = "ConfigHWRangeFinder1";
//
// backstageViewPageairspeed
//
this.backstageViewPageairspeed.Advanced = false;
this.backstageViewPageairspeed.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPageairspeed.LinkText = "Airspeed";
this.backstageViewPageairspeed.Page = this.configHWAirspeed1;
this.backstageViewPageairspeed.Parent = this.backstageViewPageopt;
this.backstageViewPageairspeed.Show = true;
this.backstageViewPageairspeed.Spacing = 30;
resources.ApplyResources(this.backstageViewPageairspeed, "backstageViewPageairspeed");
//
// configHWAirspeed1
//
resources.ApplyResources(this.configHWAirspeed1, "configHWAirspeed1");
this.configHWAirspeed1.Name = "configHWAirspeed1";
//
// backstageViewPageoptflow
//
this.backstageViewPageoptflow.Advanced = false;
this.backstageViewPageoptflow.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPageoptflow.LinkText = "Optical Flow";
this.backstageViewPageoptflow.Page = this.configHWOptFlow1;
this.backstageViewPageoptflow.Parent = this.backstageViewPageopt;
this.backstageViewPageoptflow.Show = true;
this.backstageViewPageoptflow.Spacing = 30;
resources.ApplyResources(this.backstageViewPageoptflow, "backstageViewPageoptflow");
//
// configHWOptFlow1
//
resources.ApplyResources(this.configHWOptFlow1, "configHWOptFlow1");
this.configHWOptFlow1.Name = "configHWOptFlow1";
//
// backstageViewPageosd
//
this.backstageViewPageosd.Advanced = false;
this.backstageViewPageosd.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPageosd.LinkText = "OSD";
this.backstageViewPageosd.Page = this.configHWOSD1;
this.backstageViewPageosd.Parent = this.backstageViewPageopt;
this.backstageViewPageosd.Show = true;
this.backstageViewPageosd.Spacing = 30;
resources.ApplyResources(this.backstageViewPageosd, "backstageViewPageosd");
//
// configHWOSD1
//
resources.ApplyResources(this.configHWOSD1, "configHWOSD1");
this.configHWOSD1.Name = "configHWOSD1";
//
// backstageViewPagegimbal
//
this.backstageViewPagegimbal.Advanced = false;
this.backstageViewPagegimbal.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isConnected", true));
this.backstageViewPagegimbal.LinkText = "Camera Gimbal";
this.backstageViewPagegimbal.Page = this.configMount1;
this.backstageViewPagegimbal.Parent = this.backstageViewPageopt;
this.backstageViewPagegimbal.Show = true;
this.backstageViewPagegimbal.Spacing = 30;
resources.ApplyResources(this.backstageViewPagegimbal, "backstageViewPagegimbal");
//
// configMount1
//
resources.ApplyResources(this.configMount1, "configMount1");
this.configMount1.Name = "configMount1";
//
// backstageViewPageAntTrack
//
this.backstageViewPageAntTrack.Advanced = false;
this.backstageViewPageAntTrack.LinkText = "Antenna tracker";
this.backstageViewPageAntTrack.Page = this.tracker1;
this.backstageViewPageAntTrack.Parent = this.backstageViewPageopt;
this.backstageViewPageAntTrack.Show = true;
this.backstageViewPageAntTrack.Spacing = 30;
resources.ApplyResources(this.backstageViewPageAntTrack, "backstageViewPageAntTrack");
//
// tracker1
//
this.tracker1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(38)))), ((int)(((byte)(39)))), ((int)(((byte)(40)))));
resources.ApplyResources(this.tracker1, "tracker1");
this.tracker1.ForeColor = System.Drawing.Color.White;
this.tracker1.Name = "tracker1";
//
// backstageViewPageMotorTest
//
this.backstageViewPageMotorTest.Advanced = false;
this.backstageViewPageMotorTest.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true));
this.backstageViewPageMotorTest.LinkText = "Motor Test";
this.backstageViewPageMotorTest.Page = this.configMotor1;
this.backstageViewPageMotorTest.Parent = this.backstageViewPageopt;
this.backstageViewPageMotorTest.Show = true;
this.backstageViewPageMotorTest.Spacing = 30;
resources.ApplyResources(this.backstageViewPageMotorTest, "backstageViewPageMotorTest");
//
// configMotor1
//
resources.ApplyResources(this.configMotor1, "configMotor1");
this.configMotor1.Name = "configMotor1";
//
// backstageViewPagehwbt
//
this.backstageViewPagehwbt.Advanced = false;
this.backstageViewPagehwbt.LinkText = "Bluetooth Setup";
this.backstageViewPagehwbt.Page = this.configHWBT1;
this.backstageViewPagehwbt.Parent = this.backstageViewPageopt;
this.backstageViewPagehwbt.Show = true;
this.backstageViewPagehwbt.Spacing = 30;
resources.ApplyResources(this.backstageViewPagehwbt, "backstageViewPagehwbt");
//
// configHWBT1
//
resources.ApplyResources(this.configHWBT1, "configHWBT1");
this.configHWBT1.Name = "configHWBT1";
//
// backstageViewPageParachute
//
this.backstageViewPageParachute.Advanced = false;
this.backstageViewPageParachute.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isCopter", true));
this.backstageViewPageParachute.LinkText = "Parachute";
this.backstageViewPageParachute.Page = this.configHWPa1;
this.backstageViewPageParachute.Parent = this.backstageViewPageopt;
this.backstageViewPageParachute.Show = true;
this.backstageViewPageParachute.Spacing = 30;
resources.ApplyResources(this.backstageViewPageParachute, "backstageViewPageParachute");
//
// configHWPa1
//
resources.ApplyResources(this.configHWPa1, "configHWPa1");
this.configHWPa1.Name = "configHWPa1";
//
// backstageViewPageinstfw
//
this.backstageViewPageinstfw.Advanced = false;
this.backstageViewPageinstfw.DataBindings.Add(new System.Windows.Forms.Binding("Show", this.initialSetupBindingSource, "isDisConnected", true));
this.backstageViewPageinstfw.LinkText = "Install Firmware";
this.backstageViewPageinstfw.Page = this.configFirmware1;
this.backstageViewPageinstfw.Parent = null;
this.backstageViewPageinstfw.Show = false;
this.backstageViewPageinstfw.Spacing = 30;
resources.ApplyResources(this.backstageViewPageinstfw, "backstageViewPageinstfw");
//
// InitialSetup
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.Controls.Add(this.backstageView);
this.Controls.Add(this.configAccelerometerCalibration);
this.Controls.Add(this.configHWBT1);
this.Controls.Add(this.configBatteryMonitoring21);
this.MinimumSize = new System.Drawing.Size(1000, 450);
this.Name = "InitialSetup";
resources.ApplyResources(this, "$this");
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HardwareConfig_FormClosing);
this.Load += new System.EventHandler(this.HardwareConfig_Load);
((System.ComponentModel.ISupportInitialize)(this.initialSetupBindingSource)).EndInit();
this.ResumeLayout(false);
}
#endregion
internal Controls.BackstageView.BackstageView backstageView;
private ConfigurationView.ConfigFirmware configFirmware1;
private ConfigurationView.ConfigFirmwareDisabled configFirmwareDisabled1;
private ConfigurationView.ConfigWizard configWizard1;
private ConfigurationView.ConfigMandatory configMandatory1;
private ConfigurationView.ConfigOptional configOptional1;
private ConfigurationView.ConfigTradHeli configTradHeli1;
private ConfigurationView.ConfigFrameType configFrameType1;
private ConfigurationView.ConfigHWCompass configHWCompass1;
private ConfigurationView.ConfigRadioInput configRadioInput1;
private ConfigurationView.ConfigFlightModes configFlightModes1;
private ConfigurationView.ConfigFailSafe configFailSafe1;
private Sikradio _3DRradio1;
private ConfigurationView.ConfigBatteryMonitoring configBatteryMonitoring1;
private ConfigurationView.ConfigHWRangeFinder ConfigHWRangeFinder1;
private ConfigurationView.ConfigHWAirspeed configHWAirspeed1;
private ConfigurationView.ConfigHWOptFlow configHWOptFlow1;
private ConfigurationView.ConfigHWOSD configHWOSD1;
private ConfigurationView.ConfigMount configMount1;
private ConfigurationView.ConfigMotorTest configMotor1;
private Antenna.Tracker tracker1;
private Controls.BackstageView.BackstageViewPage backstageViewPageinstfw;
private Controls.BackstageView.BackstageViewPage backstageViewPagewizard;
private Controls.BackstageView.BackstageViewPage backstageViewPagemand;
private Controls.BackstageView.BackstageViewPage backstageViewPageopt;
private Controls.BackstageView.BackstageViewPage backstageViewPagetradheli;
private Controls.BackstageView.BackstageViewPage backstageViewPageframetype;
private Controls.BackstageView.BackstageViewPage backstageViewPagecompass;
private Controls.BackstageView.BackstageViewPage backstageViewPageradio;
private Controls.BackstageView.BackstageViewPage backstageViewPageflmode;
private Controls.BackstageView.BackstageViewPage backstageViewPagefs;
private Controls.BackstageView.BackstageViewPage backstageViewPageSikradio;
private Controls.BackstageView.BackstageViewPage backstageViewPagebatmon;
private Controls.BackstageView.BackstageViewPage backstageViewPagesonar;
private Controls.BackstageView.BackstageViewPage backstageViewPageairspeed;
private Controls.BackstageView.BackstageViewPage backstageViewPageoptflow;
private Controls.BackstageView.BackstageViewPage backstageViewPageosd;
private Controls.BackstageView.BackstageViewPage backstageViewPagegimbal;
private Controls.BackstageView.BackstageViewPage backstageViewPageAntTrack;
private Controls.BackstageView.BackstageViewPage backstageViewPagefwdisabled;
private Controls.BackstageView.BackstageViewPage backstageViewPagefw;
private System.Windows.Forms.BindingSource initialSetupBindingSource;
private Controls.BackstageView.BackstageViewPage backstageViewPagecompassmot;
private ConfigurationView.ConfigCompassMot configCompassMot1;
private Controls.BackstageView.BackstageViewPage backstageViewPageMotorTest;
private Controls.BackstageView.BackstageViewPage backstageViewPageaccel;
private ConfigurationView.ConfigAccelerometerCalibration configAccelerometerCalibration;
private Controls.BackstageView.BackstageViewPage backstageViewPagehwbt;
private ConfigurationView.ConfigHWBT configHWBT1;
private Controls.BackstageView.BackstageViewPage backstageViewPageParachute;
private ConfigurationView.ConfigHWParachute configHWPa1;
private Controls.BackstageView.BackstageViewPage backstageViewPageESC;
private ConfigurationView.ConfigESCCalibration configESC1; private Controls.BackstageView.BackstageViewPage backstageViewPageBatt2;
private ConfigurationView.ConfigBatteryMonitoring2 configBatteryMonitoring21;
}
}
| Java |
/*
FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
***************************************************************************
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
***************************************************************************
FreeRTOS 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. Full license text is available on the following
link: http://www.freertos.org/a00114.html
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that is more than just the market leader, it *
* is the industry's de facto standard. *
* *
* Help yourself get started quickly while simultaneously helping *
* to support the FreeRTOS project by purchasing a FreeRTOS *
* tutorial book, reference manual, or both: *
* http://www.FreeRTOS.org/Documentation *
* *
***************************************************************************
http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
the FAQ page "My application does not run, what could be wrong?". Have you
defined configASSERT()?
http://www.FreeRTOS.org/support - In return for receiving this top quality
embedded software for free we request you assist our global community by
participating in the support forum.
http://www.FreeRTOS.org/training - Investing in training allows your team to
be as productive as possible as early as possible. Now you can receive
FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
Ltd, and the world's leading authority on the world's leading RTOS.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and commercial middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H
/*-----------------------------------------------------------
* Application specific definitions.
*
* These definitions should be adjusted for your particular hardware and
* application requirements.
*
* THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
* FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
*
* See http://www.freertos.org/a00110.html.
*----------------------------------------------------------*/
/* For definition of BOARD_MCK. */
#ifndef __IAR_SYSTEMS_ASM__
/* Prevent chip.h being included when this file is included from the IAR
port layer assembly file. */
#include "board.h"
#endif
#define configUSE_PREEMPTION 1
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1
#define configUSE_QUEUE_SETS 1
#define configUSE_IDLE_HOOK 0
#define configUSE_TICK_HOOK 1
#define configCPU_CLOCK_HZ ( BOARD_MCK << 1UL )
#define configTICK_RATE_HZ ( 1000 )
#define configMAX_PRIORITIES ( 5 )
#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 130 )
#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 46 * 1024 ) )
#define configMAX_TASK_NAME_LEN ( 10 )
#define configUSE_TRACE_FACILITY 1
#define configUSE_16_BIT_TICKS 0
#define configIDLE_SHOULD_YIELD 1
#define configUSE_MUTEXES 1
#define configQUEUE_REGISTRY_SIZE 8
#define configCHECK_FOR_STACK_OVERFLOW 2
#define configUSE_RECURSIVE_MUTEXES 1
#define configUSE_MALLOC_FAILED_HOOK 1
#define configUSE_APPLICATION_TASK_TAG 0
#define configUSE_COUNTING_SEMAPHORES 1
/* The full demo always has tasks to run so the tick will never be turned off.
The blinky demo will use the default tickless idle implementation to turn the
tick off. */
#define configUSE_TICKLESS_IDLE 0
/* Run time stats gathering definitions. */
#define configGENERATE_RUN_TIME_STATS 0
/* This demo makes use of one or more example stats formatting functions. These
format the raw data provided by the uxTaskGetSystemState() function in to human
readable ASCII form. See the notes in the implementation of vTaskList() within
FreeRTOS/Source/tasks.c for limitations. */
#define configUSE_STATS_FORMATTING_FUNCTIONS 1
/* Co-routine definitions. */
#define configUSE_CO_ROUTINES 0
#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )
/* Software timer definitions. */
#define configUSE_TIMERS 1
#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
#define configTIMER_QUEUE_LENGTH 5
#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 )
/* Set the following definitions to 1 to include the API function, or zero
to exclude the API function. */
#define INCLUDE_vTaskPrioritySet 1
#define INCLUDE_uxTaskPriorityGet 1
#define INCLUDE_vTaskDelete 1
#define INCLUDE_vTaskCleanUpResources 1
#define INCLUDE_vTaskSuspend 1
#define INCLUDE_vTaskDelayUntil 1
#define INCLUDE_vTaskDelay 1
#define INCLUDE_eTaskGetState 1
#define INCLUDE_xTimerPendFunctionCall 1
/* Cortex-M specific definitions. */
#ifdef __NVIC_PRIO_BITS
/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */
#define configPRIO_BITS __NVIC_PRIO_BITS
#else
#define configPRIO_BITS 3 /* 7 priority levels */
#endif
/* The lowest interrupt priority that can be used in a call to a "set priority"
function. */
#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x07
/* The highest interrupt priority that can be used by any interrupt service
routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL
INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER
PRIORITY THAN THIS! (higher priorities are lower numeric values. */
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 4
/* Interrupt priorities used by the kernel port layer itself. These are generic
to all Cortex-M ports, and do not rely on any particular library functions. */
#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
/* Normal assert() semantics without relying on the provision of an assert.h
header file. */
#define configASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); }
/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS
standard names. */
#define xPortPendSVHandler PendSV_Handler
#define vPortSVCHandler SVC_Handler
#define xPortSysTickHandler SysTick_Handler
#endif /* FREERTOS_CONFIG_H */
| Java |
/* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
* Copyright (C) 2011-2017 - Daniel De Matteis
* Copyright (C) 2016-2019 - Brad Parker
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
/* SIXEL context. */
#ifdef HAVE_CONFIG_H
#include "../../config.h"
#endif
#include "../../configuration.h"
#include "../../dynamic.h"
#include "../../retroarch.h"
#include "../../verbosity.h"
#include "../../ui/ui_companion_driver.h"
#if defined(_WIN32) && !defined(_XBOX)
#include "../common/win32_common.h"
#endif
static enum gfx_ctx_api sixel_ctx_api = GFX_CTX_NONE;
static void gfx_ctx_sixel_check_window(void *data, bool *quit,
bool *resize, unsigned *width, unsigned *height, bool is_shutdown)
{
}
static bool gfx_ctx_sixel_set_resize(void *data,
unsigned width, unsigned height)
{
(void)data;
(void)width;
(void)height;
return false;
}
static void gfx_ctx_sixel_update_window_title(void *data, void *data2)
{
const settings_t *settings = config_get_ptr();
video_frame_info_t *video_info = (video_frame_info_t*)data2;
#if defined(_WIN32) && !defined(_XBOX)
const ui_window_t *window = ui_companion_driver_get_window_ptr();
char title[128];
title[0] = '\0';
if (settings->bools.video_memory_show)
{
uint64_t mem_bytes_used = frontend_driver_get_used_memory();
uint64_t mem_bytes_total = frontend_driver_get_total_memory();
char mem[128];
mem[0] = '\0';
snprintf(
mem, sizeof(mem), " || MEM: %.2f/%.2fMB", mem_bytes_used / (1024.0f * 1024.0f),
mem_bytes_total / (1024.0f * 1024.0f));
strlcat(video_info->fps_text, mem, sizeof(video_info->fps_text));
}
video_driver_get_window_title(title, sizeof(title));
if (window && title[0])
window->set_title(&main_window, title);
#endif
}
static void gfx_ctx_sixel_get_video_size(void *data,
unsigned *width, unsigned *height)
{
(void)data;
}
static void *gfx_ctx_sixel_init(
video_frame_info_t *video_info, void *video_driver)
{
(void)video_driver;
return (void*)"sixel";
}
static void gfx_ctx_sixel_destroy(void *data)
{
(void)data;
}
static bool gfx_ctx_sixel_set_video_mode(void *data,
video_frame_info_t *video_info,
unsigned width, unsigned height,
bool fullscreen)
{
return true;
}
static void gfx_ctx_sixel_input_driver(void *data,
const char *joypad_name,
input_driver_t **input, void **input_data)
{
(void)data;
#ifdef HAVE_UDEV
*input_data = input_udev.init(joypad_name);
if (*input_data)
{
*input = &input_udev;
return;
}
#endif
*input = NULL;
*input_data = NULL;
}
static bool gfx_ctx_sixel_has_focus(void *data)
{
return true;
}
static bool gfx_ctx_sixel_suppress_screensaver(void *data, bool enable)
{
return true;
}
static bool gfx_ctx_sixel_get_metrics(void *data,
enum display_metric_types type, float *value)
{
return false;
}
static enum gfx_ctx_api gfx_ctx_sixel_get_api(void *data)
{
return sixel_ctx_api;
}
static bool gfx_ctx_sixel_bind_api(void *data,
enum gfx_ctx_api api, unsigned major, unsigned minor)
{
(void)data;
return true;
}
static void gfx_ctx_sixel_show_mouse(void *data, bool state)
{
(void)data;
}
static void gfx_ctx_sixel_swap_interval(void *data, int interval)
{
(void)data;
(void)interval;
}
static void gfx_ctx_sixel_set_flags(void *data, uint32_t flags)
{
(void)data;
(void)flags;
}
static uint32_t gfx_ctx_sixel_get_flags(void *data)
{
uint32_t flags = 0;
return flags;
}
static void gfx_ctx_sixel_swap_buffers(void *data, void *data2)
{
(void)data;
}
const gfx_ctx_driver_t gfx_ctx_sixel = {
gfx_ctx_sixel_init,
gfx_ctx_sixel_destroy,
gfx_ctx_sixel_get_api,
gfx_ctx_sixel_bind_api,
gfx_ctx_sixel_swap_interval,
gfx_ctx_sixel_set_video_mode,
gfx_ctx_sixel_get_video_size,
NULL, /* get_refresh_rate */
NULL, /* get_video_output_size */
NULL, /* get_video_output_prev */
NULL, /* get_video_output_next */
gfx_ctx_sixel_get_metrics,
NULL,
gfx_ctx_sixel_update_window_title,
gfx_ctx_sixel_check_window,
gfx_ctx_sixel_set_resize,
gfx_ctx_sixel_has_focus,
gfx_ctx_sixel_suppress_screensaver,
true, /* has_windowed */
gfx_ctx_sixel_swap_buffers,
gfx_ctx_sixel_input_driver,
NULL,
NULL,
NULL,
gfx_ctx_sixel_show_mouse,
"sixel",
gfx_ctx_sixel_get_flags,
gfx_ctx_sixel_set_flags,
NULL,
NULL,
NULL
};
| Java |
<!--
title: "Install Netdata on FreeNAS"
custom_edit_url: https://github.com/netdata/netdata/edit/master/packaging/installer/methods/freenas.md
-->
# Install Netdata on FreeNAS
On FreeNAS-Corral-RELEASE (>=10.0.3 and <11.3), Netdata is pre-installed.
To use Netdata, the service will need to be enabled and started from the FreeNAS [CLI](https://github.com/freenas/cli).
To enable the Netdata service:
```sh
service netdata config set enable=true
```
To start the Netdata service:
```sh
service netdata start
```
| Java |
/*
* This file is part of EasyRPG Player.
*
* EasyRPG Player 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.
*
* EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
// Headers
#include "audio.h"
#include "system.h"
#include "baseui.h"
AudioInterface& Audio() {
static EmptyAudio default_;
return DisplayUi? DisplayUi->GetAudio() : default_;
}
| Java |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the ADLINK Software License Agreement Rev 2.7 2nd October
* 2014 (the "License"); you may not use this file except in compliance with
* the License.
* You may obtain a copy of the License at:
* $OSPL_HOME/LICENSE
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/** \file os/linux/code/os_time.c
* \brief Linux time management
*
* Implements time management for Linux
* by including the generic Linux implementation
*/
#include "../linux/code/os_time.c"
| Java |
"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
def downgrade():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')
| Java |
module ComboFieldTagHelper
def combo_field_tag(name, value, option_tags = nil, options = {})
select_placeholder = options[:select_placeholder] || "Select existing value"
input_placeholder = options[:input_placeholder] || "Enter new value"
id = options[:id]
klass = options[:class] || 'combo-field'
required = options[:required]
help = options[:help]
unless options[:label] == false
label_html = label_tag(options[:label] || name, nil, class: "#{'required' if required}")
end
select_options = {
prompt: '',
class: "#{klass} form-control #{'required' if required}",
data: { placeholder: select_placeholder }
}
select_options[:id] = "#{id}_select" if id.present?
select_html = select_tag name, option_tags, select_options
text_field_options = {
class: "form-control",
placeholder: input_placeholder
}
text_field_options[:id] = "#{id}_text" if id.present?
text_field_html = text_field_tag name, value, text_field_options
if help
select_html << content_tag(:small, help.html_safe, class: 'help-block')
end
<<-HTML.html_safe
<div class='combo-field-wrapper #{klass}-wrapper'>
#{label_html}
<div class='combo-field-select #{klass}-select'>#{select_html}</div>
<div class='combo-field-alternative'>or</div>
<div class='combo-field-input #{klass}-input'>
#{text_field_html}
<a href='#' class='clear-input hidden'>×</a>
</div>
</div>
HTML
end
end
| Java |
{
"": {
"domain": "ckan",
"lang": "cs_CZ",
"plural-forms": "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"
},
"An Error Occurred": [
null,
"Nastala chyba"
],
"Are you sure you want to perform this action?": [
null,
"Jste si jistí, že chcete provést tuto akci?"
],
"Cancel": [
null,
"Zrušit"
],
"Confirm": [
null,
"Potvrdit"
],
"Edit": [
null,
"Upravit"
],
"Failed to load data API information": [
null,
"Pokus o získání informací pomocí API selhal"
],
"Follow": [
null,
"Sledovat"
],
"Hide": [
null,
"Skrýt"
],
"Image": [
null,
"Obrázek"
],
"Input is too short, must be at least one character": [
null,
"Zadaný vstup je příliš krátký, musíte zadat alespoň jeden znak"
],
"Link": [
null,
"Odkaz"
],
"Link to a URL on the internet (you can also link to an API)": [
null,
"Odkaz na internetovou URL adresu (můžete také zadat odkaz na API)"
],
"Loading...": [
null,
"Nahrávám ..."
],
"No matches found": [
null,
"Nenalezena žádná shoda"
],
"Please Confirm Action": [
null,
"Prosím potvrďte akci"
],
"Remove": [
null,
"Odstranit"
],
"Reorder resources": [
null,
"Změnit pořadí zdrojů"
],
"Reset this": [
null,
"Resetovat"
],
"Resource uploaded": [
null,
"Zdroj nahrán"
],
"Save order": [
null,
"Uložit pořadí"
],
"Saving...": [
null,
"Ukládám..."
],
"Show more": [
null,
"Ukázat více"
],
"Start typing…": [
null,
"Začněte psát..."
],
"There are unsaved modifications to this form": [
null,
"Tento formulář obsahuje neuložené změny"
],
"There is no API data to load for this resource": [
null,
"Tento zdroj neobsahuje žádná data, která lze poskytnou přes API"
],
"URL": [
null,
"URL"
],
"Unable to authenticate upload": [
null,
"Nastala chyba autentizace při nahrávání dat"
],
"Unable to get data for uploaded file": [
null,
"Nelze získat data z nahraného souboru"
],
"Unable to upload file": [
null,
"Nelze nahrát soubor"
],
"Unfollow": [
null,
"Přestat sledovat"
],
"Upload": [
null,
"Nahrát"
],
"Upload a file": [
null,
"Nahrát soubor"
],
"Upload a file on your computer": [
null,
"Nahrát soubor na Váš počítač"
],
"You are uploading a file. Are you sure you want to navigate away and stop this upload?": [
null,
"Právě nahráváte soubor. Jste si opravdu jistí, že chcete tuto stránku opustit a ukončit tak nahrávání?"
],
"show less": [
null,
"ukázat méně"
],
"show more": [
null,
"ukázat více"
]
} | Java |
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Spectra</title>
<meta name="author" content="CEERI">
<meta name="description" content="[No canvas support] spectra = []; // Graph Data Array l = 0; // The letter 'L' - NOT a one var socket = io.connect('http://172.16.5.14:7000'); // …">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="/spectra/atom.xml" rel="alternate" title="Spectra" type="application/atom+xml">
<link rel="canonical" href="">
<link href="/spectra/favicon.png" rel="shortcut icon">
<link href="/spectra/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script async="true" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<header id="header" class="inner"><h1><a href="/spectra/">Spectra</a></h1>
<nav id="main-nav"><ul class="main">
</ul>
</nav>
<nav id="mobile-nav">
<div class="alignleft menu">
<a class="button">Menu</a>
<div class="container"><ul class="main">
</ul>
</div>
</div>
<div class="alignright search">
<a class="button"></a>
<div class="container">
<form action="http://google.com/search" method="get">
<input type="text" name="q" results="0">
<input type="hidden" name="q" value="site:172.16.5.14/spectra">
</form>
</div>
</div>
</nav>
<nav id="sub-nav" class="alignright">
<div class="social">
<a class="github" href="https://github.com/debanjum/Spectroserver" title="GitHub">GitHub</a>
<a class="rss" href="/spectra/atom.xml" title="RSS">RSS</a>
</div>
<form class="search" action="http://google.com/search" method="get">
<input class="alignright" type="text" name="q" results="0">
<input type="hidden" name="q" value="site:172.16.5.14/spectra">
</form>
</nav>
<h2><a>Spectral Data Visualisation & Spectrophotometer Control</a></h2>
</header>
<div id="content" class="inner"> <head>
<script type="text/javascript" src="http://172.16.5.14:7000/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/spectra/javascripts/RGraph.line.js" ></script>
<script type="text/javascript" src="/spectra/javascripts/RGraph.common.core.js" ></script>
<canvas id="cvs" width="1000" height="450">[No canvas support]</canvas>
<script>
spectra = []; // Graph Data Array
l = 0; // The letter 'L' - NOT a one
var socket = io.connect('http://172.16.5.14:7000');
// Pre-pad the arrays with null values
for (var i=0; i<1000; ++i)
{ spectra.push(null); }
function getGraph(id, spectra)
{
// After creating the chart, store it on the global window object
if (!window.__rgraph_line__) {
window.__rgraph_line__ = new RGraph.Line(id, spectra);
window.__rgraph_line__.Set('chart.background.barcolor1', 'white');
window.__rgraph_line__.Set('chart.background.barcolor2', 'white');
window.__rgraph_line__.Set('chart.title.xaxis', 'Wavelength');
window.__rgraph_line__.Set('chart.title.yaxis', 'Voltage');
window.__rgraph_line__.Set('chart.title.vpos', 0.5);
window.__rgraph_line__.Set('chart.title', 'Spectral Profile');
window.__rgraph_line__.Set('chart.title.yaxis.pos', 0.5);
window.__rgraph_line__.Set('chart.title.xaxis.pos', 0.5);
window.__rgraph_line__.Set('chart.colors', ['black']);
window.__rgraph_line__.Set('chart.linewidth',1.5);
window.__rgraph_line__.Set('chart.yaxispos', 'right');
window.__rgraph_line__.Set('chart.ymax', 3.3);
window.__rgraph_line__.Set('chart.ymin', 0);
window.__rgraph_line__.Set('chart.yticks', 1);
window.__rgraph_line__.Set('chart.xticks', 5);
window.__rgraph_line__.Set('units.post', 'V');
}
return window.__rgraph_line__;
}
function drawGraph ()
{
// "cache" this in a local variable
var _RG = RGraph;
_RG.Clear(document.getElementById("cvs"));
var graph = getGraph('cvs', spectra);
graph.Draw();
socket.on ('connect', function () //Connects to Node Data Server
{
socket.on ('data', function (msg)
{
var VALUE = parseFloat(msg); // Convert message to float
spectra.push(VALUE); // Push to Graph Data Array
var SPAN = document.getElementById('sensorvalue');
var text = document.createTextNode(VALUE);
if(SPAN.childNodes.length == 0) { SPAN.appendChild(text) }
else { SPAN.firstChild.nodeValue = VALUE; }
if (spectra.length > 500) { spectra = _RG.array_shift(spectra); }
});
});
if (document.all && _RG.isIE8())
{ alert('[MSIE] Sorry, Internet Explorer 8 is not fast enough to support animated charts'); }
else
{
window.__rgraph_line__.original_data[0] = spectra;
setTimeout(drawGraph, 10); //Delay between Graph Updates
}
}
drawGraph();
socket.on( 'sff', function() { } );
function initspec(start,stop)
{ drawGraph();
socket.emit('initspec', start, stop );
}
function scanspec()
{ socket.emit('scanspec'); }
function resetspec()
{ socket.emit('resetspec'); }
function save(start,stop,spectra)
{ socket.emit('savespec', start, stop, spectra ); }
function openspec(openw)
{ drawGraph();
socket.emit('openspec', openw );
}
</script>
</head>
<body>
<div role="main">
Analog Out: <span id="sensorvalue"></span>
</div>
<form name="input" action="" method="post">
Start Wavelength: <input type="text" name="startwave" id="startw" ><br />
Stop Wavelength: <input type="text" name="stopwave" id="stopw" ><br />
Open Spectra <input type="value" name="openwave" id="openw" ><br />
<input type="button" value="reset" onClick=resetspec()>
<input type="button" value="intialise" onClick=initspec(startw.value,stopw.value)>
<input type="button" value="scan" onClick=scanspec()>
<input type="button" value="save" onClick=save(startw.value,stopw.value,spectra)>
<input type="button" value="open" onClick=openspec(openw.value)>
</form>
</body>
</div>
<footer id="footer" class="inner">Copyright © 2014
CEERI
<span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span>
</footer>
<script src="/spectra/javascripts/slash.js"></script>
<script src="/spectra/javascripts/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
(function($){
$('.fancybox').fancybox();
})(jQuery);
</script> <!-- Delete or comment this line to disable Fancybox -->
</body>
</html>
| Java |
> **Note**: this project is hosted on a [public repository](https://github.com/hhkaos/awesome-arcgis) where anyone can contribute. Learn how to [contribute in less than a minute](https://github.com/hhkaos/awesome-arcgis/blob/master/CONTRIBUTING.md#contributions).
# Scene services
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of contents**
- [Training](#training)
- [Videos](#videos)
- [Resources](#resources)
- [Utils](#utils)
- [News](#news)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Training
### Videos
|Event|Title|Length|
|---|---|---|
## Resources
Probably not all the resources are in this list, please use the [ArcGIS Search](https://esri-es.github.io/arcgis-search/) tool looking for: ["scene service"](https://esri-es.github.io/arcgis-search/?search="scene service"&utm_campaign=awesome-list&utm_source=awesome-list&utm_medium=page).
## Utils
## News
| Java |
package net.einsteinsci.betterbeginnings.items;
import net.einsteinsci.betterbeginnings.register.IBBName;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.HashSet;
import java.util.Set;
public abstract class ItemKnife extends ItemTool implements IBBName
{
public static final float DAMAGE = 3.0f;
public ItemKnife(ToolMaterial material)
{
super(DAMAGE, material, getBreakable());
}
public static Set getBreakable()
{
Set<Block> s = new HashSet<>();
// s.add(Blocks.log);
// s.add(Blocks.log2);
// s.add(Blocks.planks);
s.add(Blocks.pumpkin);
s.add(Blocks.lit_pumpkin);
s.add(Blocks.melon_block);
s.add(Blocks.clay);
s.add(Blocks.grass);
s.add(Blocks.mycelium);
s.add(Blocks.leaves);
s.add(Blocks.leaves2);
s.add(Blocks.brown_mushroom_block);
s.add(Blocks.red_mushroom_block);
s.add(Blocks.glass);
s.add(Blocks.glass_pane);
s.add(Blocks.soul_sand);
s.add(Blocks.stained_glass);
s.add(Blocks.stained_glass_pane);
s.add(Blocks.cactus);
return s;
}
@Override
public boolean shouldRotateAroundWhenRendering()
{
return true;
}
@Override
public int getHarvestLevel(ItemStack stack, String toolClass)
{
return toolMaterial.getHarvestLevel();
}
@Override
public Set<String> getToolClasses(ItemStack stack)
{
Set<String> res = new HashSet<>();
res.add("knife");
return res;
}
// ...which also requires this...
@Override
public ItemStack getContainerItem(ItemStack itemStack)
{
ItemStack result = itemStack.copy();
result.setItemDamage(itemStack.getItemDamage() + 1);
return result;
}
// Allows durability-based crafting.
@Override
public boolean hasContainerItem(ItemStack stack)
{
return true;
}
@Override
public abstract String getName();
}
| Java |
/* Copyright (c) 2008, 2009
* Juergen Weigert ([email protected])
* Michael Schroeder ([email protected])
* Micah Cowan ([email protected])
* Sadrul Habib Chowdhury ([email protected])
* Copyright (c) 1993-2002, 2003, 2005, 2006, 2007
* Juergen Weigert ([email protected])
* Michael Schroeder ([email protected])
* Copyright (c) 1987 Oliver Laumann
*
* 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, 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 (see the file COPYING); if not, see
* http://www.gnu.org/licenses/, or contact Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*
****************************************************************
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include "config.h"
#ifdef BUILTIN_TELNET
#include "screen.h"
extern Window *fore;
extern Layer *flayer;
extern int visual_bell;
extern char screenterm[];
extern int af;
static void TelReply(Window *, char *, int);
static void TelDocmd(Window *, int, int);
static void TelDosub(Window *);
// why TEL_DEFPORT has "
#define TEL_DEFPORT "23"
#define TEL_CONNECTING (-2)
#define TC_IAC 255
#define TC_DONT 254
#define TC_DO 253
#define TC_WONT 252
#define TC_WILL 251
#define TC_SB 250
#define TC_BREAK 243
#define TC_SE 240
#define TC_S "S b swWdDc"
#define TO_BINARY 0
#define TO_ECHO 1
#define TO_SGA 3
#define TO_TM 6
#define TO_TTYPE 24
#define TO_NAWS 31
#define TO_TSPEED 32
#define TO_LFLOW 33
#define TO_LINEMODE 34
#define TO_XDISPLOC 35
#define TO_NEWENV 39
#define TO_S "be c t wsf xE E"
static unsigned char tn_init[] = {
TC_IAC, TC_DO, TO_SGA,
TC_IAC, TC_WILL, TO_TTYPE,
TC_IAC, TC_WILL, TO_NAWS,
TC_IAC, TC_WILL, TO_LFLOW,
};
static void tel_connev_fn(Event *ev, char *data)
{
Window *p = (Window *)data;
if (connect(p->w_ptyfd, (struct sockaddr *)&p->w_telsa, sizeof(p->w_telsa)) && errno != EISCONN) {
char buf[1024];
buf[0] = ' ';
strncpy(buf + 1, strerror(errno), sizeof(buf) - 2);
buf[sizeof(buf) - 1] = 0;
WriteString(p, buf, strlen(buf));
WindowDied(p, 0, 0);
return;
}
WriteString(p, "connected.\r\n", 12);
evdeq(&p->w_telconnev);
p->w_telstate = 0;
}
int TelOpenAndConnect(Window *p)
{
int fd, on = 1;
char buf[256];
struct addrinfo hints, *res0, *res;
if (!(p->w_cmdargs[1])) {
Msg(0, "Usage: screen //telnet host [port]");
return -1;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = af;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(p->w_cmdargs[1], p->w_cmdargs[2] ? p->w_cmdargs[2] : TEL_DEFPORT, &hints, &res0)) {
Msg(0, "unknown host: %s", p->w_cmdargs[1]);
return -1;
}
for (res = res0; res; res = res->ai_next) {
if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) {
if (res->ai_next)
continue;
else {
Msg(errno, "TelOpenAndConnect: socket");
freeaddrinfo(res0);
return -1;
}
}
if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on)))
Msg(errno, "TelOpenAndConnect: setsockopt SO_OOBINLINE");
if (p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT))
snprintf(buf, 256, "Trying %s %s...", p->w_cmdargs[1], p->w_cmdargs[2]);
else
snprintf(buf, 256, "Trying %s...", p->w_cmdargs[1]);
WriteString(p, buf, strlen(buf));
if (connect(fd, res->ai_addr, res->ai_addrlen)) {
if (errno == EINPROGRESS) {
p->w_telstate = TEL_CONNECTING;
p->w_telconnev.fd = fd;
p->w_telconnev.handler = tel_connev_fn;
p->w_telconnev.data = (char *)p;
p->w_telconnev.type = EV_WRITE;
p->w_telconnev.priority = 1;
evenq(&p->w_telconnev);
} else {
close(fd);
if (res->ai_next)
continue;
else {
Msg(errno, "TelOpenAndConnect: connect");
freeaddrinfo(res0);
return -1;
}
}
} else
WriteString(p, "connected.\r\n", 12);
if (!(p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT)))
TelReply(p, (char *)tn_init, sizeof(tn_init));
p->w_ptyfd = fd;
memcpy(&p->w_telsa, &res->ai_addr, sizeof(res->ai_addr));
freeaddrinfo(res0);
return 0;
}
return -1;
}
int TelIsline(Window *p)
{
return !fore->w_telropts[TO_SGA];
}
void TelProcessLine(char **bufpp, int *lenp)
{
int echo = !fore->w_telropts[TO_ECHO];
unsigned char c;
char *tb;
int tl;
char *buf = *bufpp;
int l = *lenp;
while (l--) {
c = *(unsigned char *)buf++;
if (fore->w_telbufl + 2 >= IOSIZE) {
WBell(fore, visual_bell);
continue;
}
if (c == '\r') {
if (echo)
WriteString(fore, "\r\n", 2);
fore->w_telbuf[fore->w_telbufl++] = '\r';
fore->w_telbuf[fore->w_telbufl++] = '\n';
tb = fore->w_telbuf;
tl = fore->w_telbufl;
LayProcess(&tb, &tl);
fore->w_telbufl = 0;
continue;
}
if (c == '\b' && fore->w_telbufl > 0) {
if (echo) {
WriteString(fore, (char *)&c, 1);
WriteString(fore, " ", 1);
WriteString(fore, (char *)&c, 1);
}
fore->w_telbufl--;
}
if ((c >= 0x20 && c <= 0x7e) || c >= 0xa0) {
if (echo)
WriteString(fore, (char *)&c, 1);
fore->w_telbuf[fore->w_telbufl++] = c;
}
}
*lenp = 0;
}
int DoTelnet(char *buf, int *lenp, int f)
{
int echo = !fore->w_telropts[TO_ECHO];
int cmode = fore->w_telropts[TO_SGA];
int bin = fore->w_telropts[TO_BINARY];
char *p = buf, *sbuf;
int trunc = 0;
int c;
int l = *lenp;
sbuf = p;
while (l-- > 0) {
c = *(unsigned char *)p++;
if (c == TC_IAC || (c == '\r' && (l == 0 || *p != '\n') && cmode && !bin)) {
if (cmode && echo) {
WriteString(fore, sbuf, p - sbuf);
sbuf = p;
}
if (f-- <= 0) {
trunc++;
l--;
}
if (l < 0) {
p--; /* drop char */
break;
}
if (l)
bcopy(p, p + 1, l);
if (c == TC_IAC)
*p++ = c;
else if (c == '\r')
*p++ = 0;
else if (c == '\n') {
p[-1] = '\r';
*p++ = '\n';
}
}
}
*lenp = p - buf;
return trunc;
}
/* modifies data in-place, returns new length */
int TelIn(Window *p, char *buf, int len, int free)
{
char *rp, *wp;
int c;
rp = wp = buf;
while (len-- > 0) {
c = *(unsigned char *)rp++;
if (p->w_telstate >= TC_WILL && p->w_telstate <= TC_DONT) {
TelDocmd(p, p->w_telstate, c);
p->w_telstate = 0;
continue;
}
if (p->w_telstate == TC_SB || p->w_telstate == TC_SE) {
if (p->w_telstate == TC_SE && c == TC_IAC)
p->w_telsubidx--;
if (p->w_telstate == TC_SE && c == TC_SE) {
p->w_telsubidx--;
TelDosub(p);
p->w_telstate = 0;
continue;
}
if (p->w_telstate == TC_SB && c == TC_IAC)
p->w_telstate = TC_SE;
else
p->w_telstate = TC_SB;
p->w_telsubbuf[p->w_telsubidx] = c;
if (p->w_telsubidx < sizeof(p->w_telsubbuf) - 1)
p->w_telsubidx++;
continue;
}
if (p->w_telstate == TC_IAC) {
if ((c >= TC_WILL && c <= TC_DONT) || c == TC_SB) {
p->w_telsubidx = 0;
p->w_telstate = c;
continue;
}
p->w_telstate = 0;
if (c != TC_IAC)
continue;
} else if (c == TC_IAC) {
p->w_telstate = c;
continue;
}
if (p->w_telstate == '\r') {
p->w_telstate = 0;
if (c == 0)
continue; /* suppress trailing \0 */
} else if (c == '\n' && !p->w_telropts[TO_SGA]) {
/* oops... simulate terminal line mode: insert \r */
if (wp + 1 == rp) {
if (free-- > 0) {
if (len)
bcopy(rp, rp + 1, len);
rp++;
*wp++ = '\r';
}
} else
*wp++ = '\r';
}
if (c == '\r')
p->w_telstate = c;
*wp++ = c;
}
return wp - buf;
}
static void TelReply(Window *p, char *str, int len)
{
if (len <= 0)
return;
if (p->w_inlen + len > IOSIZE) {
Msg(0, "Warning: telnet protocol overrun!");
return;
}
bcopy(str, p->w_inbuf + p->w_inlen, len);
p->w_inlen += len;
}
static void TelDocmd(Window *p, int cmd, int opt)
{
unsigned char b[3];
int repl = 0;
switch (cmd) {
case TC_WILL:
if (p->w_telropts[opt] || opt == TO_TM)
return;
repl = TC_DONT;
if (opt == TO_ECHO || opt == TO_SGA || opt == TO_BINARY) {
p->w_telropts[opt] = 1;
/* setcon(); */
repl = TC_DO;
}
break;
case TC_WONT:
if (!p->w_telropts[opt] || opt == TO_TM)
return;
repl = TC_DONT;
p->w_telropts[opt] = 0;
break;
case TC_DO:
if (p->w_telmopts[opt])
return;
repl = TC_WONT;
if (opt == TO_TTYPE || opt == TO_SGA || opt == TO_BINARY || opt == TO_NAWS || opt == TO_TM
|| opt == TO_LFLOW) {
repl = TC_WILL;
p->w_telmopts[opt] = 1;
}
p->w_telmopts[TO_TM] = 0;
break;
case TC_DONT:
if (!p->w_telmopts[opt])
return;
repl = TC_WONT;
p->w_telmopts[opt] = 0;
break;
}
b[0] = TC_IAC;
b[1] = repl;
b[2] = opt;
TelReply(p, (char *)b, 3);
if (cmd == TC_DO && opt == TO_NAWS)
TelWindowSize(p);
}
static void TelDosub(Window *p)
{
char trepl[20 + 6 + 1];
int l;
switch (p->w_telsubbuf[0]) {
case TO_TTYPE:
if (p->w_telsubidx != 2 || p->w_telsubbuf[1] != 1)
return;
l = strlen(screenterm);
if (l >= 20)
break;
sprintf(trepl, "%c%c%c%c%s%c%c", TC_IAC, TC_SB, TO_TTYPE, 0, screenterm, TC_IAC, TC_SE);
TelReply(p, trepl, l + 6);
break;
case TO_LFLOW:
if (p->w_telsubidx != 2)
return;
break;
default:
break;
}
}
void TelBreak(Window *p)
{
static unsigned char tel_break[] = { TC_IAC, TC_BREAK };
TelReply(p, (char *)tel_break, 2);
}
void TelWindowSize(Window *p)
{
char s[20], trepl[20], *t;
int i;
if (p->w_width == 0 || p->w_height == 0 || !p->w_telmopts[TO_NAWS])
return;
sprintf(s, "%c%c%c%c%c%c%c%c%c", TC_SB, TC_SB, TO_NAWS, p->w_width / 256, p->w_width & 255, p->w_height / 256,
p->w_height & 255, TC_SE, TC_SE);
t = trepl;
for (i = 0; i < 9; i++)
if ((unsigned char)(*t++ = s[i]) == TC_IAC)
*t++ = TC_IAC;
trepl[0] = TC_IAC;
t[-2] = TC_IAC;
TelReply(p, trepl, t - trepl);
}
static char tc_s[] = TC_S;
static char to_s[] = TO_S;
void TelStatus(Window *p, char *buf, int l)
{
int i;
*buf++ = '[';
for (i = 0; to_s[i]; i++) {
if (to_s[i] == ' ' || p->w_telmopts[i] == 0)
continue;
*buf++ = to_s[i];
}
*buf++ = ':';
for (i = 0; to_s[i]; i++) {
if (to_s[i] == ' ' || p->w_telropts[i] == 0)
continue;
*buf++ = to_s[i];
}
if (p->w_telstate == TEL_CONNECTING)
buf[-1] = 'C';
else if (p->w_telstate && p->w_telstate != '\r') {
*buf++ = ':';
*buf++ = tc_s[p->w_telstate - TC_SE];
}
*buf++ = ']';
*buf = 0;
return;
}
#endif /* BUILTIN_TELNET */
| Java |
/****************************************************************************/
/// @file GUILaneSpeedTrigger.h
/// @author Daniel Krajzewicz
/// @author Jakob Erdmann
/// @author Michael Behrisch
/// @date Mon, 26.04.2004
/// @version $Id: GUILaneSpeedTrigger.h 13107 2012-12-02 13:57:34Z behrisch $
///
// Changes the speed allowed on a set of lanes (gui version)
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
// Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO 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.
//
/****************************************************************************/
#ifndef GUILaneSpeedTrigger_h
#define GUILaneSpeedTrigger_h
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <vector>
#include <string>
#include <microsim/trigger/MSLaneSpeedTrigger.h>
#include <utils/gui/globjects/GUIGlObject_AbstractAdd.h>
#include <utils/gui/globjects/GUIGLObjectPopupMenu.h>
#include <utils/foxtools/FXRealSpinDial.h>
#include <gui/GUIManipulator.h>
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class GUILaneSpeedTrigger
* @brief Changes the speed allowed on a set of lanes (gui version)
*
* This is the gui-version of the MSLaneSpeedTrigger-object
*/
class GUILaneSpeedTrigger
: public MSLaneSpeedTrigger,
public GUIGlObject_AbstractAdd {
public:
/** @brief Constructor
* @param[in] idStorage The gl-id storage for giving this object an gl-id
* @param[in] id The id of the lane speed trigger
* @param[in] destLanes List of lanes affected by this speed trigger
* @param[in] file Name of the file to read the speeds to set from
*/
GUILaneSpeedTrigger(const std::string& id,
const std::vector<MSLane*>& destLanes,
const std::string& file);
/** destructor */
~GUILaneSpeedTrigger();
/// @name inherited from GUIGlObject
//@{
/** @brief Returns an own popup-menu
*
* @param[in] app The application needed to build the popup-menu
* @param[in] parent The parent window needed to build the popup-menu
* @return The built popup-menu
* @see GUIGlObject::getPopUpMenu
*/
GUIGLObjectPopupMenu* getPopUpMenu(GUIMainWindow& app,
GUISUMOAbstractView& parent);
/** @brief Returns an own parameter window
*
* @param[in] app The application needed to build the parameter window
* @param[in] parent The parent window needed to build the parameter window
* @return The built parameter window
* @see GUIGlObject::getParameterWindow
*/
GUIParameterTableWindow* getParameterWindow(GUIMainWindow& app,
GUISUMOAbstractView& parent);
/** @brief Returns the boundary to which the view shall be centered in order to show the object
*
* @return The boundary the object is within
* @see GUIGlObject::getCenteringBoundary
*/
Boundary getCenteringBoundary() const;
/** @brief Draws the object
* @param[in] s The settings for the current view (may influence drawing)
* @see GUIGlObject::drawGL
*/
void drawGL(const GUIVisualizationSettings& s) const;
//@}
GUIManipulator* openManipulator(GUIMainWindow& app,
GUISUMOAbstractView& parent);
public:
class GUILaneSpeedTriggerPopupMenu : public GUIGLObjectPopupMenu {
FXDECLARE(GUILaneSpeedTriggerPopupMenu)
public:
GUILaneSpeedTriggerPopupMenu(GUIMainWindow& app,
GUISUMOAbstractView& parent, GUIGlObject& o);
~GUILaneSpeedTriggerPopupMenu();
/** @brief Called if the object's manipulator shall be shown */
long onCmdOpenManip(FXObject*, FXSelector, void*);
protected:
GUILaneSpeedTriggerPopupMenu() { }
};
class GUIManip_LaneSpeedTrigger : public GUIManipulator {
FXDECLARE(GUIManip_LaneSpeedTrigger)
public:
enum {
MID_USER_DEF = FXDialogBox::ID_LAST,
MID_PRE_DEF,
MID_OPTION,
MID_CLOSE,
ID_LAST
};
/// Constructor
GUIManip_LaneSpeedTrigger(GUIMainWindow& app,
const std::string& name, GUILaneSpeedTrigger& o,
int xpos, int ypos);
/// Destructor
virtual ~GUIManip_LaneSpeedTrigger();
long onCmdOverride(FXObject*, FXSelector, void*);
long onCmdClose(FXObject*, FXSelector, void*);
long onCmdUserDef(FXObject*, FXSelector, void*);
long onUpdUserDef(FXObject*, FXSelector, void*);
long onCmdPreDef(FXObject*, FXSelector, void*);
long onUpdPreDef(FXObject*, FXSelector, void*);
long onCmdChangeOption(FXObject*, FXSelector, void*);
private:
GUIMainWindow* myParent;
FXint myChosenValue;
FXDataTarget myChosenTarget;
SUMOReal mySpeed;
FXDataTarget mySpeedTarget;
FXRealSpinDial* myUserDefinedSpeed;
FXComboBox* myPredefinedValues;
GUILaneSpeedTrigger* myObject;
protected:
GUIManip_LaneSpeedTrigger() { }
};
private:
/// Definition of a positions container
typedef std::vector<Position> PosCont;
/// Definition of a rotation container
typedef std::vector<SUMOReal> RotCont;
private:
/// The positions in full-geometry mode
PosCont myFGPositions;
/// The rotations in full-geometry mode
RotCont myFGRotations;
/// The boundary of this rerouter
Boundary myBoundary;
/// The information whether the speed shall be shown in m/s or km/h
bool myShowAsKMH;
/// Storage for last value to avoid string recomputation
mutable SUMOReal myLastValue;
/// Storage for speed string to avoid recomputation
mutable std::string myLastValueString;
};
#endif
/****************************************************************************/
| Java |
/****************************************************************************/
/// @file MSEdge.cpp
/// @author Christian Roessel
/// @author Jakob Erdmann
/// @author Christoph Sommer
/// @author Daniel Krajzewicz
/// @author Laura Bieker
/// @author Michael Behrisch
/// @author Sascha Krieg
/// @date Tue, 06 Mar 2001
/// @version $Id: MSEdge.cpp 13107 2012-12-02 13:57:34Z behrisch $
///
// A road/street connecting two junctions
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
// Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO 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.
//
/****************************************************************************/
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <algorithm>
#include <iostream>
#include <cassert>
#include <utils/common/StringTokenizer.h>
#include <utils/options/OptionsCont.h>
#include "MSEdge.h"
#include "MSLane.h"
#include "MSLaneChanger.h"
#include "MSGlobals.h"
#include "MSVehicle.h"
#include "MSEdgeWeightsStorage.h"
#ifdef HAVE_INTERNAL
#include <mesosim/MELoop.h>
#include <mesosim/MESegment.h>
#include <mesosim/MEVehicle.h>
#endif
#ifdef CHECK_MEMORY_LEAKS
#include <foreign/nvwa/debug_new.h>
#endif // CHECK_MEMORY_LEAKS
// ===========================================================================
// static member definitions
// ===========================================================================
MSEdge::DictType MSEdge::myDict;
std::vector<MSEdge*> MSEdge::myEdges;
// ===========================================================================
// member method definitions
// ===========================================================================
MSEdge::MSEdge(const std::string& id, int numericalID,
const EdgeBasicFunction function,
const std::string& streetName) :
Named(id), myNumericalID(numericalID), myLanes(0),
myLaneChanger(0), myFunction(function), myVaporizationRequests(0),
myLastFailedInsertionTime(-1), myStreetName(streetName) {}
MSEdge::~MSEdge() {
delete myLaneChanger;
for (AllowedLanesCont::iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); i1++) {
delete(*i1).second;
}
for (ClassedAllowedLanesCont::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) {
for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) {
delete(*i1).second;
}
}
delete myLanes;
// Note: Lanes are delete using MSLane::clear();
}
void
MSEdge::initialize(std::vector<MSLane*>* lanes) {
assert(myFunction == EDGEFUNCTION_DISTRICT || lanes != 0);
myLanes = lanes;
if (myLanes && myLanes->size() > 1 && myFunction != EDGEFUNCTION_INTERNAL) {
myLaneChanger = new MSLaneChanger(myLanes, OptionsCont::getOptions().getBool("lanechange.allow-swap"));
}
}
void
MSEdge::closeBuilding() {
myAllowed[0] = new std::vector<MSLane*>();
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
myAllowed[0]->push_back(*i);
const MSLinkCont& lc = (*i)->getLinkCont();
for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
MSLane* toL = (*j)->getLane();
if (toL != 0) {
MSEdge& to = toL->getEdge();
//
if (std::find(mySuccessors.begin(), mySuccessors.end(), &to) == mySuccessors.end()) {
mySuccessors.push_back(&to);
}
if (std::find(to.myPredeccesors.begin(), to.myPredeccesors.end(), this) == to.myPredeccesors.end()) {
to.myPredeccesors.push_back(this);
}
//
if (myAllowed.find(&to) == myAllowed.end()) {
myAllowed[&to] = new std::vector<MSLane*>();
}
myAllowed[&to]->push_back(*i);
}
#ifdef HAVE_INTERNAL_LANES
toL = (*j)->getViaLane();
if (toL != 0) {
MSEdge& to = toL->getEdge();
to.myPredeccesors.push_back(this);
}
#endif
}
}
std::sort(mySuccessors.begin(), mySuccessors.end(), by_id_sorter());
rebuildAllowedLanes();
}
void
MSEdge::rebuildAllowedLanes() {
// clear myClassedAllowed.
// it will be rebuilt on demand
for (ClassedAllowedLanesCont::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) {
for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) {
delete(*i1).second;
}
}
myClassedAllowed.clear();
// rebuild myMinimumPermissions and myCombinedPermissions
myMinimumPermissions = SVCFreeForAll;
myCombinedPermissions = 0;
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
myMinimumPermissions &= (*i)->getPermissions();
myCombinedPermissions |= (*i)->getPermissions();
}
}
// ------------ Access to the edge's lanes
MSLane*
MSEdge::leftLane(const MSLane* const lane) const {
std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane);
if (laneIt == myLanes->end() || laneIt == myLanes->end() - 1) {
return 0;
}
return *(laneIt + 1);
}
MSLane*
MSEdge::rightLane(const MSLane* const lane) const {
std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane);
if (laneIt == myLanes->end() || laneIt == myLanes->begin()) {
return 0;
}
return *(laneIt - 1);
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(const MSEdge& destination, SUMOVehicleClass vclass) const {
return allowedLanes(&destination, vclass);
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(SUMOVehicleClass vclass) const {
return allowedLanes(0, vclass);
}
const std::vector<MSLane*>*
MSEdge::getAllowedLanesWithDefault(const AllowedLanesCont& c, const MSEdge* dest) const {
AllowedLanesCont::const_iterator it = c.find(dest);
if (it == c.end()) {
return 0;
}
return it->second;
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(const MSEdge* destination, SUMOVehicleClass vclass) const {
if ((myMinimumPermissions & vclass) == vclass) {
// all lanes allow vclass
return getAllowedLanesWithDefault(myAllowed, destination);
}
// look up cached result in myClassedAllowed
ClassedAllowedLanesCont::const_iterator i = myClassedAllowed.find(vclass);
if (i != myClassedAllowed.end()) {
// can use cached value
const AllowedLanesCont& c = (*i).second;
return getAllowedLanesWithDefault(c, destination);
} else {
// this vclass is requested for the first time. rebuild all destinations
// go through connected edges
for (AllowedLanesCont::const_iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); ++i1) {
const MSEdge* edge = i1->first;
const std::vector<MSLane*>* lanes = i1->second;
myClassedAllowed[vclass][edge] = new std::vector<MSLane*>();
// go through lanes approaching current edge
for (std::vector<MSLane*>::const_iterator i2 = lanes->begin(); i2 != lanes->end(); ++i2) {
// allows the current vehicle class?
if ((*i2)->allowsVehicleClass(vclass)) {
// -> may be used
myClassedAllowed[vclass][edge]->push_back(*i2);
}
}
// assert that 0 is returned if no connection is allowed for a class
if (myClassedAllowed[vclass][edge]->size() == 0) {
delete myClassedAllowed[vclass][edge];
myClassedAllowed[vclass][edge] = 0;
}
}
return myClassedAllowed[vclass][destination];
}
}
// ------------
SUMOTime
MSEdge::incVaporization(SUMOTime) {
++myVaporizationRequests;
return 0;
}
SUMOTime
MSEdge::decVaporization(SUMOTime) {
--myVaporizationRequests;
return 0;
}
MSLane*
MSEdge::getFreeLane(const std::vector<MSLane*>* allowed, const SUMOVehicleClass vclass) const {
if (allowed == 0) {
allowed = allowedLanes(vclass);
}
MSLane* res = 0;
if (allowed != 0) {
unsigned int noCars = INT_MAX;
for (std::vector<MSLane*>::const_iterator i = allowed->begin(); i != allowed->end(); ++i) {
if ((*i)->getVehicleNumber() < noCars) {
res = (*i);
noCars = (*i)->getVehicleNumber();
}
}
}
return res;
}
MSLane*
MSEdge::getDepartLane(const MSVehicle& veh) const {
switch (veh.getParameter().departLaneProcedure) {
case DEPART_LANE_GIVEN:
if ((int) myLanes->size() <= veh.getParameter().departLane || !(*myLanes)[veh.getParameter().departLane]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) {
return 0;
}
return (*myLanes)[veh.getParameter().departLane];
case DEPART_LANE_RANDOM:
return RandHelper::getRandomFrom(*allowedLanes(veh.getVehicleType().getVehicleClass()));
case DEPART_LANE_FREE:
return getFreeLane(0, veh.getVehicleType().getVehicleClass());
case DEPART_LANE_ALLOWED_FREE:
if (veh.getRoute().size() == 1) {
return getFreeLane(0, veh.getVehicleType().getVehicleClass());
} else {
return getFreeLane(allowedLanes(**(veh.getRoute().begin() + 1)), veh.getVehicleType().getVehicleClass());
}
case DEPART_LANE_BEST_FREE: {
const std::vector<MSVehicle::LaneQ>& bl = veh.getBestLanes(false, (*myLanes)[0]);
SUMOReal bestLength = -1;
for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) {
if ((*i).length > bestLength) {
bestLength = (*i).length;
}
}
std::vector<MSLane*>* bestLanes = new std::vector<MSLane*>();
for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) {
if ((*i).length == bestLength) {
bestLanes->push_back((*i).lane);
}
}
MSLane* ret = getFreeLane(bestLanes, veh.getVehicleType().getVehicleClass());
delete bestLanes;
return ret;
}
case DEPART_LANE_DEFAULT:
default:
break;
}
if (!(*myLanes)[0]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) {
return 0;
}
return (*myLanes)[0];
}
bool
MSEdge::insertVehicle(SUMOVehicle& v, SUMOTime time) const {
// when vaporizing, no vehicles are inserted...
if (isVaporizing()) {
return false;
}
#ifdef HAVE_INTERNAL
if (MSGlobals::gUseMesoSim) {
const SUMOVehicleParameter& pars = v.getParameter();
SUMOReal pos = 0.0;
switch (pars.departPosProcedure) {
case DEPART_POS_GIVEN:
if (pars.departPos >= 0.) {
pos = pars.departPos;
} else {
pos = pars.departPos + getLength();
}
if (pos < 0 || pos > getLength()) {
WRITE_WARNING("Invalid departPos " + toString(pos) + " given for vehicle '" +
v.getID() + "'. Inserting at lane end instead.");
pos = getLength();
}
break;
case DEPART_POS_RANDOM:
case DEPART_POS_RANDOM_FREE:
pos = RandHelper::rand(getLength());
break;
default:
break;
}
bool result = false;
MESegment* segment = MSGlobals::gMesoNet->getSegmentForEdge(*this, pos);
MEVehicle* veh = static_cast<MEVehicle*>(&v);
if (pars.departPosProcedure == DEPART_POS_FREE) {
while (segment != 0 && !result) {
result = segment->initialise(veh, time);
segment = segment->getNextSegment();
}
} else {
result = segment->initialise(veh, time);
}
return result;
}
#else
UNUSED_PARAMETER(time);
#endif
MSLane* insertionLane = getDepartLane(static_cast<MSVehicle&>(v));
return insertionLane != 0 && insertionLane->insertVehicle(static_cast<MSVehicle&>(v));
}
void
MSEdge::changeLanes(SUMOTime t) {
if (myFunction == EDGEFUNCTION_INTERNAL) {
return;
}
assert(myLaneChanger != 0);
myLaneChanger->laneChange(t);
}
#ifdef HAVE_INTERNAL_LANES
const MSEdge*
MSEdge::getInternalFollowingEdge(MSEdge* followerAfterInternal) const {
//@todo to be optimized
for (std::vector<MSLane*>::const_iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
MSLane* l = *i;
const MSLinkCont& lc = l->getLinkCont();
for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
MSLink* link = *j;
if (&link->getLane()->getEdge() == followerAfterInternal) {
if (link->getViaLane() != 0) {
return &link->getViaLane()->getEdge();
} else {
return 0; // network without internal links
}
}
}
}
return 0;
}
#endif
SUMOReal
MSEdge::getCurrentTravelTime(SUMOReal minSpeed) const {
assert(minSpeed > 0);
SUMOReal v = 0;
#ifdef HAVE_INTERNAL
if (MSGlobals::gUseMesoSim) {
MESegment* first = MSGlobals::gMesoNet->getSegmentForEdge(*this);
unsigned segments = 0;
do {
v += first->getMeanSpeed();
first = first->getNextSegment();
segments++;
} while (first != 0);
v /= (SUMOReal) segments;
} else {
#endif
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
v += (*i)->getMeanSpeed();
}
v /= (SUMOReal) myLanes->size();
#ifdef HAVE_INTERNAL
}
#endif
v = MAX2(minSpeed, v);
return getLength() / v;
}
bool
MSEdge::dictionary(const std::string& id, MSEdge* ptr) {
DictType::iterator it = myDict.find(id);
if (it == myDict.end()) {
// id not in myDict.
myDict[id] = ptr;
if (ptr->getNumericalID() != -1) {
while ((int)myEdges.size() < ptr->getNumericalID() + 1) {
myEdges.push_back(0);
}
myEdges[ptr->getNumericalID()] = ptr;
}
return true;
}
return false;
}
MSEdge*
MSEdge::dictionary(const std::string& id) {
DictType::iterator it = myDict.find(id);
if (it == myDict.end()) {
// id not in myDict.
return 0;
}
return it->second;
}
MSEdge*
MSEdge::dictionary(size_t id) {
assert(myEdges.size() > id);
return myEdges[id];
}
size_t
MSEdge::dictSize() {
return myDict.size();
}
size_t
MSEdge::numericalDictSize() {
return myEdges.size();
}
void
MSEdge::clear() {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) {
delete(*i).second;
}
myDict.clear();
}
void
MSEdge::insertIDs(std::vector<std::string>& into) {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) {
into.push_back((*i).first);
}
}
void
MSEdge::parseEdgesList(const std::string& desc, std::vector<const MSEdge*>& into,
const std::string& rid) {
if (desc[0] == BinaryFormatter::BF_ROUTE) {
std::istringstream in(desc, std::ios::binary);
char c;
in >> c;
FileHelpers::readEdgeVector(in, into, rid);
} else {
StringTokenizer st(desc);
parseEdgesList(st.getVector(), into, rid);
}
}
void
MSEdge::parseEdgesList(const std::vector<std::string>& desc, std::vector<const MSEdge*>& into,
const std::string& rid) {
for (std::vector<std::string>::const_iterator i = desc.begin(); i != desc.end(); ++i) {
const MSEdge* edge = MSEdge::dictionary(*i);
// check whether the edge exists
if (edge == 0) {
throw ProcessError("The edge '" + *i + "' within the route " + rid + " is not known."
+ "\n The route can not be build.");
}
into.push_back(edge);
}
}
SUMOReal
MSEdge::getDistanceTo(const MSEdge* other) const {
if (getLanes().size() > 0 && other->getLanes().size() > 0) {
return getLanes()[0]->getShape()[-1].distanceTo2D(other->getLanes()[0]->getShape()[0]);
} else {
return 0; // optimism is just right for astar
}
}
SUMOReal
MSEdge::getLength() const {
return getLanes()[0]->getLength();
}
SUMOReal
MSEdge::getSpeedLimit() const {
// @note lanes might have different maximum speeds in theory
return getLanes()[0]->getSpeedLimit();
}
SUMOReal
MSEdge::getVehicleMaxSpeed(const SUMOVehicle* const veh) const {
// @note lanes might have different maximum speeds in theory
return getLanes()[0]->getVehicleMaxSpeed(veh);
}
/****************************************************************************/
| Java |
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* OPCODE - Optimized Collision Detection
* Copyright (C) 2001 Pierre Terdiman
* Homepage: http://www.codercorner.com/Opcode.htm
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains base volume collider class.
* \file OPC_VolumeCollider.h
* \author Pierre Terdiman
* \date June, 2, 2001
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Include Guard
#ifndef __OPC_VOLUMECOLLIDER_H__
#define __OPC_VOLUMECOLLIDER_H__
struct VolumeCache
{
VolumeCache() : Model(null) {}
~VolumeCache() {}
IceCore::Container TouchedPrimitives; //!< Indices of touched primitives
const BaseModel* Model; //!< Owner
};
class VolumeCollider : public Collider
{
public:
// Constructor / Destructor
VolumeCollider();
virtual ~VolumeCollider() = 0;
// Collision report
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Gets the number of touched primitives after a collision query.
* \see GetContactStatus()
* \see GetTouchedPrimitives()
* \return the number of touched primitives
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline_ udword GetNbTouchedPrimitives() const { return mTouchedPrimitives ? mTouchedPrimitives->GetNbEntries() : 0; }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Gets the list of touched primitives after a collision query.
* \see GetContactStatus()
* \see GetNbTouchedPrimitives()
* \return the list of touched primitives (primitive indices)
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline_ const udword* GetTouchedPrimitives() const { return mTouchedPrimitives ? mTouchedPrimitives->GetEntries() : null; }
// Stats
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Stats: gets the number of Volume-BV overlap tests after a collision query.
* \see GetNbVolumePrimTests()
* \return the number of Volume-BV tests performed during last query
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline_ udword GetNbVolumeBVTests() const { return mNbVolumeBVTests; }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Stats: gets the number of Volume-Triangle overlap tests after a collision query.
* \see GetNbVolumeBVTests()
* \return the number of Volume-Triangle tests performed during last query
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline_ udword GetNbVolumePrimTests() const { return mNbVolumePrimTests; }
// Settings
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Validates current settings. You should call this method after all the settings / callbacks have been defined for a collider.
* \return null if everything is ok, else a string describing the problem
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
override(Collider) const char* ValidateSettings();
protected:
// Touched primitives
IceCore::Container* mTouchedPrimitives; //!< List of touched primitives
// Precompured scale cache
IceMaths::Point mLocalScale; //!< Collision model's local scale (stripped off from its matrix)
// Dequantization coeffs
IceMaths::Point mCenterCoeff;
IceMaths::Point mExtentsCoeff;
// Stats
udword mNbVolumeBVTests; //!< Number of Volume-BV tests
udword mNbVolumePrimTests; //!< Number of Volume-Primitive tests
// Internal methods
void _Dump(const AABBCollisionNode* node);
void _Dump(const AABBNoLeafNode* node);
void _Dump(const AABBQuantizedNode* node);
void _Dump(const AABBQuantizedNoLeafNode* node);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Initializes a query
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
override(Collider) inline_ void InitQuery()
{
// Reset stats & contact status
mNbVolumeBVTests = 0;
mNbVolumePrimTests = 0;
Collider::InitQuery();
}
inline_ BOOL IsCacheValid(VolumeCache& cache)
{
// We're going to do a volume-vs-model query.
if(cache.Model!=mCurrentModel)
{
// Cached list was for another model so we can't keep it
// Keep track of new owner and reset cache
cache.Model = mCurrentModel;
return FALSE;
}
else
{
// Same models, no problem
return TRUE;
}
}
};
#endif // __OPC_VOLUMECOLLIDER_H__
| Java |
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 4.7.1
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: [email protected]
Follow: www.twitter.com/keenthemes
Dribbble: www.dribbble.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>Metronic Admin Theme #3 | Fixed Top Bar</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin Theme #3 for " name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="../assets/global/css/components-rounded.min.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="../assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<link href="../assets/layouts/layout3/css/layout.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/layouts/layout3/css/themes/default.min.css" rel="stylesheet" type="text/css" id="style_color" />
<link href="../assets/layouts/layout3/css/custom.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="favicon.ico" /> </head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-header-top-fixed">
<div class="page-wrapper">
<div class="page-wrapper-row">
<div class="page-wrapper-top">
<!-- BEGIN HEADER -->
<div class="page-header">
<!-- BEGIN HEADER TOP -->
<div class="page-header-top">
<div class="container">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../assets/layouts/layout3/img/logo-default.jpg" alt="logo" class="logo-default">
</a>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler"></a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-hoverable" class after "dropdown" and remove data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to enable hover dropdown mode -->
<!-- DOC: Remove "dropdown-hoverable" and add data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to the below A element with dropdown-toggle class -->
<li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-default">7</span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have
<strong>12 pending</strong> tasks</h3>
<a href="app_todo.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span> New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span> Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span> Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span> Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span> System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<!-- BEGIN TODO DROPDOWN -->
<li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-default">3</span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have
<strong>12 pending</strong> tasks</h3>
<a href="app_todo_2.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">65% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">98% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">10% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">58% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">85% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">38% Complete</span>
</span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<li class="droddown dropdown-separator">
<span class="separator"></span>
</li>
<!-- BEGIN INBOX DROPDOWN -->
<li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="circle">3</span>
<span class="corner"></span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have
<strong>7 New</strong> Messages</h3>
<a href="app_inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<li class="dropdown dropdown-user dropdown-dark">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<img alt="" class="img-circle" src="../assets/layouts/layout3/img/avatar9.jpg">
<span class="username username-hide-mobile">Nick</span>
</a>
<ul class="dropdown-menu dropdown-menu-default">
<li>
<a href="page_user_profile_1.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="app_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="app_inbox.html">
<i class="icon-envelope-open"></i> My Inbox
<span class="badge badge-danger"> 3 </span>
</a>
</li>
<li>
<a href="app_todo_2.html">
<i class="icon-rocket"></i> My Tasks
<span class="badge badge-success"> 7 </span>
</a>
</li>
<li class="divider"> </li>
<li>
<a href="page_user_lock_1.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="page_user_login_1.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
<!-- BEGIN QUICK SIDEBAR TOGGLER -->
<li class="dropdown dropdown-extended quick-sidebar-toggler">
<span class="sr-only">Toggle Quick Sidebar</span>
<i class="icon-logout"></i>
</li>
<!-- END QUICK SIDEBAR TOGGLER -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
</div>
<!-- END HEADER TOP -->
<!-- BEGIN HEADER MENU -->
<div class="page-header-menu">
<div class="container">
<!-- BEGIN HEADER SEARCH BOX -->
<form class="search-form" action="page_general_search.html" method="GET">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="query">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit">
<i class="icon-magnifier"></i>
</a>
</span>
</div>
</form>
<!-- END HEADER SEARCH BOX -->
<!-- BEGIN MEGA MENU -->
<!-- DOC: Apply "hor-menu-light" class after the "hor-menu" class below to have a horizontal menu with white background -->
<!-- DOC: Remove data-hover="dropdown" and data-close-others="true" attributes below to disable the dropdown opening on mouse hover -->
<div class="hor-menu ">
<ul class="nav navbar-nav">
<li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown ">
<a href="javascript:;"> Dashboard
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class=" ">
<a href="index.html" class="nav-link ">
<i class="icon-bar-chart"></i> Default Dashboard
<span class="badge badge-success">1</span>
</a>
</li>
<li aria-haspopup="true" class=" ">
<a href="dashboard_2.html" class="nav-link ">
<i class="icon-bulb"></i> Dashboard 2 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="dashboard_3.html" class="nav-link ">
<i class="icon-graph"></i> Dashboard 3
<span class="badge badge-danger">3</span>
</a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown ">
<a href="javascript:;"> UI Features
<span class="arrow"></span>
</a>
<ul class="dropdown-menu" style="min-width: 710px">
<li>
<div class="mega-menu-content">
<div class="row">
<div class="col-md-4">
<ul class="mega-menu-submenu">
<li>
<a href="ui_colors.html"> Color Library </a>
</li>
<li>
<a href="ui_metronic_grid.html"> Metronic Grid System </a>
</li>
<li>
<a href="ui_general.html"> General Components </a>
</li>
<li>
<a href="ui_buttons.html"> Buttons </a>
</li>
<li>
<a href="ui_buttons_spinner.html"> Spinner Buttons </a>
</li>
<li>
<a href="ui_confirmations.html"> Popover Confirmations </a>
</li>
<li>
<a href="ui_sweetalert.html"> Bootstrap Sweet Alerts </a>
</li>
<li>
<a href="ui_icons.html"> Font Icons </a>
</li>
<li>
<a href="ui_socicons.html"> Social Icons </a>
</li>
<li>
<a href="ui_typography.html"> Typography </a>
</li>
<li>
<a href="ui_tabs_accordions_navs.html"> Tabs, Accordions & Navs </a>
</li>
<li>
<a href="ui_tree.html"> Tree View </a>
</li>
<li>
<a href="maps_google.html"> Google Maps </a>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="mega-menu-submenu">
<li>
<a href="maps_vector.html"> Vector Maps </a>
</li>
<li>
<a href="ui_timeline.html"> Timeline 1 </a>
</li>
<li>
<a href="ui_timeline_2.html"> Timeline 2 </a>
</li>
<li>
<a href="ui_timeline_horizontal.html"> Horizontal Timeline </a>
</li>
<li>
<a href="ui_page_progress_style_1.html"> Page Progress Bar - Flash </a>
</li>
<li>
<a href="ui_page_progress_style_2.html"> Page Progress Bar - Big Counter </a>
</li>
<li>
<a href="ui_blockui.html"> Block UI </a>
</li>
<li>
<a href="ui_bootstrap_growl.html"> Bootstrap Growl Notifications </a>
</li>
<li>
<a href="ui_notific8.html"> Notific8 Notifications </a>
</li>
<li>
<a href="ui_toastr.html"> Toastr Notifications </a>
</li>
<li>
<a href="ui_bootbox.html"> Bootbox Dialogs </a>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="mega-menu-submenu">
<li>
<a href="ui_alerts_api.html"> Metronic Alerts API </a>
</li>
<li>
<a href="ui_session_timeout.html"> Session Timeout </a>
</li>
<li>
<a href="ui_idle_timeout.html"> User Idle Timeout </a>
</li>
<li>
<a href="ui_modals.html"> Modals </a>
</li>
<li>
<a href="ui_extended_modals.html"> Extended Modals </a>
</li>
<li>
<a href="ui_tiles.html"> Tiles </a>
</li>
<li>
<a href="ui_datepaginator.html"> Date Paginator </a>
</li>
<li>
<a href="ui_nestable.html"> Nestable List </a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown active">
<a href="javascript:;"> Layouts
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class=" ">
<a href="layout_mega_menu_light.html" class="nav-link "> Light Mega Menu </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_top_bar_light.html" class="nav-link "> Light Top Bar Dropdowns </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_fluid_page.html" class="nav-link "> Fluid Page </a>
</li>
<li aria-haspopup="true" class=" active">
<a href="layout_top_bar_fixed.html" class="nav-link active"> Fixed Top Bar </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_mega_menu_fixed.html" class="nav-link "> Fixed Mega Menu </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_disabled_menu.html" class="nav-link "> Disabled Menu Links </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="layout_blank_page.html" class="nav-link "> Blank Page </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown mega-menu-dropdown mega-menu-full">
<a href="javascript:;"> Components
<span class="arrow"></span>
</a>
<ul class="dropdown-menu" style="min-width: ">
<li>
<div class="mega-menu-content">
<div class="row">
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 1</h3>
</li>
<li>
<a href="components_date_time_pickers.html"> Date & Time Pickers </a>
</li>
<li>
<a href="components_color_pickers.html"> Color Pickers </a>
</li>
<li>
<a href="components_select2.html"> Select2 Dropdowns </a>
</li>
<li>
<a href="components_bootstrap_multiselect_dropdown.html"> Bootstrap Multiselect Dropdowns </a>
</li>
<li>
<a href="components_bootstrap_select.html"> Bootstrap Select </a>
</li>
<li>
<a href="components_multi_select.html"> Bootstrap Multiple Select </a>
</li>
</ul>
</div>
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 2</h3>
</li>
<li>
<a href="components_bootstrap_select_splitter.html"> Select Splitter </a>
</li>
<li>
<a href="components_clipboard.html"> Clipboard </a>
</li>
<li>
<a href="components_typeahead.html"> Typeahead Autocomplete </a>
</li>
<li>
<a href="components_bootstrap_tagsinput.html"> Bootstrap Tagsinput </a>
</li>
<li>
<a href="components_bootstrap_switch.html"> Bootstrap Switch </a>
</li>
<li>
<a href="components_bootstrap_maxlength.html"> Bootstrap Maxlength </a>
</li>
</ul>
</div>
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 3</h3>
</li>
<li>
<a href="components_bootstrap_fileinput.html"> Bootstrap File Input </a>
</li>
<li>
<a href="components_bootstrap_touchspin.html"> Bootstrap Touchspin </a>
</li>
<li>
<a href="components_form_tools.html"> Form Widgets & Tools </a>
</li>
<li>
<a href="components_context_menu.html"> Context Menu </a>
</li>
<li>
<a href="components_editors.html"> Markdown & WYSIWYG Editors </a>
</li>
</ul>
</div>
<div class="col-md-3">
<ul class="mega-menu-submenu">
<li>
<h3>Components 4</h3>
</li>
<li>
<a href="components_code_editors.html"> Code Editors </a>
</li>
<li>
<a href="components_ion_sliders.html"> Ion Range Sliders </a>
</li>
<li>
<a href="components_noui_sliders.html"> NoUI Range Sliders </a>
</li>
<li>
<a href="components_knob_dials.html"> Knob Circle Dials </a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown ">
<a href="javascript:;"> More
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-settings"></i> Form Stuff
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="form_controls.html" class="nav-link "> Bootstrap Form
<br>Controls </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_controls_md.html" class="nav-link "> Material Design
<br>Form Controls </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_validation.html" class="nav-link "> Form Validation </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_validation_states_md.html" class="nav-link "> Material Design
<br>Form Validation States </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_validation_md.html" class="nav-link "> Material Design
<br>Form Validation </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_layouts.html" class="nav-link "> Form Layouts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_repeater.html" class="nav-link "> Form Repeater </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_input_mask.html" class="nav-link "> Form Input Mask </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_editable.html" class="nav-link "> Form X-editable </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_wizard.html" class="nav-link "> Form Wizard </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_icheck.html" class="nav-link "> iCheck Controls </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_image_crop.html" class="nav-link "> Image Cropping </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_fileupload.html" class="nav-link "> Multiple File Upload </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="form_dropzone.html" class="nav-link "> Dropzone File Upload </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-briefcase"></i> Tables
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="table_static_basic.html" class="nav-link "> Basic Tables </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="table_static_responsive.html" class="nav-link "> Responsive Tables </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="table_bootstrap.html" class="nav-link "> Bootstrap Tables </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle"> Datatables
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="table_datatables_managed.html" class="nav-link "> Managed Datatables </a>
</li>
<li class="">
<a href="table_datatables_buttons.html" class="nav-link "> Buttons Extension </a>
</li>
<li class="">
<a href="table_datatables_colreorder.html" class="nav-link "> Colreorder Extension </a>
</li>
<li class="">
<a href="table_datatables_rowreorder.html" class="nav-link "> Rowreorder Extension </a>
</li>
<li class="">
<a href="table_datatables_scroller.html" class="nav-link "> Scroller Extension </a>
</li>
<li class="">
<a href="table_datatables_fixedheader.html" class="nav-link "> FixedHeader Extension </a>
</li>
<li class="">
<a href="table_datatables_responsive.html" class="nav-link "> Responsive Extension </a>
</li>
<li class="">
<a href="table_datatables_editable.html" class="nav-link "> Editable Datatables </a>
</li>
<li class="">
<a href="table_datatables_ajax.html" class="nav-link "> Ajax Datatables </a>
</li>
</ul>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="?p=" class="nav-link nav-toggle ">
<i class="icon-wallet"></i> Portlets
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="portlet_boxed.html" class="nav-link "> Boxed Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_light.html" class="nav-link "> Light Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_solid.html" class="nav-link "> Solid Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_ajax.html" class="nav-link "> Ajax Portlets </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="portlet_draggable.html" class="nav-link "> Draggable Portlets </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="?p=" class="nav-link nav-toggle ">
<i class="icon-settings"></i> Elements
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="elements_steps.html" class="nav-link "> Steps </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_lists.html" class="nav-link "> Lists </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_ribbons.html" class="nav-link "> Ribbons </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_overlay.html" class="nav-link "> Overlays </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="elements_cards.html" class="nav-link "> User Cards </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-bar-chart"></i> Charts
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="charts_amcharts.html" class="nav-link "> amChart </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_flotcharts.html" class="nav-link "> Flot Charts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_flowchart.html" class="nav-link "> Flow Charts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_google.html" class="nav-link "> Google Charts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_echarts.html" class="nav-link "> eCharts </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="charts_morris.html" class="nav-link "> Morris Charts </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle"> HighCharts
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="charts_highcharts.html" class="nav-link " target="_blank"> HighCharts </a>
</li>
<li class="">
<a href="charts_highstock.html" class="nav-link " target="_blank"> HighStock </a>
</li>
<li class="">
<a href="charts_highmaps.html" class="nav-link " target="_blank"> HighMaps </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li aria-haspopup="true" class="menu-dropdown classic-menu-dropdown ">
<a href="javascript:;">
<i class="icon-briefcase"></i> Pages
<span class="arrow"></span>
</a>
<ul class="dropdown-menu pull-left">
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-basket"></i> eCommerce
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="ecommerce_index.html" class="nav-link ">
<i class="icon-home"></i> Dashboard </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="ecommerce_orders.html" class="nav-link ">
<i class="icon-basket"></i> Orders </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="ecommerce_orders_view.html" class="nav-link ">
<i class="icon-tag"></i> Order View </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="ecommerce_products.html" class="nav-link ">
<i class="icon-graph"></i> Products </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="ecommerce_products_edit.html" class="nav-link ">
<i class="icon-graph"></i> Product Edit </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-docs"></i> Apps
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="app_todo.html" class="nav-link ">
<i class="icon-clock"></i> Todo 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_todo_2.html" class="nav-link ">
<i class="icon-check"></i> Todo 2 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_inbox.html" class="nav-link ">
<i class="icon-envelope"></i> Inbox </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_calendar.html" class="nav-link ">
<i class="icon-calendar"></i> Calendar </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="app_ticket.html" class="nav-link ">
<i class="icon-notebook"></i> Support </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-user"></i> User
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="page_user_profile_1.html" class="nav-link ">
<i class="icon-user"></i> Profile 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_profile_1_account.html" class="nav-link ">
<i class="icon-user-female"></i> Profile 1 Account </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_profile_1_help.html" class="nav-link ">
<i class="icon-user-following"></i> Profile 1 Help </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_profile_2.html" class="nav-link ">
<i class="icon-users"></i> Profile 2 </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-notebook"></i> Login
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="page_user_login_1.html" class="nav-link " target="_blank"> Login Page 1 </a>
</li>
<li class="">
<a href="page_user_login_2.html" class="nav-link " target="_blank"> Login Page 2 </a>
</li>
<li class="">
<a href="page_user_login_3.html" class="nav-link " target="_blank"> Login Page 3 </a>
</li>
<li class="">
<a href="page_user_login_4.html" class="nav-link " target="_blank"> Login Page 4 </a>
</li>
<li class="">
<a href="page_user_login_5.html" class="nav-link " target="_blank"> Login Page 5 </a>
</li>
<li class="">
<a href="page_user_login_6.html" class="nav-link " target="_blank"> Login Page 6 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_lock_1.html" class="nav-link " target="_blank">
<i class="icon-lock"></i> Lock Screen 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_user_lock_2.html" class="nav-link " target="_blank">
<i class="icon-lock-open"></i> Lock Screen 2 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-social-dribbble"></i> General
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="page_general_about.html" class="nav-link ">
<i class="icon-info"></i> About </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_contact.html" class="nav-link ">
<i class="icon-call-end"></i> Contact </a>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-notebook"></i> Portfolio
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="page_general_portfolio_1.html" class="nav-link "> Portfolio 1 </a>
</li>
<li class="">
<a href="page_general_portfolio_2.html" class="nav-link "> Portfolio 2 </a>
</li>
<li class="">
<a href="page_general_portfolio_3.html" class="nav-link "> Portfolio 3 </a>
</li>
<li class="">
<a href="page_general_portfolio_4.html" class="nav-link "> Portfolio 4 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-magnifier"></i> Search
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li class="">
<a href="page_general_search.html" class="nav-link "> Search 1 </a>
</li>
<li class="">
<a href="page_general_search_2.html" class="nav-link "> Search 2 </a>
</li>
<li class="">
<a href="page_general_search_3.html" class="nav-link "> Search 3 </a>
</li>
<li class="">
<a href="page_general_search_4.html" class="nav-link "> Search 4 </a>
</li>
<li class="">
<a href="page_general_search_5.html" class="nav-link "> Search 5 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_pricing.html" class="nav-link ">
<i class="icon-tag"></i> Pricing </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_faq.html" class="nav-link ">
<i class="icon-wrench"></i> FAQ </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_blog.html" class="nav-link ">
<i class="icon-pencil"></i> Blog </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_blog_post.html" class="nav-link ">
<i class="icon-note"></i> Blog Post </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_invoice.html" class="nav-link ">
<i class="icon-envelope"></i> Invoice </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_general_invoice_2.html" class="nav-link ">
<i class="icon-envelope"></i> Invoice 2 </a>
</li>
</ul>
</li>
<li aria-haspopup="true" class="dropdown-submenu ">
<a href="javascript:;" class="nav-link nav-toggle ">
<i class="icon-settings"></i> System
<span class="arrow"></span>
</a>
<ul class="dropdown-menu">
<li aria-haspopup="true" class=" ">
<a href="page_system_coming_soon.html" class="nav-link " target="_blank"> Coming Soon </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_404_1.html" class="nav-link "> 404 Page 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_404_2.html" class="nav-link " target="_blank"> 404 Page 2 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_404_3.html" class="nav-link " target="_blank"> 404 Page 3 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_500_1.html" class="nav-link "> 500 Page 1 </a>
</li>
<li aria-haspopup="true" class=" ">
<a href="page_system_500_2.html" class="nav-link " target="_blank"> 500 Page 2 </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- END MEGA MENU -->
</div>
</div>
<!-- END HEADER MENU -->
</div>
<!-- END HEADER -->
</div>
</div>
<div class="page-wrapper-row full-height">
<div class="page-wrapper-middle">
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Fixed Top Bar </h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
<!-- BEGIN THEME PANEL -->
<div class="btn-group btn-theme-panel">
<a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown">
<i class="icon-settings"></i>
</a>
<div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<h3>THEME COLORS</h3>
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<ul class="theme-colors">
<li class="theme-color theme-color-default" data-theme="default">
<span class="theme-color-view"></span>
<span class="theme-color-name">Default</span>
</li>
<li class="theme-color theme-color-blue-hoki" data-theme="blue-hoki">
<span class="theme-color-view"></span>
<span class="theme-color-name">Blue Hoki</span>
</li>
<li class="theme-color theme-color-blue-steel" data-theme="blue-steel">
<span class="theme-color-view"></span>
<span class="theme-color-name">Blue Steel</span>
</li>
<li class="theme-color theme-color-yellow-orange" data-theme="yellow-orange">
<span class="theme-color-view"></span>
<span class="theme-color-name">Orange</span>
</li>
<li class="theme-color theme-color-yellow-crusta" data-theme="yellow-crusta">
<span class="theme-color-view"></span>
<span class="theme-color-name">Yellow Crusta</span>
</li>
</ul>
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
<ul class="theme-colors">
<li class="theme-color theme-color-green-haze" data-theme="green-haze">
<span class="theme-color-view"></span>
<span class="theme-color-name">Green Haze</span>
</li>
<li class="theme-color theme-color-red-sunglo" data-theme="red-sunglo">
<span class="theme-color-view"></span>
<span class="theme-color-name">Red Sunglo</span>
</li>
<li class="theme-color theme-color-red-intense" data-theme="red-intense">
<span class="theme-color-view"></span>
<span class="theme-color-name">Red Intense</span>
</li>
<li class="theme-color theme-color-purple-plum" data-theme="purple-plum">
<span class="theme-color-view"></span>
<span class="theme-color-name">Purple Plum</span>
</li>
<li class="theme-color theme-color-purple-studio" data-theme="purple-studio">
<span class="theme-color-view"></span>
<span class="theme-color-name">Purple Studio</span>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 seperator">
<h3>LAYOUT</h3>
<ul class="theme-settings">
<li> Theme Style
<select class="theme-setting theme-setting-style form-control input-sm input-small input-inline tooltips" data-original-title="Change theme style" data-container="body" data-placement="left">
<option value="boxed" selected="selected">Square corners</option>
<option value="rounded">Rounded corners</option>
</select>
</li>
<li> Layout
<select class="theme-setting theme-setting-layout form-control input-sm input-small input-inline tooltips" data-original-title="Change layout type" data-container="body" data-placement="left">
<option value="boxed" selected="selected">Boxed</option>
<option value="fluid">Fluid</option>
</select>
</li>
<li> Top Menu Style
<select class="theme-setting theme-setting-top-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change top menu dropdowns style" data-container="body"
data-placement="left">
<option value="dark" selected="selected">Dark</option>
<option value="light">Light</option>
</select>
</li>
<li> Top Menu Mode
<select class="theme-setting theme-setting-top-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) top menu" data-container="body"
data-placement="left">
<option value="fixed">Fixed</option>
<option value="not-fixed" selected="selected">Not Fixed</option>
</select>
</li>
<li> Mega Menu Style
<select class="theme-setting theme-setting-mega-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change mega menu dropdowns style" data-container="body"
data-placement="left">
<option value="dark" selected="selected">Dark</option>
<option value="light">Light</option>
</select>
</li>
<li> Mega Menu Mode
<select class="theme-setting theme-setting-mega-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) mega menu" data-container="body"
data-placement="left">
<option value="fixed" selected="selected">Fixed</option>
<option value="not-fixed">Not Fixed</option>
</select>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- END THEME PANEL -->
</div>
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE CONTENT BODY -->
<div class="page-content">
<div class="container">
<!-- BEGIN PAGE BREADCRUMBS -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span>Layouts</span>
</li>
</ul>
<!-- END PAGE BREADCRUMBS -->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="page-content-inner">
<div class="note note-info">
<p> To set fixed top bar apply <code>page-header-top-fixed</code> to the body element. </p>
</div>
<div class="portlet light portlet-fit ">
<div class="portlet-title">
<div class="caption">
<i class=" icon-layers font-green"></i>
<span class="caption-subject font-green bold uppercase">Basic Portlet</span>
</div>
<div class="actions">
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-cloud-upload"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-wrench"></i>
</a>
<a class="btn btn-circle btn-icon-only btn-default" href="javascript:;">
<i class="icon-trash"></i>
</a>
</div>
</div>
<div class="portlet-body">
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? </p>
<p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any
code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in
app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which
is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering
if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d
love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose
or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing
UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that
I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi!
This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. </p>
<p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend
for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI!
Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element
that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks
a ton! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any
code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in
app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which
is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering
if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d
love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. </p> Thanks a ton!height of the window and adjusts the height of an element that I could re-purpose
or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing
UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that
I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi!
This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. </p>
<p> I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element that I could re-purpose or extend
for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks a ton!Hi! This is an amazing UI!
Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical space between the
fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the height of an element
that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions you may have. Thanks
a ton! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
<p> Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a way to make portlets fill the vertical
space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the height of the window and adjusts the
height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever else. Otherwise any other suggestions
you may have. Thanks a ton!Hi! This is an amazing UI! Is there a way to turn sidebar completely off with a simple body class, like that which is used to minimize the sidebar? Also, I’m looking for a
way to make portlets fill the vertical space between the fixed header and fixed footer. I know that full height divs are a chore, but I’m wondering if you have already written any code that checks the
height of the window and adjusts the height of an element that I could re-purpose or extend for these full height content areas? If you have, I’d love a tip on where to find it in app.js or wherever
else. Otherwise any other suggestions you may have. Thanks a ton!Hi! </p>
</div>
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT BODY -->
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<div class="page-quick-sidebar-wrapper" data-close-on-body-click="false">
<div class="page-quick-sidebar">
<ul class="nav nav-tabs">
<li class="active">
<a href="javascript:;" data-target="#quick_sidebar_tab_1" data-toggle="tab"> Users
<span class="badge badge-danger">2</span>
</a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_2" data-toggle="tab"> Alerts
<span class="badge badge-success">7</span>
</a>
</li>
<li class="dropdown">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-bell"></i> Alerts </a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-info"></i> Notifications </a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-speech"></i> Activities </a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-settings"></i> Settings </a>
</li>
</ul>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active page-quick-sidebar-chat" id="quick_sidebar_tab_1">
<div class="page-quick-sidebar-chat-users" data-rail-color="#ddd" data-wrapper-class="page-quick-sidebar-list">
<h3 class="list-heading">Staff</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-success">8</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar3.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Bob Nilson</h4>
<div class="media-heading-sub"> Project Manager </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar1.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Nick Larson</h4>
<div class="media-heading-sub"> Art Director </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">3</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar4.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Hubert</h4>
<div class="media-heading-sub"> CTO </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar2.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ella Wong</h4>
<div class="media-heading-sub"> CEO </div>
</div>
</li>
</ul>
<h3 class="list-heading">Customers</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-warning">2</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar6.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lara Kunis</h4>
<div class="media-heading-sub"> CEO, Loop Inc </div>
<div class="media-heading-small"> Last seen 03:10 AM </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="label label-sm label-success">new</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar7.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ernie Kyllonen</h4>
<div class="media-heading-sub"> Project Manager,
<br> SmartBizz PTL </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar8.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lisa Stone</h4>
<div class="media-heading-sub"> CTO, Keort Inc </div>
<div class="media-heading-small"> Last seen 13:10 PM </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-success">7</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar9.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Portalatin</h4>
<div class="media-heading-sub"> CFO, H&D LTD </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar10.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Irina Savikova</h4>
<div class="media-heading-sub"> CEO, Tizda Motors Inc </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">4</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar11.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Maria Gomez</h4>
<div class="media-heading-sub"> Manager, Infomatic Inc </div>
<div class="media-heading-small"> Last seen 03:10 AM </div>
</div>
</li>
</ul>
</div>
<div class="page-quick-sidebar-item">
<div class="page-quick-sidebar-chat-user">
<div class="page-quick-sidebar-nav">
<a href="javascript:;" class="page-quick-sidebar-back-to-list">
<i class="icon-arrow-left"></i>Back</a>
</div>
<div class="page-quick-sidebar-chat-user-messages">
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body"> When could you send me the report ? </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:15</span>
<span class="body"> Its almost done. I will be sending it shortly </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body"> Alright. Thanks! :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:16</span>
<span class="body"> You are most welcome. Sorry for the delay. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> No probs. Just take your time :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body"> Alright. I just emailed it to you. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> Great! Thanks. Will check it right away. </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body"> Please let me know if you have any comment. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span>
</div>
</div>
</div>
<div class="page-quick-sidebar-chat-user-form">
<div class="input-group">
<input type="text" class="form-control" placeholder="Type a message here...">
<div class="input-group-btn">
<button type="button" class="btn green">
<i class="icon-paper-clip"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane page-quick-sidebar-alerts" id="quick_sidebar_tab_2">
<div class="page-quick-sidebar-alerts-list">
<h3 class="list-heading">General</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 4 pending tasks.
<span class="label label-sm label-warning "> Take action
<i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> Just now </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Finance Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> New order received with
<span class="label label-sm label-success"> Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 30 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Web server hardware needs to be upgraded.
<span class="label label-sm label-warning"> Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 2 hours </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> IPO Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
</ul>
<h3 class="list-heading">System</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 4 pending tasks.
<span class="label label-sm label-warning "> Take action
<i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> Just now </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Finance Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> New order received with
<span class="label label-sm label-success"> Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 30 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-warning">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Web server hardware needs to be upgraded.
<span class="label label-sm label-default "> Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 2 hours </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> IPO Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane page-quick-sidebar-settings" id="quick_sidebar_tab_3">
<div class="page-quick-sidebar-settings-list">
<h3 class="list-heading">General Settings</h3>
<ul class="list-items borderless">
<li> Enable Notifications
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Allow Tracking
<input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Log Errors
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Auto Sumbit Issues
<input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Enable SMS Alerts
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
</ul>
<h3 class="list-heading">System Settings</h3>
<ul class="list-items borderless">
<li> Security Level
<select class="form-control input-inline input-sm input-small">
<option value="1">Normal</option>
<option value="2" selected>Medium</option>
<option value="e">High</option>
</select>
</li>
<li> Failed Email Attempts
<input class="form-control input-inline input-sm input-small" value="5" /> </li>
<li> Secondary SMTP Port
<input class="form-control input-inline input-sm input-small" value="3560" /> </li>
<li> Notify On System Error
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Notify On SMTP Error
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
</ul>
<div class="inner-content">
<button class="btn btn-success">
<i class="icon-settings"></i> Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
</div>
</div>
<div class="page-wrapper-row">
<div class="page-wrapper-bottom">
<!-- BEGIN FOOTER -->
<!-- BEGIN PRE-FOOTER -->
<div class="page-prefooter">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12 footer-block">
<h2>About</h2>
<p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam dolore. </p>
</div>
<div class="col-md-3 col-sm-6 col-xs12 footer-block">
<h2>Subscribe Email</h2>
<div class="subscribe-form">
<form action="javascript:;">
<div class="input-group">
<input type="text" placeholder="[email protected]" class="form-control">
<span class="input-group-btn">
<button class="btn" type="submit">Submit</button>
</span>
</div>
</form>
</div>
</div>
<div class="col-md-3 col-sm-6 col-xs-12 footer-block">
<h2>Follow Us On</h2>
<ul class="social-icons">
<li>
<a href="javascript:;" data-original-title="rss" class="rss"></a>
</li>
<li>
<a href="javascript:;" data-original-title="facebook" class="facebook"></a>
</li>
<li>
<a href="javascript:;" data-original-title="twitter" class="twitter"></a>
</li>
<li>
<a href="javascript:;" data-original-title="googleplus" class="googleplus"></a>
</li>
<li>
<a href="javascript:;" data-original-title="linkedin" class="linkedin"></a>
</li>
<li>
<a href="javascript:;" data-original-title="youtube" class="youtube"></a>
</li>
<li>
<a href="javascript:;" data-original-title="vimeo" class="vimeo"></a>
</li>
</ul>
</div>
<div class="col-md-3 col-sm-6 col-xs-12 footer-block">
<h2>Contacts</h2>
<address class="margin-bottom-40"> Phone: 800 123 3456
<br> Email:
<a href="mailto:[email protected]">[email protected]</a>
</address>
</div>
</div>
</div>
</div>
<!-- END PRE-FOOTER -->
<!-- BEGIN INNER FOOTER -->
<div class="page-footer">
<div class="container"> 2016 © Metronic Theme By
<a target="_blank" href="http://keenthemes.com">Keenthemes</a> |
<a href="http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a>
</div>
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
<!-- END INNER FOOTER -->
<!-- END FOOTER -->
</div>
</div>
</div>
<!-- BEGIN QUICK NAV -->
<nav class="quick-nav">
<a class="quick-nav-trigger" href="#0">
<span aria-hidden="true"></span>
</a>
<ul>
<li>
<a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" target="_blank" class="active">
<span>Purchase Metronic</span>
<i class="icon-basket"></i>
</a>
</li>
<li>
<a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/reviews/4021469?ref=keenthemes" target="_blank">
<span>Customer Reviews</span>
<i class="icon-users"></i>
</a>
</li>
<li>
<a href="http://keenthemes.com/showcast/" target="_blank">
<span>Showcase</span>
<i class="icon-user"></i>
</a>
</li>
<li>
<a href="http://keenthemes.com/metronic-theme/changelog/" target="_blank">
<span>Changelog</span>
<i class="icon-graph"></i>
</a>
</li>
</ul>
<span aria-hidden="true" class="quick-nav-bg"></span>
</nav>
<div class="quick-nav-overlay"></div>
<!-- END QUICK NAV -->
<!--[if lt IE 9]>
<script src="../assets/global/plugins/respond.min.js"></script>
<script src="../assets/global/plugins/excanvas.min.js"></script>
<script src="../assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<!-- BEGIN CORE PLUGINS -->
<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="../assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS -->
<script src="../assets/layouts/layout3/scripts/layout.min.js" type="text/javascript"></script>
<script src="../assets/layouts/layout3/scripts/demo.min.js" type="text/javascript"></script>
<script src="../assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script>
<script src="../assets/layouts/global/scripts/quick-nav.min.js" type="text/javascript"></script>
<!-- END THEME LAYOUT SCRIPTS -->
</body>
</html> | Java |
package es.ucm.fdi.emf.model.ed2.diagram.sheet;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.graphics.Image;
import es.ucm.fdi.emf.model.ed2.diagram.navigator.Ed2NavigatorGroup;
import es.ucm.fdi.emf.model.ed2.diagram.part.Ed2VisualIDRegistry;
import es.ucm.fdi.emf.model.ed2.diagram.providers.Ed2ElementTypes;
/**
* @generated
*/
public class Ed2SheetLabelProvider extends BaseLabelProvider implements
ILabelProvider {
/**
* @generated
*/
public String getText(Object element) {
element = unwrap(element);
if (element instanceof Ed2NavigatorGroup) {
return ((Ed2NavigatorGroup) element).getGroupName();
}
IElementType etype = getElementType(getView(element));
return etype == null ? "" : etype.getDisplayName();
}
/**
* @generated
*/
public Image getImage(Object element) {
IElementType etype = getElementType(getView(unwrap(element)));
return etype == null ? null : Ed2ElementTypes.getImage(etype);
}
/**
* @generated
*/
private Object unwrap(Object element) {
if (element instanceof IStructuredSelection) {
return ((IStructuredSelection) element).getFirstElement();
}
return element;
}
/**
* @generated
*/
private View getView(Object element) {
if (element instanceof View) {
return (View) element;
}
if (element instanceof IAdaptable) {
return (View) ((IAdaptable) element).getAdapter(View.class);
}
return null;
}
/**
* @generated
*/
private IElementType getElementType(View view) {
// For intermediate views climb up the containment hierarchy to find the one associated with an element type.
while (view != null) {
int vid = Ed2VisualIDRegistry.getVisualID(view);
IElementType etype = Ed2ElementTypes.getElementType(vid);
if (etype != null) {
return etype;
}
view = view.eContainer() instanceof View ? (View) view.eContainer()
: null;
}
return null;
}
}
| Java |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# 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
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset()
| Java |
# frozen_string_literal: true
# How minitest plugins. See https://github.com/simplecov-ruby/simplecov/pull/756 for why we need this.
# https://github.com/seattlerb/minitest#writing-extensions
module Minitest
def self.plugin_simplecov_init(_options)
if defined?(SimpleCov)
SimpleCov.external_at_exit = true
Minitest.after_run do
SimpleCov.at_exit_behavior
end
end
end
end
| Java |
//***************************************************************************
//
// Copyright (c) 1999 - 2006 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.
//
//***************************************************************************
/**
@file FileScanner.cpp
This module defines ...
*/
//***************************************************************************
// Defines
//***************************************************************************
//***************************************************************************
// Includes
//***************************************************************************
#include "FileScanner.h"
#include "IFXException.h"
#include "IFXMatrix4x4.h"
#include "Color.h"
#include "Quat.h"
#include "Point.h"
#include "Int3.h"
#include "Int2.h"
#include "MetaDataList.h"
#include "Tokens.h"
#include <ctype.h>
#include <wchar.h>
using namespace U3D_IDTF;
//***************************************************************************
// Constants
//***************************************************************************
//***************************************************************************
// Enumerations
//***************************************************************************
//***************************************************************************
// Classes, structures and types
//***************************************************************************
//***************************************************************************
// Global data
//***************************************************************************
//***************************************************************************
// Local data
//***************************************************************************
//***************************************************************************
// Local function prototypes
//***************************************************************************
//***************************************************************************
// Public methods
//***************************************************************************
FileScanner::FileScanner()
{
m_currentCharacter[0] = 0;
m_currentCharacter[1] = 0;
m_used = TRUE;
}
FileScanner::~FileScanner()
{
}
IFXRESULT FileScanner::Initialize( const IFXCHAR* pFileName )
{
IFXRESULT result = IFX_OK;
result = m_file.Initialize( pFileName );
if( IFXSUCCESS( result ) )
m_currentCharacter[0] = m_file.ReadCharacter();
return result;
}
IFXRESULT FileScanner::Scan( IFXString* pToken, U32 scanLine )
{
// try to use fscanf
IFXRESULT result = IFX_OK;
if( NULL != pToken )
{
if( scanLine )
SkipBlanks();
else
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
U8 i = 0;
U8 buffer[MAX_STRING_LENGTH] = {0};
while( 0 == IsSpace( GetCurrentCharacter() ) && !IsEndOfFile() )
{
buffer[i++] = GetCurrentCharacter();
NextCharacter();
}
result = pToken->Assign(buffer);
}
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanString( IFXString* pString )
{
IFXRESULT result = IFX_OK;
if( NULL == pString )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
{
SkipSpaces();
if( '"' == GetCurrentCharacter() )
{
// found string, skip first quote
NextCharacter();
U32 i = 0;
U8 scanBuffer[MAX_STRING_LENGTH+2];
while( '"' != GetCurrentCharacter() && i < MAX_STRING_LENGTH )
{
if( '\\' == GetCurrentCharacter())
{
NextCharacter();
U8 currentCharacter = GetCurrentCharacter();
switch (currentCharacter)
{
case '\\':
scanBuffer[i++] = '\\';
break;
case 'n':
scanBuffer[i++] = '\n';
break;
case 't':
scanBuffer[i++] = '\t';
break;
case 'r':
scanBuffer[i++] = '\r';
break;
case '"':
scanBuffer[i++] = '"';
break;
default:
scanBuffer[i++] = currentCharacter;
}
}
else
scanBuffer[i++] = GetCurrentCharacter();
NextCharacter();
}
NextCharacter(); // skip last double quote
scanBuffer[i] = 0;
/// @todo: Converter Unicode support
// convert one byte string to unicode
pString->Assign( scanBuffer );
}
else
{
result = IFX_E_STRING_NOT_FOUND;
}
}
return result;
}
IFXRESULT FileScanner::ScanFloat( F32* pNumber )
{
IFXRESULT result = IFX_OK;
if( NULL == pNumber )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
{
//this F32 format is preferred
#ifdef F32_EXPONENTIAL
IFXString buffer;
U32 fpos;
result = m_file.GetPosition( &fpos );
if( IFXSUCCESS( result ) )
result = Scan( &buffer, 1 );
if( IFXSUCCESS( result ) )
{
I32 scanResult = swscanf( buffer.Raw(), L"%g", pNumber );
if( 0 == scanResult || EOF == scanResult )
{
result = IFX_E_FLOAT_NOT_FOUND;
// new token found, not float
// do not allow client to continue scan for new tokens
m_used = TRUE;
m_currentToken = buffer;
fpos--;
m_file.SetPosition( fpos );
NextCharacter();
}
}
#else
I32 sign = 1;
U32 value = 0;
SkipBlanks();
if( '-' == GetCurrentCharacter() )
{
sign = -1;
NextCharacter();
}
if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() )
NextCharacter();
while( isdigit( GetCurrentCharacter() ) )
{
value = ( value*10 ) + ( GetCurrentCharacter() - '0' );
NextCharacter();
}
// there should be fraction part of float
if( '.' == GetCurrentCharacter() )
{
F32 fraction = 0.0f;
F32 divisor = 10.0f;
if( '.' == GetCurrentCharacter() )
NextCharacter();
while( isdigit( GetCurrentCharacter() ) )
{
fraction += ( GetCurrentCharacter() - '0' ) / divisor;
divisor *=10.0f;
NextCharacter();
}
*pNumber = static_cast<float>(value);
*pNumber += fraction;
*pNumber *= sign;
}
else
{
result = IFX_E_FLOAT_NOT_FOUND;
}
#endif
}
return result;
}
IFXRESULT FileScanner::ScanInteger( I32* pNumber )
{
IFXRESULT result = IFX_OK;
IFXString buffer;
if( NULL == pNumber )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
{
I32 sign = 1;
I32 value = 0;
SkipSpaces();
if( '-' == GetCurrentCharacter() )
{
sign = -1;
}
if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() )
{
NextCharacter();
}
while( isdigit( GetCurrentCharacter() ) )
{
value = (value*10) + (GetCurrentCharacter() - '0');
NextCharacter();
}
*pNumber = value * sign;
}
return result;
}
IFXRESULT FileScanner::ScanHex( I32* pNumber )
{
IFXRESULT result = IFX_OK;
IFXString buffer;
if( NULL == pNumber )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
result = Scan( &buffer );
if( IFXSUCCESS( result ) )
{
buffer.ForceUppercase();
int scanResult = swscanf( buffer.Raw(), L"%X", pNumber );
if( 0 == scanResult || EOF == scanResult )
{
result = IFX_E_INT_NOT_FOUND;
}
}
return result;
}
IFXRESULT FileScanner::ScanTM( IFXMatrix4x4* pMatrix )
{
IFXRESULT result = IFX_OK;
F32 matrix[16];
U32 i;
for( i = 0; i < 16 && IFXSUCCESS( result ); ++i )
{
result = ScanFloat( &matrix[i] );
if( 0 == (i + 1)%4 )
{
// skip end of line
SkipSpaces();
}
}
if( IFXSUCCESS( result ) )
{
*pMatrix = matrix;
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanColor( Color* pColor )
{
IFXRESULT result = IFX_OK;
F32 red = 0.0f, green = 0.0f, blue = 0.0f, alpha = 0.0f;
result = ScanFloat( &red );
if( IFXSUCCESS( result ) )
result = ScanFloat( &green );
if( IFXSUCCESS( result ) )
result = ScanFloat( &blue );
if( IFXSUCCESS( result ) )
{
result = ScanFloat( &alpha );
if( IFXSUCCESS( result ) )
{
// 4 component color
IFXVector4 color( red, green, blue, alpha );
pColor->SetColor( color );
}
else if( IFX_E_FLOAT_NOT_FOUND == result )
{
// 3 component color
IFXVector4 color( red, green, blue );
pColor->SetColor( color );
result = IFX_OK;
}
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanQuat( Quat* pQuat )
{
IFXRESULT result = IFX_OK;
F32 w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f;
result = ScanFloat( &w );
if( IFXSUCCESS( result ) )
result = ScanFloat( &x );
if( IFXSUCCESS( result ) )
result = ScanFloat( &y );
if( IFXSUCCESS( result ) )
{
result = ScanFloat( &z );
if( IFXSUCCESS( result ) )
{
IFXVector4 quat( w, x, y, z );
pQuat->SetQuat( quat );
SkipSpaces();
}
}
return result;
}
IFXRESULT FileScanner::ScanPoint( Point* pPoint )
{
IFXRESULT result = IFX_OK;
F32 x = 0.0f, y = 0.0f, z = 0.0f;
result = ScanFloat( &x );
if( IFXSUCCESS( result ) )
result = ScanFloat( &y );
if( IFXSUCCESS( result ) )
result = ScanFloat( &z );
if( IFXSUCCESS( result ) )
{
IFXVector3 point( x, y, z );
pPoint->SetPoint( point );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanVector4( IFXVector4* pVector4 )
{
IFXRESULT result = IFX_OK;
F32 x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f;
result = ScanFloat( &x );
if( IFXSUCCESS( result ) )
result = ScanFloat( &y );
if( IFXSUCCESS( result ) )
result = ScanFloat( &z );
if( IFXSUCCESS( result ) )
result = ScanFloat( &w );
if( IFXSUCCESS( result ) )
{
pVector4->Set( x, y, z, w );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanInt3( Int3* pData )
{
IFXRESULT result = IFX_OK;
I32 x = 0, y = 0, z = 0;
result = ScanInteger( &x );
if( IFXSUCCESS( result ) )
result = ScanInteger( &y );
if( IFXSUCCESS( result ) )
result = ScanInteger( &z );
if( IFXSUCCESS( result ) )
{
pData->SetData( x, y, z );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanInt2( Int2* pData )
{
IFXRESULT result = IFX_OK;
I32 x = 0, y = 0;
result = ScanInteger( &x );
if( IFXSUCCESS( result ) )
result = ScanInteger( &y );
if( IFXSUCCESS( result ) )
{
pData->SetData( x, y );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanToken( const IFXCHAR* pToken )
{
// try to use fscanf
IFXRESULT result = IFX_OK;
if( NULL != pToken )
{
if( TRUE == m_used )
{
// previous token was successfuly used and we can scan next
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
U8 buffer[MAX_STRING_LENGTH];
U32 i = 0;
if( IDTF_END_BLOCK != GetCurrentCharacter() )
{
while( ( 0 == IsSpace( GetCurrentCharacter() ) ) &&
!IsEndOfFile() &&
i < MAX_STRING_LENGTH
)
{
buffer[i++] = GetCurrentCharacter();
NextCharacter();
}
buffer[i] = 0;
/// @todo: Converter unicode support
m_currentToken.Assign( buffer );
}
else
{
// block terminator found
// do not allow client to continue scan for new tokens
m_used = FALSE;
}
}
}
/// @todo: Converter Unicode support
// convert one byte token to unicode
IFXString token( pToken );
if( m_currentToken != token )
{
m_used = FALSE;
result = IFX_E_TOKEN_NOT_FOUND;
}
else
m_used = TRUE;
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanStringToken( const IFXCHAR* pToken, IFXString* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanString( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanIntegerToken( const IFXCHAR* pToken, I32* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanInteger( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanHexToken( const IFXCHAR* pToken, I32* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanHex( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanFloatToken( const IFXCHAR* pToken, F32* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanFloat( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanTMToken( const IFXCHAR* pToken, IFXMatrix4x4* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = FindBlockStarter();
if( IFXSUCCESS( result ) )
result = ScanTM( pValue );
if( IFXSUCCESS( result ) )
result = FindBlockTerminator();
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanColorToken( const IFXCHAR* pToken, Color* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanColor( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanQuatToken( const IFXCHAR* pToken, Quat* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanQuat( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanPointToken( const IFXCHAR* pToken, Point* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanPoint( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::FindBlockStarter()
{
IFXRESULT result = IFX_OK;
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
if( GetCurrentCharacter() == IDTF_BEGIN_BLOCK )
{
NextCharacter();
SkipSpaces();
}
else
result = IFX_E_STARTER_NOT_FOUND;
}
return result;
}
IFXRESULT FileScanner::FindBlockTerminator()
{
IFXRESULT result = IFX_OK;
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
if( GetCurrentCharacter() == IDTF_END_BLOCK )
{
// block terminator found
// allow client to scan for next token
m_used = TRUE;
NextCharacter();
}
else
result = IFX_E_TERMINATOR_NOT_FOUND;
}
return result;
}
//***************************************************************************
// Protected methods
//***************************************************************************
BOOL FileScanner::IsSpace( I8 character )
{
return isspace( character );
}
BOOL FileScanner::IsEndOfFile()
{
return m_file.IsEndOfFile();
}
void FileScanner::SkipSpaces()
{
while( 0 != isspace( GetCurrentCharacter() ) && !m_file.IsEndOfFile() )
NextCharacter();
}
void FileScanner::SkipBlanks()
{
while( ( ' ' == GetCurrentCharacter() || '\t' == GetCurrentCharacter() )
&& !m_file.IsEndOfFile() )
NextCharacter();
}
U8 FileScanner::NextCharacter()
{
return m_currentCharacter[0] = m_file.ReadCharacter();
}
//***************************************************************************
// Private methods
//***************************************************************************
//***************************************************************************
// Global functions
//***************************************************************************
//***************************************************************************
// Local functions
//***************************************************************************
| Java |
// Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
// $hash=517c8bf7f36b294cbbcb0a52dcc9b1d1922986ce$
//
#ifndef CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_
#define CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_
#pragma once
#if !defined(WRAPPING_CEF_SHARED)
#error This file can be included wrapper-side only
#endif
#include "include/capi/cef_dom_capi.h"
#include "include/cef_dom.h"
#include "libcef_dll/ctocpp/ctocpp_ref_counted.h"
// Wrap a C structure with a C++ class.
// This class may be instantiated and accessed wrapper-side only.
class CefDOMNodeCToCpp
: public CefCToCppRefCounted<CefDOMNodeCToCpp, CefDOMNode, cef_domnode_t> {
public:
CefDOMNodeCToCpp();
// CefDOMNode methods.
Type GetType() OVERRIDE;
bool IsText() OVERRIDE;
bool IsElement() OVERRIDE;
bool IsEditable() OVERRIDE;
bool IsFormControlElement() OVERRIDE;
CefString GetFormControlElementType() OVERRIDE;
bool IsSame(CefRefPtr<CefDOMNode> that) OVERRIDE;
CefString GetName() OVERRIDE;
CefString GetValue() OVERRIDE;
bool SetValue(const CefString& value) OVERRIDE;
CefString GetAsMarkup() OVERRIDE;
CefRefPtr<CefDOMDocument> GetDocument() OVERRIDE;
CefRefPtr<CefDOMNode> GetParent() OVERRIDE;
CefRefPtr<CefDOMNode> GetPreviousSibling() OVERRIDE;
CefRefPtr<CefDOMNode> GetNextSibling() OVERRIDE;
bool HasChildren() OVERRIDE;
CefRefPtr<CefDOMNode> GetFirstChild() OVERRIDE;
CefRefPtr<CefDOMNode> GetLastChild() OVERRIDE;
CefString GetElementTagName() OVERRIDE;
bool HasElementAttributes() OVERRIDE;
bool HasElementAttribute(const CefString& attrName) OVERRIDE;
CefString GetElementAttribute(const CefString& attrName) OVERRIDE;
void GetElementAttributes(AttributeMap& attrMap) OVERRIDE;
bool SetElementAttribute(const CefString& attrName,
const CefString& value) OVERRIDE;
CefString GetElementInnerText() OVERRIDE;
CefRect GetElementBounds() OVERRIDE;
};
#endif // CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_
| Java |
local pi = math.pi
local player_in_bed = 0
local is_sp = minetest.is_singleplayer()
local enable_respawn = minetest.setting_getbool("enable_bed_respawn")
if enable_respawn == nil then
enable_respawn = true
end
-- Helper functions
local function get_look_yaw(pos)
local n = minetest.get_node(pos)
if n.param2 == 1 then
return pi / 2, n.param2
elseif n.param2 == 3 then
return -pi / 2, n.param2
elseif n.param2 == 0 then
return pi, n.param2
else
return 0, n.param2
end
end
local function is_night_skip_enabled()
local enable_night_skip = minetest.setting_getbool("enable_bed_night_skip")
if enable_night_skip == nil then
enable_night_skip = true
end
return enable_night_skip
end
local function check_in_beds(players)
local in_bed = beds.player
if not players then
players = minetest.get_connected_players()
end
for n, player in ipairs(players) do
local name = player:get_player_name()
if not in_bed[name] then
return false
end
end
return #players > 0
end
local function lay_down(player, pos, bed_pos, state, skip)
local name = player:get_player_name()
local hud_flags = player:hud_get_flags()
if not player or not name then
return
end
-- stand up
if state ~= nil and not state then
local p = beds.pos[name] or nil
if beds.player[name] ~= nil then
beds.player[name] = nil
player_in_bed = player_in_bed - 1
end
-- skip here to prevent sending player specific changes (used for leaving players)
if skip then
return
end
if p then
player:setpos(p)
end
-- physics, eye_offset, etc
player:set_eye_offset({x = 0, y = 0, z = 0}, {x = 0, y = 0, z = 0})
player:set_look_yaw(math.random(1, 180) / 100)
default.player_attached[name] = false
player:set_physics_override(1, 1, 1)
hud_flags.wielditem = true
default.player_set_animation(player, "stand" , 30)
-- lay down
else
beds.player[name] = 1
beds.pos[name] = pos
player_in_bed = player_in_bed + 1
-- physics, eye_offset, etc
player:set_eye_offset({x = 0, y = -13, z = 0}, {x = 0, y = 0, z = 0})
local yaw, param2 = get_look_yaw(bed_pos)
player:set_look_yaw(yaw)
local dir = minetest.facedir_to_dir(param2)
local p = {x = bed_pos.x + dir.x / 2, y = bed_pos.y, z = bed_pos.z + dir.z / 2}
player:set_physics_override(0, 0, 0)
player:setpos(p)
default.player_attached[name] = true
hud_flags.wielditem = false
default.player_set_animation(player, "lay" , 0)
end
player:hud_set_flags(hud_flags)
end
local function update_formspecs(finished)
local ges = #minetest.get_connected_players()
local form_n = ""
local is_majority = (ges / 2) < player_in_bed
if finished then
form_n = beds.formspec .. "label[2.7,11; Good morning.]"
else
form_n = beds.formspec .. "label[2.2,11;" .. tostring(player_in_bed) ..
" of " .. tostring(ges) .. " players are in bed]"
if is_majority and is_night_skip_enabled() then
form_n = form_n .. "button_exit[2,8;4,0.75;force;Force night skip]"
end
end
for name,_ in pairs(beds.player) do
minetest.show_formspec(name, "beds_form", form_n)
end
end
-- Public functions
function beds.kick_players()
for name, _ in pairs(beds.player) do
local player = minetest.get_player_by_name(name)
lay_down(player, nil, nil, false)
end
end
function beds.skip_night()
minetest.set_timeofday(0.23)
beds.set_spawns()
end
function beds.on_rightclick(pos, player)
local name = player:get_player_name()
local ppos = player:getpos()
local tod = minetest.get_timeofday()
if tod > 0.2 and tod < 0.805 then
if beds.player[name] then
lay_down(player, nil, nil, false)
end
minetest.chat_send_player(name, "You can only sleep at night.")
return
end
-- move to bed
if not beds.player[name] then
lay_down(player, ppos, pos)
else
lay_down(player, nil, nil, false)
end
if not is_sp then
update_formspecs(false)
end
-- skip the night and let all players stand up
if check_in_beds() then
minetest.after(2, function()
if not is_sp then
update_formspecs(is_night_skip_enabled())
end
if is_night_skip_enabled() then
beds.skip_night()
beds.kick_players()
end
end)
end
end
-- Callbacks
minetest.register_on_joinplayer(function(player)
beds.read_spawns()
end)
-- respawn player at bed if enabled and valid position is found
minetest.register_on_respawnplayer(function(player)
if not enable_respawn then
return false
end
local name = player:get_player_name()
local pos = beds.spawn[name] or nil
if pos then
player:setpos(pos)
return true
end
end)
minetest.register_on_leaveplayer(function(player)
local name = player:get_player_name()
lay_down(player, nil, nil, false, true)
beds.player[name] = nil
if check_in_beds() then
minetest.after(2, function()
update_formspecs(is_night_skip_enabled())
if is_night_skip_enabled() then
beds.skip_night()
beds.kick_players()
end
end)
end
end)
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= "beds_form" then
return
end
if fields.quit or fields.leave then
lay_down(player, nil, nil, false)
update_formspecs(false)
end
if fields.force then
update_formspecs(is_night_skip_enabled())
if is_night_skip_enabled() then
beds.skip_night()
beds.kick_players()
end
end
end)
| Java |
.color-picker {
-moz-box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3);
box-shadow: 1px 1px 15px rgba(0, 0, 0, 0.3);
-moz-border-radius: 0 0 5px 5px;
-webkit-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
}
.color-picker-title-bar,
.color-picker-closer {
position: absolute;
top: -22px;
color: white;
padding: 5px 15px 3px;
-moz-border-radius: 5px 5px 0 0;
-webkit-border-radius: 5px 5px 0 0;
border-radius: 5px 5px 0 0;
}
.color-picker-title-bar {
left: 0;
width: 245px;
height: 15px;
}
.color-picker-value {
position: absolute;
top: -22px;
}
.color-picker-color {
position: absolute;
top: -17px;
left: 15px;
width: 12px;
height: 12px;
border: 1px solid #ccc;
}
.color-picker-hex {
position: absolute;
top: -16px;
left: 33px;
color: white;
font-size: 10px;
}
.color-picker-closer {
right: 0px;
cursor: pointer;
}
.color-picker img {
display: block;
margin: 0;
padding: 0;
border: 0;
}
.color-picker div {
float: left;
}
.color-picker-sv {
position: relative;
background-repeat: none;
margin-right: 20px;
width: 200px;
height: 200px;
}
.color-picker-h {
position: relative;
background-repeat: none;
width: 25px;
height: 200px;
}
.color-picker-h-slider {
position: absolute;
left: -14px;
top: -5px;
width: 44px;
height: 12px;
}
.color-picker-sv-slider {
position: absolute;
left: -8px;
top: -8px;
width: 17px;
height: 17px;
}
| Java |
/* str*()-like functions for raw memory "lines" (non-NUL terminated strings).
*
* Especially when we're parsing input in an ESL_BUFFER, we need to be
* able to parse non-writable raw memory buffers. Because an
* ESL_BUFFER may have memory mapped a file, we cannot assume that the
* input is NUL-terminated, and we can't even assume it's writable (so
* we can't NUL-terminate it ourselves). These functions provide
* a set of utilities for parsing raw memory (in terms of a char * pointer
* and a length in bytes; <char *p>, <esl_pos_t n> by convention).
*
* Contents:
* 1. The esl_mem*() API.
* 2. Unit tests.
* 3. Test driver.
* 4. Copyright and license.
*/
#include "esl_config.h"
#include <string.h>
#include <ctype.h>
#include "easel.h"
/*****************************************************************
*# 1. The esl_mem*() API.
*****************************************************************/
/* Function: esl_mem_strtoi32()
* Synopsis: Convert a chunk of text memory to an int32_t.
*
* Purpose: Convert the text starting at <p> to an <int32_t>, converting
* no more than <n> characters (the valid length of non-<NUL>
* terminated memory buffer <p>). Interpret the text as
* base <base> (2 or 10, for example). <base> must be 2..36,
* or 0. 0 is treated specially as base 8, 10, or 16, autodetected
* according to the leading characters of the number format.
*
* Any leading whitespace is skipped. The next letter may
* be a '-' for a negative number. If <base> is 0 or 16,
* the next two characters may be "0x", in which case hex base
* 16 is assumed. Else if <base> is 0 and the next
* character is '0', octal base 8 is assumed. All subsequent
* characters are converted to a number, until an invalid
* character is reached. Upper or lower case letters are
* accepted, starting at A or a, for bases over 10. For
* example, In base 16, characters A-F or a-f are accepted.
* The base of the representation is limited to 36 because
* 'Z' or 'z' represents 35.
*
* The converted value is optionally returned in <*opt_val>.
* The number of characters parsed (up to the first invalid
* character, or <n>, whichever comes first) is optionally
* returned in <*opt_nc>. The caller can reposition a parser
* to <p + *opt_nc> to exactly skip past the parsed number.
*
* If no valid digit is found (including pathological cases
* of leader-only, such as "0x" or "-"), then return <eslEINVAL>,
* and <*opt_nc> and <*opt_val> are both 0.
*
* This syntax is essentially identical to <strtol()>,
* except that we can operate on a non-NUL-terminated
* memory buffer of maximum length <n>, rather than on a
* NUL-terminated string.
*
* Args: p - pointer to text buffer to convert to int32_t
* n - maximum number of chars to parse in <p>: p[0..n-1] are valid.
* base - integer base. Often 10, 2, 8, or 16. Must be
* <2..36>, or 0. 0 means base 8, 10, or 16 depending on
* autodetected format.
* *opt_nc - optRETURN: number of valid chars parsed from p.
* First invalid char is p[*opt_nc].
* *opt_val - optRETURN: parsed value.
*
* Returns: <eslOK> on success.
*
* <eslEFORMAT> if no valid integer digits are found. Now
* <*opt_val> and <*opt_nc> are 0.
*
* <eslERANGE> on an overflow error. In this case
* <*opt_val> is <INT32_MAX> or <INT32_MIN> for an
* overflow or underflow, respectively. <*opt_nc> is
* set to the number of characters parsed INCLUDING
* the digit that caused the overflow.
*
* Throws: <eslEINVAL> if <base> isn't in range <0..36>. Now
* <*opt_nc> and <*opt_val> are 0.
*
* Note: An example of why you need this instead of
* strtol(): suppose you've mmap()'ed a file to memory,
* and it ends in ... "12345". You can't strtol the
* end of the mmap'ed memory buffer because it is not
* a NUL-terminated string. (Same goes anywhere in the file,
* though elsewhere in the file you could overwrite
* a NUL where you need it. At EOF of an mmap'ed() buffer,
* you can't even do that.)
*
* sscanf() doesn't work either - I don't see a way to
* limit it to a buffer of at most <n> chars.
*
* I could copy <p> to a temporary allocated string that I
* NUL-terminate, then use strtol() or suchlike, but that's
* just as awful as what I've done here (rewriting
* strtol()). Plus, here I get complete control of the integer
* type (<int32_t>) whereas strtol() gives me the less satisfying
* <long>.
*/
int
esl_mem_strtoi32(char *p, esl_pos_t n, int base, int *opt_nc, int32_t *opt_val)
{
esl_pos_t i = 0;
int32_t sign = 1;
int32_t currval = 0;
int32_t digit = 0;
int ndigits = 0;
if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0");
while (i < n && isspace(p[i])) i++; /* skip leading whitespace */
if (i < n && p[i] == '-') { sign = -1; i++; }
if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x')
{ i += 2; base = 16; }
else if (base == 0 && i < n && p[i] == '0')
{ i += 1; base = 8; }
else if (base == 0)
{ base = 10; }
for (ndigits = 0; i < n; i++, ndigits++)
{
if (isdigit(p[i])) digit = p[i] - '0';
else if (isupper(p[i])) digit = 10 + (p[i] - 'A');
else if (islower(p[i])) digit = 10 + (p[i] - 'a');
else break;
if (digit >= base) break;
if (sign == 1)
{
if (currval > (INT32_MAX - digit) / base)
{
if (opt_val) *opt_val = INT32_MAX;
if (opt_nc) *opt_nc = i+1;
return eslERANGE;
}
currval = currval * base + digit;
}
else
{
if (currval < (INT32_MIN + digit) / base)
{
if (opt_val) *opt_val = INT32_MIN;
if (opt_nc) *opt_nc = i+1;
return eslERANGE;
}
currval = currval * base - digit;
}
}
if (opt_nc) { *opt_nc = (ndigits ? i : 0); }
if (opt_val) { *opt_val = currval; }
return (ndigits ? eslOK : eslEFORMAT);
}
/* Function: esl_memnewline()
* Synopsis: Find next newline in memory.
*
* Purpose: Given a memory buffer <*m> of <n> bytes, delimit a
* next line by finding the next newline character(s).
* Store the number of bytes in the line (exclusive of
* the newline character(s)) in <*ret_nline>. Store
* the number of bytes in the newline in <*ret_nterm>.
*
* If no newline is found, <nline=n> and <nterm=0>, and the
* return status is <eslEOD>.
*
* Currently we assume newlines are either UNIX-style \verb+\n+
* or Windows-style \verb+\r\n+, in this implementation.
*
* Caller should not rely on this, though. Caller may only
* assume that a newline is an arbitrary one- or two-byte
* code.
*
* For example, if <*m> = \verb+"line one\r\nline two"+, <nline>
* is 8 and <nterm> is 2. If <*m> = \verb+"try two\ntry three"+,
* <nline> is 7 and <nterm> is 1. If <*m> = "attempt
* four", <nline> is 12 and <nterm> is 0.
*
* In cases where the caller may have an incompletely read
* buffer, it should be careful of cases where one possible
* newline may be a prefix of another; for example, suppose
* a file has \verb+"line one\r\nline two"+, but we only input the
* buffer \verb+"line one\r"+ at first. The \verb+"\r"+ looks like an old
* MacOS newline. Now we read more input, and we think the
* buffer is \verb+"\nline two"+. Now we think the \verb+"\n"+ is a UNIX
* newline. The result is that we read two newlines where
* there's only one. Instead, caller should check for the
* case of nterm==1 at the end of its buffer, and try to
* extend the buffer. See <esl_buffer_GetLine()> for an
* example.
*
* Args: m - ptr to memory buffer
* n - length of p in bytes
* *ret_nline - length of line found starting at p[0], exclusive of newline; up to n
* *ret_nterm - # of bytes in newline code: 1 or 2, or 0 if no newline found
*
* Returns: <eslOK> on success. Now <*ret_nline> is the number of
* bytes in the next line (exclusive of newline) and
* <*ret_nterm> is the number of bytes in the newline code
* (1 or 2). Thus the next line is <m[0..nline-1]>, and
* the line after this starts at <m[nline+nterm]>.
*
* <eslEOD> if no newline is found. Now <*ret_nline> is <n>,
* and <*ret_nterm> is 0.
*
* Xref: http://en.wikipedia.org/wiki/Newline
*/
int
esl_memnewline(const char *m, esl_pos_t n, esl_pos_t *ret_nline, int *ret_nterm)
{
char *ptr = memchr(m, '\n', n);
if (ptr == NULL) { *ret_nline = n; *ret_nterm = 0; }
else if (ptr > m && *(ptr-1) == '\r') { *ret_nline = ptr-m-1; *ret_nterm = 2; }
else { *ret_nline = ptr-m; *ret_nterm = 1; }
return eslOK;
}
/* Function: esl_memtok()
* Synopsis: Get next delimited token from a line.
*
* Purpose: Given references to a line and its length, <*p> and <*n>,
* find the next token delimited by any of the characters
* in the string <delim>. Set <*ret_tok> to point at the
* start of the token, and <*ret_toklen> to its length.
* Increment <*p> to point to the next non-delim character
* that follows, and decrement <*n> by the same,
* so that <*p> and <*n> are ready for another
* call to <esl_memtok()>.
*
* Three differences between <esl_strtok()> and <esl_memtok()>:
* first, <esl_strtok()> expects a NUL-terminated string,
* whereas <esl_memtok()>'s line does not need to be
* NUL-terminated; second, <esl_memtok()> does not modify
* the string, whereas <esl_strtok()> writes NUL bytes
* to delimit tokens; third, <esl_memtok()> skips trailing
* <delim> characters as well as leading ones.
*
* Args: *p - pointer to line;
* will be incremented to next byte after token.
* *n - pointer to line length, in bytes;
* will be decremented
* delim - delimiter chars (example: " \t\r\n")
* *ret_tok - RETURN: ptr to token found in <*p>
* *ret_toklen - RETURN: length of token
*
* Returns: <eslOK> if a delimited token is found.
* <eslEOL> if not; now <*ret_tok> is <NULL> and <*ret_toklen> is <0>.
*
*/
int
esl_memtok(char **p, esl_pos_t *n, const char *delim, char **ret_tok, esl_pos_t *ret_toklen)
{
char *s = *p;
esl_pos_t so, xo, eo;
for (so = 0; so < *n; so++) if (strchr(delim, s[so]) == NULL) break;
for (xo = so; xo < *n; xo++) if (strchr(delim, s[xo]) != NULL) break;
for (eo = xo; eo < *n; eo++) if (strchr(delim, s[eo]) == NULL) break;
if (so == *n) { *ret_tok = NULL; *ret_toklen = 0; return eslEOL; }
else { *p += eo; *n -= eo; *ret_tok = s + so; *ret_toklen = xo - so; return eslOK; }
}
/* Function: esl_memspn()
* Synopsis: Finds length of prefix consisting only of given chars
*
* Purpose: For line <p> of length <n>, return the length of
* a prefix that consists only of characters in the
* string <allow>.
*
* A commonly used idiom for "buffer is all whitespace"
* is <esl_memspn(p, n, " \t\r\n") == n>.
*/
esl_pos_t
esl_memspn(char *p, esl_pos_t n, const char *allow)
{
esl_pos_t so;
for (so = 0; so < n; so++) if (strchr(allow, p[so]) == NULL) break;
return so;
}
/* Function: esl_memcspn()
* Synopsis: Finds length of prefix consisting of anything other than given chars
*
* Purpose: For line <p> of length <n>, return the length of
* a prefix that consists only of characters NOT in the
* string <disallow>.
*/
esl_pos_t
esl_memcspn(char *p, esl_pos_t n, const char *disallow)
{
esl_pos_t so;
for (so = 0; so < n; so++) if (strchr(disallow, p[so]) != NULL) break;
return so;
}
/* Function: esl_memstrcmp()
* Synopsis: Compare a memory line and string for equality.
*
* Purpose: Compare line <p> of length <n> to a NUL-terminated
* string <s>, and return TRUE if they are exactly
* equal: <strlen(s) == n> and <p[0..n-1] == s[0..n-1]>.
* Else, return FALSE.
*/
int
esl_memstrcmp(const char *p, esl_pos_t n, const char *s)
{
esl_pos_t pos;
if (p == NULL && n == 0 && (s == NULL || s[0] == '\0')) return TRUE;
if (!p || !s) return FALSE;
for (pos = 0; pos < n && s[pos] != '\0'; pos++)
if (p[pos] != s[pos]) return FALSE;
if (pos != n) return FALSE;
if (s[pos] != '\0') return FALSE;
return TRUE;
}
/* Function: esl_memstrpfx()
* Synopsis: Return TRUE if memory line starts with string.
*
* Purpose: Compare line <p> of length <n> to a NUL-terminated
* string <s>. Return TRUE if the prefix of <p> exactly
* matches <s> up to its NUL sentinel byte. Else,
* return FALSE.
*/
int
esl_memstrpfx(const char *p, esl_pos_t n, const char *s)
{
esl_pos_t pos;
if (!p || !s) return FALSE;
for (pos = 0; pos < n && s[pos] != '\0'; pos++)
if (p[pos] != s[pos]) return FALSE;
if (s[pos] != '\0') return FALSE;
return TRUE;
}
/* Function: esl_memstrcontains()
* Synopsis: Return TRUE if memory line matches a string.
*
* Purpose: Compare line <p> of length <n> to NUL-terminated
* string <s>. Return <TRUE> if <p> contains an exact
* match to <s> at any position.
*/
int
esl_memstrcontains(const char *p, esl_pos_t n, const char *s)
{
esl_pos_t s0, pos;
if (! p || ! s) return FALSE;
for (s0 = 0; s0 < n; s0++)
{
for (pos = 0; s0+pos < n && s[pos] != '\0'; pos++)
if (p[s0+pos] != s[pos]) break;
if (s[pos] == '\0') return TRUE;
}
return FALSE;
}
/* Function: esl_memstrdup()
* Synopsis: Duplicate a memory line as a NUL-terminated string.
*
* Purpose: Given memory line <p> of length <n>, duplicate it
* as a NUL-terminated string; return the new string
* in <*ret_s>.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation failure; now <*ret_s> is <NULL>.
*/
int
esl_memstrdup(const char *p, esl_pos_t n, char **ret_s)
{
char *s = NULL;
int status;
if (! p) { *ret_s = NULL; return eslOK; }
ESL_ALLOC(s, sizeof(char) * (n+1));
memcpy(s, p, n);
s[n] = '\0';
*ret_s = s;
return eslOK;
ERROR:
*ret_s = NULL;
return status;
}
/* Function: esl_memstrcpy()
* Synopsis: Copy a memory line as a string.
*
* Purpose: Given memory line <p> of length <n>, copy
* it to <dest> and NUL-terminate it. Caller must
* be sure that <s> is already allocated for
* at least <n+1> bytes.
*
* Returns: <eslOK> on success.
*/
int
esl_memstrcpy(const char *p, esl_pos_t n, char *dest)
{
memcpy(dest, p, n);
dest[n] = '\0';
return eslOK;
}
/* Function: esl_memtod()
* Synopsis: esl_mem equivalent to strtod().
*
* Purpose: Given a buffer <p> of length <n>, convert it to a
* double-precision floating point value, just as
* <strtod()> would do for a NUL-terminated string.
*
* Returns: <eslOK> on success, and <*ret_val> contains the
* converted value.
*
* Throws: <eslEMEM> on allocation error, and <*ret_val> is 0.
*/
int
esl_memtod(const char *p, esl_pos_t n, double *ret_val)
{
char fixedbuf[128];
char *bigbuf = NULL;
int status;
if (n < 128)
{
memcpy(fixedbuf, p, sizeof(char) * n);
fixedbuf[n] = '\0';
*ret_val = strtod(fixedbuf, NULL);
return eslOK;
}
else
{
ESL_ALLOC(bigbuf, sizeof(char) * (n+1));
memcpy(bigbuf, p, sizeof(char) * n);
bigbuf[n] = '\0';
*ret_val = strtod(fixedbuf, NULL);
free(bigbuf);
return eslOK;
}
ERROR:
*ret_val = 0.;
return status;
}
/* Function: esl_memtof()
* Synopsis: esl_mem equivalent to strtod(), for a float
*
* Purpose: Given a buffer <p> of length <n>, convert it to a
* single-precision floating point value, just as
* <strtod()> would do for a NUL-terminated string.
*
* Returns: <eslOK> on success, and <*ret_val> contains the
* converted value.
*
* Throws: <eslEMEM> on allocation error, and <*ret_val> is 0.
*/
int
esl_memtof(const char *p, esl_pos_t n, float *ret_val)
{
char fixedbuf[128];
char *bigbuf = NULL;
int status;
if (n < 128)
{
memcpy(fixedbuf, p, sizeof(char) * n);
fixedbuf[n] = '\0';
*ret_val = (float) strtod(fixedbuf, NULL);
return eslOK;
}
else
{
ESL_ALLOC(bigbuf, sizeof(char) * (n+1));
memcpy(bigbuf, p, sizeof(char) * n);
bigbuf[n] = '\0';
*ret_val = (float) strtod(fixedbuf, NULL);
free(bigbuf);
return eslOK;
}
ERROR:
*ret_val = 0.;
return status;
}
/* Function: esl_mem_IsReal()
* Synopsis: Return TRUE if <p> is a real number; else FALSE.
*
* Purpose: If the memory <p> of <n> bytes is convertible
* to a floating point real number by the rules of
* atof(), return TRUE; else return FALSE.
*
* Xref: easel.c::esl_str_IsReal() for string version.
*/
int
esl_mem_IsReal(const char *p, esl_pos_t n)
{
int gotdecimal = 0;
int gotexp = 0;
int gotreal = 0;
if (!p || !n) return FALSE;
while (n && isspace((int) *p)) { p++; n--; } /* skip leading whitespace */
if (n && (*p == '-' || *p == '+')) { p++; n--; } /* skip leading sign */
/* Examine remainder for garbage. Allowed one '.' and
* one 'e' or 'E'; if both '.' and e/E occur, '.'
* must be first.
*/
while (n)
{
if (isdigit((int) (*p))) gotreal++;
else if (*p == '.')
{
if (gotdecimal) return FALSE; /* can't have two */
if (gotexp) return FALSE; /* e/E preceded . */
else gotdecimal++;
}
else if (*p == 'e' || *p == 'E')
{
if (gotexp) return FALSE; /* can't have two */
else gotexp++;
}
else if (isspace((int) (*p))) break;
p++;
n--;
}
while (n && isspace((int) *p)) { p++; n--; } /* skip trailing whitespace */
return ( (n == 0 && gotreal) ? TRUE : FALSE);
}
/*----------------- end, esl_mem*() API ------------------------*/
/*****************************************************************
* 2. Benchmark driver.
*****************************************************************/
#ifdef eslMEM_BENCHMARK
#include "esl_config.h"
#include <stdio.h>
#include "easel.h"
#include "esl_buffer.h"
#include "esl_getopts.h"
#include "esl_stopwatch.h"
static ESL_OPTIONS options[] = {
/* name type default env range togs reqs incomp help docgrp */
{"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
{ 0,0,0,0,0,0,0,0,0,0},
};
static char usage[] = "[-options] <infile>";
static char banner[] = "benchmark driver for mem module";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
ESL_STOPWATCH *w = esl_stopwatch_Create();
char *infile = esl_opt_GetArg(go, 1);
ESL_BUFFER *bf = NULL;
int64_t nlines = 0;
int64_t ntokens = 0;
int64_t nchar = 0;
char *p, *tok;
esl_pos_t n, toklen;
int status;
esl_stopwatch_Start(w);
if ( esl_buffer_Open(infile, NULL, &bf) != eslOK) esl_fatal("open failed");
while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK)
{
nlines++;
while ( (status = esl_memtok(&p, &n, " \t", &tok, &toklen)) == eslOK)
{
ntokens++;
nchar += toklen;
}
if (status != eslEOL) esl_fatal("memtok failure");
}
if (status != eslEOF) esl_fatal("GetLine failure");
esl_stopwatch_Stop(w);
esl_stopwatch_Display(stdout, w, NULL);
printf("lines = %" PRId64 "\n", nlines);
printf("tokens = %" PRId64 "\n", ntokens);
printf("chars = %" PRId64 "\n", nchar);
esl_buffer_Close(bf);
esl_stopwatch_Destroy(w);
esl_getopts_Destroy(go);
return 0;
}
#endif /*eslMEM_BENCHMARK*/
/*---------------- end, benchmark driver ------------------------*/
/*****************************************************************
* 2. Unit tests
*****************************************************************/
#ifdef eslMEM_TESTDRIVE
static void
utest_mem_strtoi32(void)
{
char msg[] = "esl_mem_strtoi32() unit test failed";
int nc;
int32_t val;
int status;
if ( (status = esl_mem_strtoi32("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 2147483647", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MAX) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("-2147483648", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MIN) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 2147483648", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("-2147483649", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 214748364800", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("-214748364900", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg);
if ( (status = esl_mem_strtoi32(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg);
if ( (status = esl_mem_strtoi32("09999999", 7, 0, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg);
return;
}
static void
utest_memtok(void)
{
char msg[] = "esl_memtok() unit test failed";
char *teststring;
esl_pos_t n;
char *s;
char *tok;
esl_pos_t toklen;
if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg);
s = teststring;
n = strlen(teststring);
if (esl_memtok(&s, &n, " ", &tok, &toklen) != eslOK) esl_fatal(msg);
if (toklen != 4) esl_fatal(msg);
if (memcmp(tok, "This", toklen) != 0) esl_fatal(msg);
if (*s != 'i') esl_fatal(msg);
if (esl_memtok(&s, &n, " \t", &tok, &toklen) != eslOK) esl_fatal(msg);
if (toklen != 2) esl_fatal(msg);
if (memcmp(tok, "is", toklen) != 0) esl_fatal(msg);
if (*s != 'a') esl_fatal(msg);
if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslOK) esl_fatal(msg);
if (toklen != 11) esl_fatal(msg);
if (memcmp(tok, "a sentence.", toklen) != 0) esl_fatal(msg);
if (*s != '\0') esl_fatal(msg);
if (n != 0) esl_fatal(msg);
if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslEOL) esl_fatal(msg);
if (toklen != 0) esl_fatal(msg);
if (tok != NULL) esl_fatal(msg);
free(teststring);
return;
}
/* memspn, memcspn() */
static void
utest_memspn_memcspn(void)
{
char msg[] = "memspn/memcspn unit test failed";
char test1[] = " this is a test";
char *p;
esl_pos_t n;
p = test1;
n = 13; /* so the memory is " this is a t" */
if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg);
p = test1+2;
n = 11; /* "this is a t" */
if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg);
p = test1;
n = 2;
if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg);
p = test1+2;
n = 4;
if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg);
if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg);
}
/* memstrcmp/memstrpfx */
static void
utest_memstrcmp_memstrpfx(void)
{
char msg[] = "memstrcmp/memstrpfx unit test failed";
char test[] = "this is a test";
char *p;
esl_pos_t n;
p = test;
n = strlen(p);
if (! esl_memstrcmp(p, n, test)) esl_fatal(msg);
if ( esl_memstrcmp(p, n, "this")) esl_fatal(msg);
if (! esl_memstrpfx(p, n, "this")) esl_fatal(msg);
if ( esl_memstrpfx(p, n, "that")) esl_fatal(msg);
p = test;
n = 2; /* now p is just "th" */
if (! esl_memstrcmp(p, n, "th")) esl_fatal(msg);
if ( esl_memstrcmp(p, n, test)) esl_fatal(msg);
if (! esl_memstrpfx(p, n, "th")) esl_fatal(msg);
if ( esl_memstrpfx(p, n, "this")) esl_fatal(msg);
/* special cases involving NULLs */
p = test;
n = strlen(p);
if (! esl_memstrcmp(NULL, 0, NULL)) esl_fatal(msg);
if ( esl_memstrcmp(NULL, 0, test)) esl_fatal(msg);
if ( esl_memstrcmp(p, n, NULL)) esl_fatal(msg);
if ( esl_memstrpfx(NULL, 0, NULL)) esl_fatal(msg);
if ( esl_memstrpfx(NULL, 0, "this")) esl_fatal(msg);
if ( esl_memstrpfx(p, n, NULL)) esl_fatal(msg);
}
static void
utest_memstrcontains(void)
{
char msg[] = "memstrcontains unit test failed";
char test[] = "CLUSTAL W (1.83) multiple sequence alignment";
char *p;
esl_pos_t n;
p = test;
n = strlen(p);
if (! esl_memstrcontains(p, n, "multiple sequence alignment")) esl_fatal(msg);
if (! esl_memstrcontains(p, n, "CLUSTAL")) esl_fatal(msg);
if ( esl_memstrcontains(p, n, "alignmentx")) esl_fatal(msg);
}
#endif /*eslMEM_TESTDRIVE*/
/*------------------ end, unit tests ----------------------------*/
/*****************************************************************
* 3. Test driver
*****************************************************************/
#ifdef eslMEM_TESTDRIVE
#include "esl_config.h"
#include <stdio.h>
#include "easel.h"
#include "esl_mem.h"
#include "esl_getopts.h"
static ESL_OPTIONS options[] = {
/* name type default env range togs reqs incomp help docgrp */
{"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
{ 0,0,0,0,0,0,0,0,0,0},
};
static char usage[] = "[-options]";
static char banner[] = "test driver for mem module";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
utest_mem_strtoi32();
utest_memtok();
utest_memspn_memcspn();
utest_memstrcmp_memstrpfx();
utest_memstrcontains();
esl_getopts_Destroy(go);
return 0;
}
#endif /* eslMEM_TESTDRIVE */
/*------------------ end, test driver ---------------------------*/
/*****************************************************************
* @LICENSE@
*
* SVN $Id$
* SVN $URL$
*****************************************************************/
| Java |
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-device/www/device.js",
"id": "cordova-plugin-device.device",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"file": "plugins/cordova-plugin-device/src/browser/DeviceProxy.js",
"id": "cordova-plugin-device.DeviceProxy",
"pluginId": "cordova-plugin-device",
"runs": true
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassError.js",
"id": "cordova-plugin-device-orientation.CompassError",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"CompassError"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassHeading.js",
"id": "cordova-plugin-device-orientation.CompassHeading",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"CompassHeading"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/compass.js",
"id": "cordova-plugin-device-orientation.compass",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"navigator.compass"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/src/browser/CompassProxy.js",
"id": "cordova-plugin-device-orientation.CompassProxy",
"pluginId": "cordova-plugin-device-orientation",
"runs": true
},
{
"file": "plugins/cordova-plugin-dialogs/www/notification.js",
"id": "cordova-plugin-dialogs.notification",
"pluginId": "cordova-plugin-dialogs",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/browser/notification.js",
"id": "cordova-plugin-dialogs.notification_browser",
"pluginId": "cordova-plugin-dialogs",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/network.js",
"id": "cordova-plugin-network-information.network",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/Connection.js",
"id": "cordova-plugin-network-information.Connection",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"Connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/src/browser/network.js",
"id": "cordova-plugin-network-information.NetworkInfoProxy",
"pluginId": "cordova-plugin-network-information",
"runs": true
},
{
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"id": "cordova-plugin-splashscreen.SplashScreen",
"pluginId": "cordova-plugin-splashscreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"file": "plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js",
"id": "cordova-plugin-splashscreen.SplashScreenProxy",
"pluginId": "cordova-plugin-splashscreen",
"runs": true
},
{
"file": "plugins/cordova-plugin-statusbar/www/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar",
"pluginId": "cordova-plugin-statusbar",
"clobbers": [
"window.StatusBar"
]
},
{
"file": "plugins/cordova-plugin-statusbar/src/browser/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar.Browser",
"pluginId": "cordova-plugin-statusbar",
"merges": [
"window.StatusBar"
]
},
{
"file": "plugins/phonegap-plugin-mobile-accessibility/www/mobile-accessibility.js",
"id": "phonegap-plugin-mobile-accessibility.mobile-accessibility",
"pluginId": "phonegap-plugin-mobile-accessibility",
"clobbers": [
"window.MobileAccessibility"
]
},
{
"file": "plugins/phonegap-plugin-mobile-accessibility/www/MobileAccessibilityNotifications.js",
"id": "phonegap-plugin-mobile-accessibility.MobileAccessibilityNotifications",
"pluginId": "phonegap-plugin-mobile-accessibility",
"clobbers": [
"MobileAccessibilityNotifications"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/Acceleration.js",
"id": "cordova-plugin-device-motion.Acceleration",
"pluginId": "cordova-plugin-device-motion",
"clobbers": [
"Acceleration"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/accelerometer.js",
"id": "cordova-plugin-device-motion.accelerometer",
"pluginId": "cordova-plugin-device-motion",
"clobbers": [
"navigator.accelerometer"
]
},
{
"file": "plugins/cordova-plugin-device-motion/src/browser/AccelerometerProxy.js",
"id": "cordova-plugin-device-motion.AccelerometerProxy",
"pluginId": "cordova-plugin-device-motion",
"runs": true
},
{
"file": "plugins/cordova-plugin-globalization/www/GlobalizationError.js",
"id": "cordova-plugin-globalization.GlobalizationError",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"window.GlobalizationError"
]
},
{
"file": "plugins/cordova-plugin-globalization/www/globalization.js",
"id": "cordova-plugin-globalization.globalization",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"navigator.globalization"
]
},
{
"file": "plugins/cordova-plugin-globalization/www/browser/moment.js",
"id": "cordova-plugin-globalization.moment",
"pluginId": "cordova-plugin-globalization",
"runs": true
},
{
"file": "plugins/cordova-plugin-globalization/src/browser/GlobalizationProxy.js",
"id": "cordova-plugin-globalization.GlobalizationProxy",
"pluginId": "cordova-plugin-globalization",
"runs": true
},
{
"file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js",
"id": "cordova-plugin-inappbrowser.inappbrowser",
"pluginId": "cordova-plugin-inappbrowser",
"clobbers": [
"cordova.InAppBrowser.open",
"window.open"
]
},
{
"file": "plugins/cordova-plugin-inappbrowser/src/browser/InAppBrowserProxy.js",
"id": "cordova-plugin-inappbrowser.InAppBrowserProxy",
"pluginId": "cordova-plugin-inappbrowser",
"merges": [
""
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"id": "cordova-plugin-file.DirectoryEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"id": "cordova-plugin-file.DirectoryReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/Entry.js",
"id": "cordova-plugin-file.Entry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"file": "plugins/cordova-plugin-file/www/File.js",
"id": "cordova-plugin-file.File",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"id": "cordova-plugin-file.FileEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileError.js",
"id": "cordova-plugin-file.FileError",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"id": "cordova-plugin-file.FileReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"id": "cordova-plugin-file.FileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"id": "cordova-plugin-file.FileUploadOptions",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"id": "cordova-plugin-file.FileUploadResult",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"id": "cordova-plugin-file.FileWriter",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"file": "plugins/cordova-plugin-file/www/Flags.js",
"id": "cordova-plugin-file.Flags",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"id": "cordova-plugin-file.LocalFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"id": "cordova-plugin-file.Metadata",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"id": "cordova-plugin-file.ProgressEvent",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"id": "cordova-plugin-file.fileSystems",
"pluginId": "cordova-plugin-file"
},
{
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"id": "cordova-plugin-file.requestFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"id": "cordova-plugin-file.isChrome",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/Preparing.js",
"id": "cordova-plugin-file.Preparing",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/src/browser/FileProxy.js",
"id": "cordova-plugin-file.browserFileProxy",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"id": "cordova-plugin-file.fileSystemPaths",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/FileSystem.js",
"id": "cordova-plugin-file.firefoxFileSystem",
"pluginId": "cordova-plugin-file",
"merges": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-media/www/MediaError.js",
"id": "cordova-plugin-media.MediaError",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.MediaError"
]
},
{
"file": "plugins/cordova-plugin-media/www/Media.js",
"id": "cordova-plugin-media.Media",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.Media"
]
},
{
"file": "plugins/cordova-plugin-media/www/browser/Media.js",
"id": "cordova-plugin-media.BrowserMedia",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.Media"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-console": "1.0.5",
"cordova-plugin-device": "1.1.4",
"cordova-plugin-device-orientation": "1.0.5",
"cordova-plugin-dialogs": "1.2.1",
"cordova-plugin-network-information": "1.2.1",
"cordova-plugin-splashscreen": "3.2.2",
"cordova-plugin-statusbar": "2.1.3",
"cordova-plugin-whitelist": "1.2.2",
"phonegap-plugin-mobile-accessibility": "1.0.5-dev",
"cordova-plugin-device-motion": "1.2.4",
"cordova-plugin-globalization": "1.0.6",
"cordova-plugin-inappbrowser": "1.3.0",
"cordova-plugin-compat": "1.1.0",
"cordova-plugin-file": "4.3.2",
"cordova-plugin-media": "2.2.0"
}
// BOTTOM OF METADATA
}); | Java |
<?php
// Controller for latestdeaths.
class Deaths extends Controller {
public function index() {
require("config.php");
$this->load->database();
if(@$_REQUEST['world'] == 0)
$world = 0;
else
$world = (int)@$_REQUEST['world'];
$world_name = ($config['worlds'] == $world);
$players_deaths = $this->db->query('SELECT `player_deaths`.`id`, `player_deaths`.`date`, `player_deaths`.`level`, `players`.`name`, `players`.`world_id` FROM `player_deaths` LEFT JOIN `players` ON `player_deaths`.`player_id` = `players`.`id` ORDER BY `date` DESC LIMIT 0,'.$config['latestdeathlimit'])->result();
if (!empty($players_deaths))
{
foreach ($players_deaths as $death)
{
$sql = $this->db->query('SELECT environment_killers.name AS monster_name, players.name AS player_name, players.deleted AS player_exists FROM killers LEFT JOIN environment_killers ON killers.id = environment_killers.kill_id LEFT JOIN player_killers ON killers.id = player_killers.kill_id LEFT JOIN players ON players.id = player_killers.player_id WHERE killers.death_id = '.$death->id.' ORDER BY killers.final_hit DESC, killers.id ASC')->result();
$players_rows = '<td><a href="?subtopic=characters&name='.urlencode($death->name).'"><b>'.$death->name.'</b></a> ';
$i = 0;
$count = count($death);
foreach($sql as $deaths)
{
$i++;
if($deaths->player_name != "")
{
if($i == 1)
$players_rows .= "killed at level <b>".$death->level."</b>";
else if($i == $count)
$players_rows .= " and";
else
$players_rows .= ",";
$players_rows .= " by ";
if($deaths->monster_name != "")
$players_rows .= $deaths->monster_name." summoned by ";
if($deaths->player_exists == 0)
$players_rows .= "<a href=\"index.php?subtopic=characters&name=".urlencode($deaths->player_name)."\">";
$players_rows .= $deaths->player_name;
if($deaths->player_exists == 0)
$players_rows .= "</a>";
}
else
{
if($i == 1)
$players_rows .= "died at level <b>".$death->level."</b>";
else if($i == $count)
$players_rows .= " and";
else
$players_rows .= ",";
$players_rows .= " by ".$deaths->monster_name;
}
$players_rows .= "</td>";
$data['deaths'][] = array('players_rows'=>$players_rows,'date'=>$death->date,'name'=>$death->name,'player_name'=>$deaths->player_name,'monster_name'=>$deaths->monster_name,'player_exists'=>$deaths->player_exists);
$players_rows = "";
}
}
$this->load->helper("form");
$this->load->view("deaths", $data);
}
else
{
echo "<h1>There are no players killed yet.</h1>";
}
}
}
?> | Java |
#!/bin/bash
#
# flashx.tv module
# Copyright (c) 2014 Plowshare team
#
# This file is part of Plowshare.
#
# Plowshare 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.
#
# Plowshare 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 Plowshare. If not, see <http://www.gnu.org/licenses/>.
MODULE_FLASHX_REGEXP_URL='http://\(www\.\)\?flashx\.tv/'
MODULE_FLASHX_DOWNLOAD_OPTIONS=""
MODULE_FLASHX_DOWNLOAD_RESUME=yes
MODULE_FLASHX_DOWNLOAD_FINAL_LINK_NEEDS_COOKIE=no
MODULE_FLASHX_DOWNLOAD_SUCCESSIVE_INTERVAL=
MODULE_FLASHX_DOWNLOAD_FINAL_LINK_NEEDS_EXTRA=
MODULE_FLASHX_PROBE_OPTIONS=""
# Output a flashx file download URL
# $1: cookie file
# $2: flashx url
# stdout: real file download link
flashx_download() {
local -r COOKIE_FILE=$1
local -r URL=$2
local PAGE CONFIG_URL EMBED_URL FILE_NAME FILE_URL
PAGE=$(curl -c "$COOKIE_FILE" --location "$URL") || return
if match 'Video not found, deleted, abused or wrong link\|Video not found, deleted or abused, sorry!' \
"$PAGE"; then
return $ERR_LINK_DEAD
fi
if match '<h2>404 Error</h2>' "$PAGE"; then
return $ERR_LINK_DEAD
fi
FILE_NAME=$(parse_tag '<div class=.video_title' 'div' <<< "$PAGE" | html_to_utf8) || return
# On main page
EMBED_URL=$(echo "$PAGE" | parse '<div class="player_container_new"' 'src="\([^"]*\)' 1) || return
PAGE=$(curl -b "$COOKIE_FILE" "$EMBED_URL") || return
# Inside iframe embed on main page
local FORM_HTML FORM_URL FORM_HASH FORM_SEC_HASH
FORM_HTML=$(grep_form_by_name "$PAGE" 'fxplayit') || return
FORM_URL=$(echo "$FORM_HTML" | parse_form_action) || return
FORM_HASH=$(echo "$FORM_HTML" | parse_form_input_by_name 'hash') || return
FORM_SEC_HASH=$(echo "$FORM_HTML" | parse_form_input_by_name 'sechash') || return
PAGE=$(curl -b "$COOKIE_FILE" \
--referer "$EMBED_URL" \
--data "hash=$FORM_HASH" \
--data "sechash=$FORM_SEC_HASH" \
--header "Cookie: refid=; vr_referrer=" \
"$(basename_url "$EMBED_URL")/player/$FORM_URL") || return
# Player's response
CONFIG_URL=$(echo "$PAGE" | parse '<param name="movie"' 'config=\([^"]*\)') || return
PAGE=$(curl -b "$COOKIE_FILE" --location "$CONFIG_URL") || return
# XML config file
FILE_URL=$(parse_tag 'file' <<< "$PAGE") || return
echo "$FILE_URL"
echo "$FILE_NAME"
}
# Probe a download URL
# $1: cookie file (unused here)
# $2: flashx.tv url
# $3: requested capability list
# stdout: 1 capability per line
flashx_probe() {
local -r URL=$2
local -r REQ_IN=$3
local PAGE REQ_OUT FILE_NAME
PAGE=$(curl --location "$URL") || return
if match 'Video not found, deleted, abused or wrong link\|Video not found, deleted or abused, sorry!' \
"$PAGE"; then
return $ERR_LINK_DEAD
fi
if match '<h2>404 Error</h2>' "$PAGE"; then
return $ERR_LINK_DEAD
fi
REQ_OUT=c
if [[ $REQ_IN = *f* ]]; then
FILE_NAME=$(parse_tag '<div class="video_title"' 'div' <<< "$PAGE" | html_to_utf8) && \
echo "$FILE_NAME" && REQ_OUT="${REQ_OUT}f"
fi
echo $REQ_OUT
}
| Java |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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/>.
from typing import Any, Dict, Set
from snapcraft import project
from snapcraft.internal.project_loader import grammar
from snapcraft.internal import pluginhandler, repo
from ._package_transformer import package_transformer
class PartGrammarProcessor:
"""Process part properties that support grammar.
Stage packages example:
>>> from unittest import mock
>>> import snapcraft
>>> # Pretend that all packages are valid
>>> repo = mock.Mock()
>>> repo.is_valid.return_value = True
>>> plugin = mock.Mock()
>>> plugin.stage_packages = [{'try': ['foo']}]
>>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties={},
... project=snapcraft.project.Project(),
... repo=repo)
>>> processor.get_stage_packages()
{'foo'}
Build packages example:
>>> from unittest import mock
>>> import snapcraft
>>> # Pretend that all packages are valid
>>> repo = mock.Mock()
>>> repo.is_valid.return_value = True
>>> plugin = mock.Mock()
>>> plugin.build_packages = [{'try': ['foo']}]
>>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties={},
... project=snapcraft.project.Project(),
... repo=repo)
>>> processor.get_build_packages()
{'foo'}
Source example:
>>> from unittest import mock
>>> import snapcraft
>>> plugin = mock.Mock()
>>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']}
>>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties=plugin.properties,
... project=snapcraft.project.Project(),
... repo=None)
>>> processor.get_source()
'foo'
"""
def __init__(
self,
*,
plugin: pluginhandler.PluginHandler,
properties: Dict[str, Any],
project: project.Project,
repo: "repo.Ubuntu"
) -> None:
self._project = project
self._repo = repo
self._build_snap_grammar = getattr(plugin, "build_snaps", [])
self.__build_snaps = set() # type: Set[str]
self._build_package_grammar = getattr(plugin, "build_packages", [])
self.__build_packages = set() # type: Set[str]
self._stage_package_grammar = getattr(plugin, "stage_packages", [])
self.__stage_packages = set() # type: Set[str]
source_grammar = properties.get("source", [""])
if not isinstance(source_grammar, list):
self._source_grammar = [source_grammar]
else:
self._source_grammar = source_grammar
self.__source = ""
def get_source(self) -> str:
if not self.__source:
# The grammar is array-based, even though we only support a single
# source.
processor = grammar.GrammarProcessor(
self._source_grammar, self._project, lambda s: True
)
source_array = processor.process()
if len(source_array) > 0:
self.__source = source_array.pop()
return self.__source
def get_build_snaps(self) -> Set[str]:
if not self.__build_snaps:
processor = grammar.GrammarProcessor(
self._build_snap_grammar,
self._project,
repo.snaps.SnapPackage.is_valid_snap,
)
self.__build_snaps = processor.process()
return self.__build_snaps
def get_build_packages(self) -> Set[str]:
if not self.__build_packages:
processor = grammar.GrammarProcessor(
self._build_package_grammar,
self._project,
self._repo.build_package_is_valid,
transformer=package_transformer,
)
self.__build_packages = processor.process()
return self.__build_packages
def get_stage_packages(self) -> Set[str]:
if not self.__stage_packages:
processor = grammar.GrammarProcessor(
self._stage_package_grammar,
self._project,
self._repo.is_valid,
transformer=package_transformer,
)
self.__stage_packages = processor.process()
return self.__stage_packages
| Java |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestEInvoiceRequestLog(unittest.TestCase):
pass
| Java |
#include <cmath>
#include <cfloat> // DBL_MAX
#include "Action_GIST.h"
#include "CpptrajStdio.h"
#include "Constants.h"
#include "DataSet_MatrixFlt.h"
#include "DataSet_GridFlt.h"
#include "DataSet_GridDbl.h"
#include "ProgressBar.h"
#include "StringRoutines.h"
#include "DistRoutines.h"
#ifdef _OPENMP
# include <omp.h>
#endif
const double Action_GIST::maxD_ = DBL_MAX;
Action_GIST::Action_GIST() :
debug_(0),
numthreads_(1),
#ifdef CUDA
numberAtoms_(0),
numberAtomTypes_(0),
headAtomType_(0),
solvent_(NULL),
NBindex_c_(NULL),
molecule_c_(NULL),
paramsLJ_c_(NULL),
max_c_(NULL),
min_c_(NULL),
result_w_c_(NULL),
result_s_c_(NULL),
result_O_c_(NULL),
result_N_c_(NULL),
#endif
gridspacing_(0),
gridcntr_(0.0),
griddim_(0.0),
gO_(0),
gH_(0),
Esw_(0),
Eww_(0),
dTStrans_(0),
dTSorient_(0),
dTSsix_(0),
neighbor_norm_(0),
dipole_(0),
order_norm_(0),
dipolex_(0),
dipoley_(0),
dipolez_(0),
PME_(0),
U_PME_(0),
ww_Eij_(0),
G_max_(0.0),
CurrentParm_(0),
datafile_(0),
eijfile_(0),
infofile_(0),
fltFmt_(TextFormat::GDOUBLE),
intFmt_(TextFormat::INTEGER),
BULK_DENS_(0.0),
temperature_(0.0),
NeighborCut2_(12.25), // 3.5^2
// system_potential_energy_(0),
// solute_potential_energy_(0),
MAX_GRID_PT_(0),
NSOLVENT_(0),
N_ON_GRID_(0),
nMolAtoms_(0),
NFRAME_(0),
max_nwat_(0),
doOrder_(false),
doEij_(false),
skipE_(false),
includeIons_(true)
{}
/** GIST help */
void Action_GIST::Help() const {
mprintf("\t[doorder] [doeij] [skipE] [skipS] [refdens <rdval>] [temp <tval>]\n"
"\t[noimage] [gridcntr <xval> <yval> <zval>] [excludeions]\n"
"\t[griddim <nx> <ny> <nz>] [gridspacn <spaceval>] [neighborcut <ncut>]\n"
"\t[prefix <filename prefix>] [ext <grid extension>] [out <output suffix>]\n"
"\t[floatfmt {double|scientific|general}] [floatwidth <fw>] [floatprec <fp>]\n"
"\t[intwidth <iw>]\n"
"\t[info <info suffix>]\n");
# ifdef LIBPME
mprintf("\t[nopme|pme %s\n\t %s\n\t %s]\n", EwaldOptions::KeywordsCommon1(), EwaldOptions::KeywordsCommon2(), EwaldOptions::KeywordsPME());
# endif
mprintf("Perform Grid Inhomogenous Solvation Theory calculation.\n"
#ifdef CUDA
"The option doeij is not available, when using the CUDA accelerated version,\n"
"as this would need way too much memory."
#endif
);
}
/** Init GIST action. */
Action::RetType Action_GIST::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
debug_ = debugIn;
# ifdef MPI
if (init.TrajComm().Size() > 1) {
mprinterr("Error: 'gist' action does not work with > 1 process (%i processes currently).\n",
init.TrajComm().Size());
return Action::ERR;
}
# endif
gist_init_.Start();
prefix_ = actionArgs.GetStringKey("prefix");
if (prefix_.empty()) prefix_.assign("gist");
std::string ext = actionArgs.GetStringKey("ext");
if (ext.empty()) ext.assign(".dx");
std::string gistout = actionArgs.GetStringKey("out");
if (gistout.empty()) gistout.assign(prefix_ + "-output.dat");
datafile_ = init.DFL().AddCpptrajFile( gistout, "GIST output" );
if (datafile_ == 0) return Action::ERR;
// Info file: if not specified use STDOUT
gistout = actionArgs.GetStringKey("info");
if (!gistout.empty()) gistout = prefix_ + "-" + gistout;
infofile_ = init.DFL().AddCpptrajFile( gistout, "GIST info", DataFileList::TEXT, true );
if (infofile_ == 0) return Action::ERR;
// Grid files
DataFile* file_gO = init.DFL().AddDataFile( prefix_ + "-gO" + ext );
DataFile* file_gH = init.DFL().AddDataFile( prefix_ + "-gH" + ext );
DataFile* file_Esw = init.DFL().AddDataFile(prefix_ + "-Esw-dens" + ext);
DataFile* file_Eww = init.DFL().AddDataFile(prefix_ + "-Eww-dens" + ext);
DataFile* file_dTStrans = init.DFL().AddDataFile(prefix_ + "-dTStrans-dens" + ext);
DataFile* file_dTSorient = init.DFL().AddDataFile(prefix_ + "-dTSorient-dens" + ext);
DataFile* file_dTSsix = init.DFL().AddDataFile(prefix_ + "-dTSsix-dens" + ext);
DataFile* file_neighbor_norm = init.DFL().AddDataFile(prefix_ + "-neighbor-norm" + ext);
DataFile* file_dipole = init.DFL().AddDataFile(prefix_ + "-dipole-dens" + ext);
DataFile* file_order_norm = init.DFL().AddDataFile(prefix_ + "-order-norm" + ext);
DataFile* file_dipolex = init.DFL().AddDataFile(prefix_ + "-dipolex-dens" + ext);
DataFile* file_dipoley = init.DFL().AddDataFile(prefix_ + "-dipoley-dens" + ext);
DataFile* file_dipolez = init.DFL().AddDataFile(prefix_ + "-dipolez-dens" + ext);
// Output format keywords
std::string floatfmt = actionArgs.GetStringKey("floatfmt");
if (!floatfmt.empty()) {
if (floatfmt == "double")
fltFmt_.SetFormatType(TextFormat::DOUBLE);
else if (floatfmt == "scientific")
fltFmt_.SetFormatType(TextFormat::SCIENTIFIC);
else if (floatfmt == "general")
fltFmt_.SetFormatType(TextFormat::GDOUBLE);
else {
mprinterr("Error: Unrecognized format type for 'floatfmt': %s\n", floatfmt.c_str());
return Action::ERR;
}
}
fltFmt_.SetFormatWidthPrecision( actionArgs.getKeyInt("floatwidth", 0),
actionArgs.getKeyInt("floatprec", -1) );
intFmt_.SetFormatWidth( actionArgs.getKeyInt("intwidth", 0) );
// Other keywords
double neighborCut = actionArgs.getKeyDouble("neighborcut", 3.5);
NeighborCut2_ = neighborCut * neighborCut;
includeIons_ = !actionArgs.hasKey("excludeions");
imageOpt_.InitImaging( !(actionArgs.hasKey("noimage")), actionArgs.hasKey("nonortho") );
doOrder_ = actionArgs.hasKey("doorder");
doEij_ = actionArgs.hasKey("doeij");
#ifdef CUDA
if (this->doEij_) {
mprinterr("Error: 'doeij' cannot be specified when using CUDA.\n");
return Action::ERR;
}
#endif
skipE_ = actionArgs.hasKey("skipE");
if (skipE_) {
if (doEij_) {
mprinterr("Error: 'doeij' cannot be specified if 'skipE' is specified.\n");
return Action::ERR;
}
}
// Parse PME options
// TODO once PME output is stable, make pme true the default when LIBPME present.
//# ifdef LIBPME
// usePme_ = true;
//# else
usePme_ = false;
//# endif
# ifdef CUDA
// Disable PME for CUDA
usePme_ = false;
# endif
if (actionArgs.hasKey("pme"))
usePme_ = true;
else if (actionArgs.hasKey("nopme"))
usePme_ = false;
// PME and doeij are not compatible
if (usePme_ && doEij_) {
mprinterr("Error: 'doeij' cannot be used with PME. Specify 'nopme' to use 'doeij'\n");
return Action::ERR;
}
if (usePme_) {
# ifdef LIBPME
pmeOpts_.AllowLjPme(false);
if (pmeOpts_.GetOptions(EwaldOptions::PME, actionArgs, "GIST")) {
mprinterr("Error: Getting PME options for GIST failed.\n");
return Action::ERR;
}
# else
mprinterr("Error: 'pme' with GIST requires compilation with LIBPME.\n");
return Action::ERR;
# endif
}
DataFile* file_energy_pme = 0;
DataFile* file_U_energy_pme = 0;
if (usePme_) {
file_energy_pme = init.DFL().AddDataFile(prefix_ + "-Water-Etot-pme-dens" + ext);
file_U_energy_pme = init.DFL().AddDataFile(prefix_ + "-Solute-Etot-pme-dens"+ ext);
}
this->skipS_ = actionArgs.hasKey("skipS");
if (doEij_) {
eijfile_ = init.DFL().AddCpptrajFile(prefix_ + "-Eww_ij.dat", "GIST Eij matrix file");
if (eijfile_ == 0) return Action::ERR;
}
// Set Bulk Density 55.5M
BULK_DENS_ = actionArgs.getKeyDouble("refdens", 0.0334);
if ( BULK_DENS_ > (0.0334*1.2) )
mprintf("Warning: water reference density is high, consider using 0.0334 for 1g/cc water density\n");
else if ( BULK_DENS_ < (0.0334*0.8) )
mprintf("Warning: water reference density is low, consider using 0.0334 for 1g/cc water density\n");
temperature_ = actionArgs.getKeyDouble("temp", 300.0);
if (temperature_ < 0.0) {
mprinterr("Error: Negative temperature specified.\n");
return Action::ERR;
}
// Grid spacing
gridspacing_ = actionArgs.getKeyDouble("gridspacn", 0.50);
// Grid center
gridcntr_ = Vec3(0.0);
if ( actionArgs.hasKey("gridcntr") ) {
gridcntr_[0] = actionArgs.getNextDouble(-1);
gridcntr_[1] = actionArgs.getNextDouble(-1);
gridcntr_[2] = actionArgs.getNextDouble(-1);
} else
mprintf("Warning: No grid center values specified, using default (origin)\n");
// Grid dimensions
int nx = 40;
int ny = 40;
int nz = 40;
if ( actionArgs.hasKey("griddim") ) {
nx = actionArgs.getNextInteger(-1);
ny = actionArgs.getNextInteger(-1);
nz = actionArgs.getNextInteger(-1);
} else
mprintf("Warning: No grid dimension values specified, using default (40,40,40)\n");
griddim_ = Vec3((double)nx, (double)ny, (double)nz);
// Data set name
std::string dsname = actionArgs.GetStringKey("name");
if (dsname.empty())
dsname = init.DSL().GenerateDefaultName("GIST");
// Set up DataSets.
gO_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gO"));
gH_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gH"));
Esw_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Esw"));
Eww_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Eww"));
dTStrans_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTStrans"));
dTSorient_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSorient"));
dTSsix_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSsix"));
neighbor_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "neighbor"));
dipole_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dipole"));
order_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "order"));
dipolex_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolex"));
dipoley_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipoley"));
dipolez_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolez"));
if (gO_==0 || gH_==0 || Esw_==0 || Eww_==0 || dTStrans_==0 || dTSorient_==0 ||
dTSsix_==0 || neighbor_norm_==0 || dipole_==0 || order_norm_==0 ||
dipolex_==0 || dipoley_==0 || dipolez_==0)
return Action::ERR;
if (usePme_) {
PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname,"PME"));
U_PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT,MetaData(dsname,"U_PME"));
if (PME_ == 0 || U_PME_ == 0) return Action::ERR;
}
if (doEij_) {
ww_Eij_ = (DataSet_MatrixFlt*)init.DSL().AddSet(DataSet::MATRIX_FLT, MetaData(dsname, "Eij"));
if (ww_Eij_ == 0) return Action::ERR;
}
// Allocate DataSets. TODO non-orthogonal grids as well
Vec3 v_spacing( gridspacing_ );
gO_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
MAX_GRID_PT_ = gO_->Size();
gH_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
Esw_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
Eww_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTStrans_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTSorient_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTSsix_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
neighbor_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipole_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
order_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipolex_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipoley_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipolez_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
if (usePme_) {
PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing);
U_PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing);
}
if (ww_Eij_ != 0) {
if (ww_Eij_->AllocateTriangle( MAX_GRID_PT_ )) {
mprinterr("Error: Could not allocate memory for water-water Eij matrix.\n");
return Action::ERR;
}
}
// Add sets to files
file_gO->AddDataSet( gO_ );
file_gH->AddDataSet( gH_ );
file_Esw->AddDataSet( Esw_ );
file_Eww->AddDataSet( Eww_ );
file_dTStrans->AddDataSet( dTStrans_ );
file_dTSorient->AddDataSet( dTSorient_ );
file_dTSsix->AddDataSet( dTSsix_ );
file_neighbor_norm->AddDataSet( neighbor_norm_ );
file_dipole->AddDataSet( dipole_ );
file_order_norm->AddDataSet( order_norm_ );
file_dipolex->AddDataSet( dipolex_ );
file_dipoley->AddDataSet( dipoley_ );
file_dipolez->AddDataSet( dipolez_ );
if (usePme_) {
file_energy_pme->AddDataSet(PME_);
file_U_energy_pme->AddDataSet(U_PME_);
}
// Set up grid params TODO non-orthogonal as well
G_max_ = Vec3( (double)nx * gridspacing_ + 1.5,
(double)ny * gridspacing_ + 1.5,
(double)nz * gridspacing_ + 1.5 );
N_waters_.assign( MAX_GRID_PT_, 0 );
N_solute_atoms_.assign( MAX_GRID_PT_, 0);
N_hydrogens_.assign( MAX_GRID_PT_, 0 );
voxel_xyz_.resize( MAX_GRID_PT_ ); // [] = X Y Z
voxel_Q_.resize( MAX_GRID_PT_ ); // [] = W4 X4 Y4 Z4
numthreads_ = 1;
# ifdef _OPENMP
# pragma omp parallel
{
if (omp_get_thread_num() == 0)
numthreads_ = omp_get_num_threads();
}
# endif
if (!skipE_) {
E_UV_VDW_.resize( numthreads_ );
E_UV_Elec_.resize( numthreads_ );
E_VV_VDW_.resize( numthreads_ );
E_VV_Elec_.resize( numthreads_ );
neighbor_.resize( numthreads_ );
for (int thread = 0; thread != numthreads_; thread++) {
E_UV_VDW_[thread].assign( MAX_GRID_PT_, 0 );
E_UV_Elec_[thread].assign( MAX_GRID_PT_, 0 );
E_VV_VDW_[thread].assign( MAX_GRID_PT_, 0 );
E_VV_Elec_[thread].assign( MAX_GRID_PT_, 0 );
neighbor_[thread].assign( MAX_GRID_PT_, 0 );
}
if (usePme_) {
E_pme_.assign( MAX_GRID_PT_, 0 );
U_E_pme_.assign( MAX_GRID_PT_, 0 );
//E_pme_.resize( numthreads_);
//U_E_pme_.resize(numthreads_);
//for (int thread = 0; thread != numthreads_; thread++) {
// E_pme_[thread].assign( MAX_GRID_PT_,0);
// U_E_pme_[thread].assign( MAX_GRID_PT_,0);
//}
}
# ifdef _OPENMP
if (doEij_) {
// Since allocating a separate matrix for every thread will consume a lot
// of memory and since the Eij matrices tend to be sparse since solute is
// often present, each thread will record any interaction energies they
// calculate separately and add to the Eij matrix afterwards to avoid
// memory clashes. Probably not ideal if the bulk of the grid is water however.
EIJ_V1_.resize( numthreads_ );
EIJ_V2_.resize( numthreads_ );
EIJ_EN_.resize( numthreads_ );
}
# endif
#ifdef CUDA
if (this->skipE_ && this->doOrder_) {
mprintf("When the keyword \"skipE\" is supplied, \"doorder\" cannot be"
" chosen, as both calculations are done on the GPU at the same"
" time.\nIgnoring \"doorder!\"\n");
}
#endif
}
//Box gbox;
//gbox.SetBetaLengths( 90.0, (double)nx * gridspacing_,
// (double)ny * gridspacing_,
// (double)nz * gridspacing_ );
//grid_.Setup_O_Box( nx, ny, nz, gO_->GridOrigin(), gbox );
//grid_.Setup_O_D( nx, ny, nz, gO_->GridOrigin(), v_spacing );
mprintf(" GIST:\n");
mprintf("\tOutput prefix= '%s', grid output extension= '%s'\n", prefix_.c_str(), ext.c_str());
mprintf("\tOutput float format string= '%s', output integer format string= '%s'\n", fltFmt_.fmt(), intFmt_.fmt());
mprintf("\tGIST info written to '%s'\n", infofile_->Filename().full());
mprintf("\tName for data sets: %s\n", dsname.c_str());
if (doOrder_)
mprintf("\tDoing order calculation.\n");
else
mprintf("\tSkipping order calculation.\n");
if (skipE_)
mprintf("\tSkipping energy calculation.\n");
else {
mprintf("\tPerforming energy calculation.\n");
if (numthreads_ > 1)
mprintf("\tParallelizing energy calculation with %i threads.\n", numthreads_);
if (usePme_) {
mprintf("\tUsing PME.\n");
pmeOpts_.PrintOptions();
}
}
mprintf("\tCut off for determining solvent O-O neighbors is %f Ang\n", sqrt(NeighborCut2_));
if (includeIons_)
mprintf("\tIons will be included in the solute region.\n");
else
mprintf("\tIons will be excluded from the calculation.\n");
if (doEij_) {
mprintf("\tComputing and printing water-water Eij matrix, output to '%s'\n",
eijfile_->Filename().full());
mprintf("\tWater-water Eij matrix size is %s\n",
ByteString(ww_Eij_->MemUsageInBytes(), BYTE_DECIMAL).c_str());
} else
mprintf("\tSkipping water-water Eij matrix.\n");
mprintf("\tWater reference density: %6.4f molecules/Ang^3\n", BULK_DENS_);
mprintf("\tSimulation temperature: %6.4f K\n", temperature_);
if (imageOpt_.UseImage())
mprintf("\tDistances will be imaged.\n");
else
mprintf("\tDistances will not be imaged.\n");
if (imageOpt_.ForceNonOrtho())
mprintf("\tWill use non-orthogonal imaging routines for all cell types.\n");
gO_->GridInfo();
mprintf("\tNumber of voxels: %u, voxel volume: %f Ang^3\n",
MAX_GRID_PT_, gO_->Bin().VoxelVolume());
mprintf("#Please cite these papers if you use GIST results in a publication:\n"
"# Steven Ramsey, Crystal Nguyen, Romelia Salomon-Ferrer, Ross C. Walker, Michael K. Gilson, and Tom Kurtzman. J. Comp. Chem. 37 (21) 2016\n"
"# Crystal Nguyen, Michael K. Gilson, and Tom Young, arXiv:1108.4876v1 (2011)\n"
"# Crystal N. Nguyen, Tom Kurtzman Young, and Michael K. Gilson,\n"
"# J. Chem. Phys. 137, 044101 (2012)\n"
"# Lazaridis, J. Phys. Chem. B 102, 3531–3541 (1998)\n"
#ifdef LIBPME
"#When using the PME-enhanced version of GIST, please cite:\n"
"# Lieyang Chen, Anthony Cruz, Daniel R. Roe, Andy C. Simmonett, Lauren Wickstrom, Nanjie Deng, Tom Kurtzman. JCTC (2021) DOI: 10.1021/acs.jctc.0c01185\n"
#endif
#ifdef CUDA
"#When using the GPU parallelized version of GIST, please cite:\n"
"# Johannes Kraml, Anna S. Kamenik, Franz Waibl, Michael Schauperl, Klaus R. Liedl, JCTC (2019)\n"
#endif
);
# ifdef GIST_USE_NONORTHO_DIST2
mprintf("DEBUG: Using regular non-orthogonal distance routine.\n");
# endif
gist_init_.Stop();
return Action::OK;
}
/// \return True if given floating point values are not equal within a tolerance
static inline bool NotEqual(double v1, double v2) { return ( fabs(v1 - v2) > Constants::SMALL ); }
/** Set up GIST action. */
Action::RetType Action_GIST::Setup(ActionSetup& setup) {
gist_setup_.Start();
CurrentParm_ = setup.TopAddress();
// We need box info
if (!setup.CoordInfo().TrajBox().HasBox()) {
mprinterr("Error: Must have explicit solvent with periodic boundaries!");
return Action::ERR;
}
imageOpt_.SetupImaging( setup.CoordInfo().TrajBox().HasBox() );
#ifdef CUDA
this->numberAtoms_ = setup.Top().Natom();
this->solvent_ = new bool[this->numberAtoms_];
#endif
// Initialize PME
if (usePme_) {
# ifdef LIBPME
if (gistPme_.Init( setup.CoordInfo().TrajBox(), pmeOpts_, debug_ )) {
mprinterr("Error: GIST PME init failed.\n");
return Action::ERR;
}
// By default all atoms are selected for GIST PME to match up with atom_voxel_ array.
if (gistPme_.Setup_PME_GIST( setup.Top(), numthreads_, NeighborCut2_ )) {
mprinterr("Error: GIST PME setup/array allocation failed.\n");
return Action::ERR;
}
# else
mprinterr("Error: GIST PME requires compilation with LIBPME.\n");
return Action::ERR;
# endif
}
// Get molecule number for each solvent molecule
//mol_nums_.clear();
O_idxs_.clear();
A_idxs_.clear();
atom_voxel_.clear();
atomIsSolute_.clear();
atomIsSolventO_.clear();
U_idxs_.clear();
// NOTE: these are just guesses
O_idxs_.reserve( setup.Top().Nsolvent() );
A_idxs_.reserve( setup.Top().Natom() );
// atom_voxel_ and atomIsSolute will be indexed by atom #
atom_voxel_.assign( setup.Top().Natom(), OFF_GRID_ );
atomIsSolute_.assign(setup.Top().Natom(), false);
atomIsSolventO_.assign(setup.Top().Natom(), false);
U_idxs_.reserve(setup.Top().Natom()-setup.Top().Nsolvent()*nMolAtoms_);
unsigned int midx = 0;
unsigned int NsolventAtoms = 0;
unsigned int NsoluteAtoms = 0;
bool isFirstSolvent = true;
for (Topology::mol_iterator mol = setup.Top().MolStart();
mol != setup.Top().MolEnd(); ++mol, ++midx)
{
if (mol->IsSolvent()) {
// NOTE: We assume the oxygen is the first atom!
int o_idx = mol->MolUnit().Front();
#ifdef CUDA
this->headAtomType_ = setup.Top()[o_idx].TypeIndex();
#endif
// Check that molecule has correct # of atoms
unsigned int molNumAtoms = (unsigned int)mol->NumAtoms();
if (nMolAtoms_ == 0) {
nMolAtoms_ = molNumAtoms;
mprintf("\tEach solvent molecule has %u atoms\n", nMolAtoms_);
} else if (molNumAtoms != nMolAtoms_) {
mprinterr("Error: All solvent molecules must have same # atoms.\n"
"Error: Molecule '%s' has %u atoms, expected %u.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str(),
molNumAtoms, nMolAtoms_);
return Action::ERR;
}
//mol_nums_.push_back( midx ); // TODO needed?
// Check that first atom is actually Oxygen
if (setup.Top()[o_idx].Element() != Atom::OXYGEN) {
mprinterr("Error: Molecule '%s' is not water or does not have oxygen atom.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str());
return Action::ERR;
}
O_idxs_.push_back( o_idx );
atomIsSolventO_[o_idx] = true;
// Check that the next two atoms are Hydrogens
if (setup.Top()[o_idx+1].Element() != Atom::HYDROGEN ||
setup.Top()[o_idx+2].Element() != Atom::HYDROGEN)
{
mprinterr("Error: Molecule '%s' does not have hydrogen atoms.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str());
return Action::ERR;
}
// Save all atom indices for energy calc, including extra points
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
A_idxs_.push_back( o_idx + IDX );
atomIsSolute_[A_idxs_.back()] = false; // The identity of the atom is water
atom_voxel_[A_idxs_.back()] = OFF_GRID_;
#ifdef CUDA
this->molecule_.push_back( setup.Top()[o_idx + IDX ].MolNum() );
this->charges_.push_back( setup.Top()[o_idx + IDX ].Charge() );
this->atomTypes_.push_back( setup.Top()[o_idx + IDX ].TypeIndex() );
this->solvent_[ o_idx + IDX ] = true;
#endif
}
NsolventAtoms += nMolAtoms_;
// If first solvent molecule, save charges. If not, check that charges match.
if (isFirstSolvent) {
double q_sum = 0.0;
Q_.reserve( nMolAtoms_ );
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
Q_.push_back( setup.Top()[o_idx+IDX].Charge() );
q_sum += Q_.back();
//mprintf("DEBUG: Q= %20.10E q_sum= %20.10E\n", setup.Top()[o_idx+IDX].Charge(), q_sum);
}
// Sanity checks.
// NOTE: We know indices 1 and 2 are hydrogens (with 0 being oxygen); this is checked above.
if (NotEqual(Q_[1], Q_[2]))
mprintf("Warning: Charges on water hydrogens do not match (%g, %g).\n", Q_[1], Q_[2]);
if (fabs( q_sum ) > 0.0)
mprintf("Warning: Charges on water do not sum to 0 (%g)\n", q_sum);
//mprintf("DEBUG: Water charges: O=%g H1=%g H2=%g\n", q_O_, q_H1_, q_H2_);
} else {
for (unsigned int IDX = 0; IDX < nMolAtoms_; IDX++) {
double q_atom = setup.Top()[o_idx+IDX].Charge();
if (NotEqual(Q_[IDX], q_atom)) {
mprintf("Warning: Charge on water '%s' (%g) does not match first water (%g).\n",
setup.Top().TruncResAtomName( o_idx+IDX ).c_str(), q_atom, Q_[IDX]);
}
}
}
isFirstSolvent = false;
} else {
// This is a non-solvent molecule. Save atom indices. May want to exclude
// if only 1 atom (probably ion).
if (mol->NumAtoms() > 1 || includeIons_) {
for (Unit::const_iterator seg = mol->MolUnit().segBegin();
seg != mol->MolUnit().segEnd(); ++seg)
{
for (int u_idx = seg->Begin(); u_idx != seg->End(); ++u_idx) {
A_idxs_.push_back( u_idx );
atomIsSolute_[A_idxs_.back()] = true; // the identity of the atom is solute
NsoluteAtoms++;
U_idxs_.push_back( u_idx ); // store the solute atom index for locating voxel index
#ifdef CUDA
this->molecule_.push_back( setup.Top()[ u_idx ].MolNum() );
this->charges_.push_back( setup.Top()[ u_idx ].Charge() );
this->atomTypes_.push_back( setup.Top()[ u_idx ].TypeIndex() );
this->solvent_[ u_idx ] = false;
#endif
}
}
}
}
}
NSOLVENT_ = O_idxs_.size();
mprintf("\t%zu solvent molecules, %u solvent atoms, %u solute atoms (%zu total).\n",
O_idxs_.size(), NsolventAtoms, NsoluteAtoms, A_idxs_.size());
if (doOrder_ && NSOLVENT_ < 5) {
mprintf("Warning: Less than 5 solvent molecules. Cannot perform order calculation.\n");
doOrder_ = false;
}
// Allocate space for saving indices of water atoms that are on the grid
// Estimate how many solvent molecules can possibly fit onto the grid.
// Add some extra voxels as a buffer.
double max_voxels = (double)MAX_GRID_PT_ + (1.10 * (double)MAX_GRID_PT_);
double totalVolume = max_voxels * gO_->Bin().VoxelVolume();
double max_mols = totalVolume * BULK_DENS_;
//mprintf("\tEstimating grid can fit a max of %.0f solvent molecules (w/ 10%% buffer).\n",
// max_mols);
OnGrid_idxs_.reserve( (size_t)max_mols * (size_t)nMolAtoms_ );
N_ON_GRID_ = 0;
if (!skipE_) {
if (imageOpt_.ImagingEnabled())
mprintf("\tImaging enabled for energy distance calculations.\n");
else
mprintf("\tNo imaging will be performed for energy distance calculations.\n");
}
#ifdef CUDA
NonbondParmType nb = setup.Top().Nonbond();
this->NBIndex_ = nb.NBindex();
this->numberAtomTypes_ = nb.Ntypes();
for (unsigned int i = 0; i < nb.NBarray().size(); ++i) {
this->lJParamsA_.push_back( (float) nb.NBarray().at(i).A() );
this->lJParamsB_.push_back( (float) nb.NBarray().at(i).B() );
}
try {
allocateCuda(((void**)&this->NBindex_c_), this->NBIndex_.size() * sizeof(int));
allocateCuda((void**)&this->max_c_, 3 * sizeof(float));
allocateCuda((void**)&this->min_c_, 3 * sizeof(float));
allocateCuda((void**)&this->result_w_c_, this->numberAtoms_ * sizeof(float));
allocateCuda((void**)&this->result_s_c_, this->numberAtoms_ * sizeof(float));
allocateCuda((void**)&this->result_O_c_, this->numberAtoms_ * 4 * sizeof(int));
allocateCuda((void**)&this->result_N_c_, this->numberAtoms_ * sizeof(int));
} catch (CudaException &e) {
mprinterr("Error: Could not allocate memory on GPU!\n");
this->freeGPUMemory();
return Action::ERR;
}
try {
this->copyToGPU();
} catch (CudaException &e) {
return Action::ERR;
}
#endif
gist_setup_.Stop();
return Action::OK;
}
const Vec3 Action_GIST::x_lab_ = Vec3(1.0, 0.0, 0.0);
const Vec3 Action_GIST::y_lab_ = Vec3(0.0, 1.0, 0.0);
const Vec3 Action_GIST::z_lab_ = Vec3(0.0, 0.0, 1.0);
const double Action_GIST::QFAC_ = Constants::ELECTOAMBER * Constants::ELECTOAMBER;
const int Action_GIST::OFF_GRID_ = -1;
/* Calculate the charge-charge, vdw interaction using pme, frame by frame
*
*/
void Action_GIST::NonbondEnergy_pme(Frame const& frameIn)
{
# ifdef LIBPME
// Two energy terms for the whole system
//double ene_pme_all = 0.0;
//double ene_vdw_all = 0.0;
// pointer to the E_pme_, where has the voxel-wise pme energy for water
double* E_pme_grid = &E_pme_[0];
// pointer to U_E_pme_, where has the voxel-wise pme energy for solute
double* U_E_pme_grid = &U_E_pme_[0];
gistPme_.CalcNonbondEnergy_GIST(frameIn, atom_voxel_, atomIsSolute_, atomIsSolventO_,
E_UV_VDW_, E_UV_Elec_, E_VV_VDW_, E_VV_Elec_,
neighbor_);
// system_potential_energy_ += ene_pme_all + ene_vdw_all;
// Water energy on the GIST grid
double pme_sum = 0.0;
for (unsigned int gidx=0; gidx < N_ON_GRID_; gidx++ )
{
int a = OnGrid_idxs_[gidx]; // index of the atom of on-grid solvent;
int a_voxel = atom_voxel_[a]; // index of the voxel
double nonbond_energy = gistPme_.E_of_atom(a);
pme_sum += nonbond_energy;
E_pme_grid[a_voxel] += nonbond_energy;
}
// Solute energy on the GIST grid
double solute_on_grid_sum = 0.0; // To sum up the potential energy on solute atoms that on the grid
for (unsigned int uidx=0; uidx < U_onGrid_idxs_.size(); uidx++ )
{
int u = U_onGrid_idxs_[uidx]; // index of the solute atom on the grid
int u_voxel = atom_voxel_[u];
double u_nonbond_energy = gistPme_.E_of_atom(u);
solute_on_grid_sum += u_nonbond_energy;
U_E_pme_grid[u_voxel] += u_nonbond_energy;
}
/*
// Total solute energy
double solute_sum = 0.0;
for (unsigned int uidx=0; uidx < U_idxs_.size(); uidx++)
{
int u = U_idxs_[uidx];
double u_nonbond_energy = gistPme_.E_of_atom(u);
solute_sum += u_nonbond_energy;
solute_potential_energy_ += u_nonbond_energy; // used to calculated the ensemble energy for all solute, will print out in terminal
}
*/
//mprintf("The total potential energy on water atoms: %f \n", pme_sum);
# else /*LIBPME */
mprinterr("Error: Compiled without LIBPME\n");
return;
# endif /*LIBPME */
}
/** Non-bonded energy calc. */
void Action_GIST::Ecalc(double rij2, double q1, double q2, NonbondType const& LJ,
double& Evdw, double& Eelec)
{
double rij = sqrt(rij2);
// VDW
double r2 = 1.0 / rij2;
double r6 = r2 * r2 * r2;
double r12 = r6 * r6;
double f12 = LJ.A() * r12; // A/r^12
double f6 = LJ.B() * r6; // B/r^6
Evdw = f12 - f6; // (A/r^12)-(B/r^6)
// Coulomb
double qiqj = QFAC_ * q1 * q2;
Eelec = qiqj / rij;
}
/** Calculate the energy between all solute/solvent atoms and solvent atoms
* on the grid. This is done after the intial GIST calculations
* so that all waters have voxels assigned in atom_voxel_.
* NOTE: This routine modifies the coordinates in OnGrid_XYZ_ when the cell
* has nonorthogonal shape in order to properly satsify the minimum
* image convention, so any calculations that rely on the on grid
* coordinates (like Order()) must be done *BEFORE* this routine.
*/
void Action_GIST::NonbondEnergy(Frame const& frameIn, Topology const& topIn)
{
// Set up imaging info.
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
// Wrap on-grid water coords back to primary cell TODO openmp
double* ongrid_xyz = &OnGrid_XYZ_[0];
int maxXYZ = (int)OnGrid_XYZ_.size();
int idx;
# ifdef _OPENMP
# pragma omp parallel private(idx)
{
# pragma omp for
# endif
for (idx = 0; idx < maxXYZ; idx += 3)
{
double* XYZ = ongrid_xyz + idx;
// Convert to frac coords
frameIn.BoxCrd().FracCell().TimesVec( XYZ, XYZ );
// Wrap to primary cell
XYZ[0] = XYZ[0] - floor(XYZ[0]);
XYZ[1] = XYZ[1] - floor(XYZ[1]);
XYZ[2] = XYZ[2] - floor(XYZ[2]);
// Convert back to Cartesian
frameIn.BoxCrd().UnitCell().TransposeMult( XYZ, XYZ );
}
# ifdef _OPENMP
}
# endif
}
// mprintf("DEBUG: NSolventAtoms= %zu NwatAtomsOnGrid= %u\n", O_idxs_.size()*nMolAtoms_, N_ON_GRID_);
double* E_UV_VDW = &(E_UV_VDW_[0][0]);
double* E_UV_Elec = &(E_UV_Elec_[0][0]);
double* E_VV_VDW = &(E_VV_VDW_[0][0]);
double* E_VV_Elec = &(E_VV_Elec_[0][0]);
float* Neighbor = &(neighbor_[0][0]);
double Evdw, Eelec;
int aidx;
int maxAidx = (int)A_idxs_.size();
// Loop over all solute + solvent atoms
# ifdef _OPENMP
int mythread;
Iarray* eij_v1 = 0;
Iarray* eij_v2 = 0;
Farray* eij_en = 0;
# pragma omp parallel private(aidx, mythread, E_UV_VDW, E_UV_Elec, E_VV_VDW, E_VV_Elec, Neighbor, Evdw, Eelec, eij_v1, eij_v2, eij_en)
{
mythread = omp_get_thread_num();
E_UV_VDW = &(E_UV_VDW_[mythread][0]);
E_UV_Elec = &(E_UV_Elec_[mythread][0]);
E_VV_VDW = &(E_VV_VDW_[mythread][0]);
E_VV_Elec = &(E_VV_Elec_[mythread][0]);
Neighbor = (&neighbor_[mythread][0]);
if (doEij_) {
eij_v1 = &(EIJ_V1_[mythread]);
eij_v2 = &(EIJ_V2_[mythread]);
eij_en = &(EIJ_EN_[mythread]);
eij_v1->clear();
eij_v2->clear();
eij_en->clear();
}
# pragma omp for
# endif
for (aidx = 0; aidx < maxAidx; aidx++)
{
int a1 = A_idxs_[aidx]; // Index of atom1
int a1_voxel = atom_voxel_[a1]; // Voxel of atom1
int a1_mol = topIn[ a1 ].MolNum(); // Molecule # of atom 1
Vec3 A1_XYZ( frameIn.XYZ( a1 ) ); // Coord of atom1
double qA1 = topIn[ a1 ].Charge(); // Charge of atom1
bool a1IsO = atomIsSolventO_[a1];
std::vector<Vec3> vImages;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
// Convert to frac coords
Vec3 vFrac = frameIn.BoxCrd().FracCell() * A1_XYZ;
// Wrap to primary unit cell
vFrac[0] = vFrac[0] - floor(vFrac[0]);
vFrac[1] = vFrac[1] - floor(vFrac[1]);
vFrac[2] = vFrac[2] - floor(vFrac[2]);
// Calculate all images of this atom
vImages.reserve(27);
for (int ix = -1; ix != 2; ix++)
for (int iy = -1; iy != 2; iy++)
for (int iz = -1; iz != 2; iz++)
// Convert image back to Cartesian
vImages.push_back( frameIn.BoxCrd().UnitCell().TransposeMult( vFrac + Vec3(ix,iy,iz) ) );
}
// Loop over all solvent atoms on the grid
for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx++)
{
int a2 = OnGrid_idxs_[gidx]; // Index of on-grid solvent
int a2_mol = topIn[ a2 ].MolNum(); // Molecule # of on-grid solvent
if (a1_mol != a2_mol)
{
int a2_voxel = atom_voxel_[a2]; // Voxel of on-grid solvent
const double* A2_XYZ = (&OnGrid_XYZ_[0])+gidx*3; // Coord of on-grid solvent
if (atomIsSolute_[a1]) {
// Solute to on-grid solvent energy
// Calculate distance
//gist_nonbond_dist_.Start();
double rij2;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
# ifdef GIST_USE_NONORTHO_DIST2
rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell());
# else
rij2 = maxD_;
for (std::vector<Vec3>::const_iterator vCart = vImages.begin();
vCart != vImages.end(); ++vCart)
{
double x = (*vCart)[0] - A2_XYZ[0];
double y = (*vCart)[1] - A2_XYZ[1];
double z = (*vCart)[2] - A2_XYZ[2];
rij2 = std::min(rij2, x*x + y*y + z*z);
}
# endif
} else if (imageOpt_.ImagingType() == ImageOption::ORTHO)
rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() );
else
rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ );
//gist_nonbond_dist_.Stop();
//gist_nonbond_UV_.Start();
// Calculate energy
Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec );
E_UV_VDW[a2_voxel] += Evdw;
E_UV_Elec[a2_voxel] += Eelec;
//gist_nonbond_UV_.Stop();
} else {
// Off-grid/on-grid solvent to on-grid solvent energy
// Only do the energy calculation if not previously done or atom1 not on grid
if (a2 != a1 && (a2 > a1 || a1_voxel == OFF_GRID_))
{
// Calculate distance
//gist_nonbond_dist_.Start();
double rij2;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
# ifdef GIST_USE_NONORTHO_DIST2
rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell());
# else
rij2 = maxD_;
for (std::vector<Vec3>::const_iterator vCart = vImages.begin();
vCart != vImages.end(); ++vCart)
{
double x = (*vCart)[0] - A2_XYZ[0];
double y = (*vCart)[1] - A2_XYZ[1];
double z = (*vCart)[2] - A2_XYZ[2];
rij2 = std::min(rij2, x*x + y*y + z*z);
}
# endif
} else if (imageOpt_.ImagingType() == ImageOption::ORTHO)
rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() );
else
rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ );
//gist_nonbond_dist_.Stop();
//gist_nonbond_VV_.Start();
// Calculate energy
Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec );
//mprintf("DEBUG1: v1= %i v2= %i EVV %i %i Vdw= %f Elec= %f\n", a2_voxel, a1_voxel, a2, a1, Evdw, Eelec);
E_VV_VDW[a2_voxel] += Evdw;
E_VV_Elec[a2_voxel] += Eelec;
// Store water neighbor using only O-O distance
bool is_O_O = (a1IsO && atomIsSolventO_[a2]);
if (is_O_O && rij2 < NeighborCut2_)
Neighbor[a2_voxel] += 1.0;
// If water atom1 was also on the grid update its energy as well.
if ( a1_voxel != OFF_GRID_ ) {
E_VV_VDW[a1_voxel] += Evdw;
E_VV_Elec[a1_voxel] += Eelec;
if (is_O_O && rij2 < NeighborCut2_)
Neighbor[a1_voxel] += 1.0;
if (doEij_) {
if (a1_voxel != a2_voxel) {
# ifdef _OPENMP
eij_v1->push_back( a1_voxel );
eij_v2->push_back( a2_voxel );
eij_en->push_back( Evdw + Eelec );
# else
ww_Eij_->UpdateElement(a1_voxel, a2_voxel, Evdw + Eelec);
# endif
}
}
}
//gist_nonbond_VV_.Stop();
}
}
} // END a1 and a2 not in same molecule
} // End loop over all solvent atoms on grid
} // End loop over all solvent + solute atoms
# ifdef _OPENMP
} // END pragma omp parallel
if (doEij_) {
// Add any Eijs to matrix
for (unsigned int thread = 0; thread != EIJ_V1_.size(); thread++)
for (unsigned int idx = 0; idx != EIJ_V1_[thread].size(); idx++)
ww_Eij_->UpdateElement(EIJ_V1_[thread][idx], EIJ_V2_[thread][idx], EIJ_EN_[thread][idx]);
}
# endif
}
/** GIST order calculation. */
void Action_GIST::Order(Frame const& frameIn) {
// Loop over all solvent molecules that are on the grid
for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx += nMolAtoms_)
{
int oidx1 = OnGrid_idxs_[gidx];
int voxel1 = atom_voxel_[oidx1];
Vec3 XYZ1( (&OnGrid_XYZ_[0])+gidx*3 );
// Find coordinates for 4 closest neighbors to this water (on or off grid).
// TODO set up overall grid in DoAction.
// TODO initialize WAT?
Vec3 WAT[4];
double d1 = maxD_;
double d2 = maxD_;
double d3 = maxD_;
double d4 = maxD_;
for (unsigned int sidx2 = 0; sidx2 < NSOLVENT_; sidx2++)
{
int oidx2 = O_idxs_[sidx2];
if (oidx2 != oidx1)
{
const double* XYZ2 = frameIn.XYZ( oidx2 );
double dist2 = DIST2_NoImage( XYZ1.Dptr(), XYZ2 );
if (dist2 < d1) {
d4 = d3; d3 = d2; d2 = d1; d1 = dist2;
WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = WAT[0]; WAT[0] = XYZ2;
} else if (dist2 < d2) {
d4 = d3; d3 = d2; d2 = dist2;
WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = XYZ2;
} else if (dist2 < d3) {
d4 = d3; d3 = dist2;
WAT[3] = WAT[2]; WAT[2] = XYZ2;
} else if (dist2 < d4) {
d4 = dist2;
WAT[3] = XYZ2;
}
}
}
// Compute the tetrahedral order parameter
double sum = 0.0;
for (int mol1 = 0; mol1 < 3; mol1++) {
for (int mol2 = mol1 + 1; mol2 < 4; mol2++) {
Vec3 v1 = WAT[mol1] - XYZ1;
Vec3 v2 = WAT[mol2] - XYZ1;
double r1 = v1.Magnitude2();
double r2 = v2.Magnitude2();
double cos = (v1* v2) / sqrt(r1 * r2);
sum += (cos + 1.0/3)*(cos + 1.0/3);
}
}
order_norm_->UpdateVoxel(voxel1, (1.0 - (3.0/8)*sum));
//mprintf("DBG: gidx= %u oidx1=%i voxel1= %i XYZ1={%g, %g, %g} sum= %g\n", gidx, oidx1, voxel1, XYZ1[0], XYZ1[1], XYZ1[2], sum);
} // END loop over all solvent molecules
}
/** GIST action */
Action::RetType Action_GIST::DoAction(int frameNum, ActionFrame& frm) {
gist_action_.Start();
NFRAME_++;
// TODO only !skipE?
N_ON_GRID_ = 0;
OnGrid_idxs_.clear();
OnGrid_XYZ_.clear();
// Determine imaging type
# ifdef DEBUG_GIST
//mprintf("DEBUG: Is_X_Aligned_Ortho() = %i Is_X_Aligned() = %i\n", (int)frm.Frm().BoxCrd().Is_X_Aligned_Ortho(), (int)frm.Frm().BoxCrd().Is_X_Aligned());
frm.Frm().BoxCrd().UnitCell().Print("Ucell");
frm.Frm().BoxCrd().FracCell().Print("Frac");
# endif
if (imageOpt_.ImagingEnabled())
imageOpt_.SetImageType( frm.Frm().BoxCrd().Is_X_Aligned_Ortho() );
# ifdef DEBUG_GIST
switch (imageOpt_.ImagingType()) {
case ImageOption::NO_IMAGE : mprintf("DEBUG: No Image.\n"); break;
case ImageOption::ORTHO : mprintf("DEBUG: Orthogonal image.\n"); break;
case ImageOption::NONORTHO : mprintf("DEBUG: Nonorthogonal image.\n"); break;
}
# endif
// CUDA necessary information
size_t bin_i, bin_j, bin_k;
Vec3 const& Origin = gO_->Bin().GridOrigin();
// Loop over each solvent molecule
for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++)
{
gist_grid_.Start();
int oidx = O_idxs_[sidx];
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++)
atom_voxel_[oidx+IDX] = OFF_GRID_;
const double* O_XYZ = frm.Frm().XYZ( oidx );
// Get vector of water oxygen to grid origin.
Vec3 W_G( O_XYZ[0] - Origin[0],
O_XYZ[1] - Origin[1],
O_XYZ[2] - Origin[2] );
gist_grid_.Stop();
// Check if water oxygen is no more then 1.5 Ang from grid
// NOTE: using <= to be consistent with original code
if ( W_G[0] <= G_max_[0] && W_G[0] >= -1.5 &&
W_G[1] <= G_max_[1] && W_G[1] >= -1.5 &&
W_G[2] <= G_max_[2] && W_G[2] >= -1.5 )
{
const double* H1_XYZ = frm.Frm().XYZ( oidx + 1 );
const double* H2_XYZ = frm.Frm().XYZ( oidx + 2 );
// Try to bin the oxygen
if ( gO_->Bin().Calc( O_XYZ[0], O_XYZ[1], O_XYZ[2], bin_i, bin_j, bin_k ) )
{
// Oxygen is inside the grid. Record the voxel.
// NOTE hydrogens/EP always assigned to same voxel for energy purposes.
int voxel = (int)gO_->CalcIndex(bin_i, bin_j, bin_k);
const double* wXYZ = O_XYZ;
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
atom_voxel_[oidx+IDX] = voxel;
//OnGrid_idxs_[N_ON_GRID_+IDX] = oidx + IDX;
OnGrid_idxs_.push_back( oidx+IDX );
OnGrid_XYZ_.push_back( wXYZ[0] );
OnGrid_XYZ_.push_back( wXYZ[1] );
OnGrid_XYZ_.push_back( wXYZ[2] );
wXYZ+=3;
}
N_ON_GRID_ += nMolAtoms_;
//mprintf("DEBUG1: Water atom %i voxel %i\n", oidx, voxel);
N_waters_[voxel]++;
max_nwat_ = std::max( N_waters_[voxel], max_nwat_ );
// ----- EULER ---------------------------
gist_euler_.Start();
// Record XYZ coords of water atoms (nonEP) in voxel TODO need EP?
voxel_xyz_[voxel].push_back( O_XYZ[0] );
voxel_xyz_[voxel].push_back( O_XYZ[1] );
voxel_xyz_[voxel].push_back( O_XYZ[2] );
// Get O-HX vectors
Vec3 H1_wat( H1_XYZ[0]-O_XYZ[0], H1_XYZ[1]-O_XYZ[1], H1_XYZ[2]-O_XYZ[2] );
Vec3 H2_wat( H2_XYZ[0]-O_XYZ[0], H2_XYZ[1]-O_XYZ[1], H2_XYZ[2]-O_XYZ[2] );
H1_wat.Normalize();
H2_wat.Normalize();
Vec3 ar1 = H1_wat.Cross( x_lab_ ); // ar1 = V cross U
Vec3 sar = ar1; // sar = V cross U
ar1.Normalize();
//mprintf("------------------------------------------\n");
//H1_wat.Print("DEBUG: H1_wat");
//x_lab_.Print("DEBUG: x_lab_");
//ar1.Print("DEBUG: ar1");
//sar.Print("DEBUG: sar");
double dp1 = x_lab_ * H1_wat; // V dot U
double theta = acos(dp1);
double sign = sar * H1_wat;
//mprintf("DEBUG0: dp1= %f theta= %f sign= %f\n", dp1, theta, sign);
// NOTE: Use SMALL instead of 0 to avoid issues with denormalization
if (sign > Constants::SMALL)
theta /= 2.0;
else
theta /= -2.0;
double w1 = cos(theta);
double sin_theta = sin(theta);
//mprintf("DEBUG0: theta= %f w1= %f sin_theta= %f\n", theta, w1, sin_theta);
double x1 = ar1[0] * sin_theta;
double y1 = ar1[1] * sin_theta;
double z1 = ar1[2] * sin_theta;
double w2 = w1;
double x2 = x1;
double y2 = y1;
double z2 = z1;
Vec3 H_temp;
H_temp[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H1_wat[0];
H_temp[0] = (2*(x2*y2 + w2*z2)*H1_wat[1]) + H_temp[0];
H_temp[0] = (2*(x2*z2-w2*y2)*H1_wat[2]) + H_temp[0];
H_temp[1] = 2*(x2*y2 - w2*z2)* H1_wat[0];
H_temp[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H1_wat[1]) + H_temp[1];
H_temp[1] = (2*(y2*z2+w2*x2)*H1_wat[2]) +H_temp[1];
H_temp[2] = 2*(x2*z2+w2*y2) *H1_wat[0];
H_temp[2] = (2*(y2*z2-w2*x2)*H1_wat[1]) + H_temp[2];
H_temp[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H1_wat[2]) + H_temp[2];
H1_wat = H_temp;
Vec3 H_temp2;
H_temp2[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H2_wat[0];
H_temp2[0] = (2*(x2*y2 + w2*z2)*H2_wat[1]) + H_temp2[0];
H_temp2[0] = (2*(x2*z2-w2*y2)*H2_wat[2]) +H_temp2[0];
H_temp2[1] = 2*(x2*y2 - w2*z2) *H2_wat[0];
H_temp2[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H2_wat[1]) +H_temp2[1];
H_temp2[1] = (2*(y2*z2+w2*x2)*H2_wat[2]) +H_temp2[1];
H_temp2[2] = 2*(x2*z2+w2*y2)*H2_wat[0];
H_temp2[2] = (2*(y2*z2-w2*x2)*H2_wat[1]) +H_temp2[2];
H_temp2[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H2_wat[2]) + H_temp2[2];
H2_wat = H_temp2;
Vec3 ar2 = H_temp.Cross(H_temp2);
ar2.Normalize();
double dp2 = ar2 * z_lab_;
theta = acos(dp2);
sar = ar2.Cross( z_lab_ );
sign = sar * H_temp;
if (sign < 0)
theta /= 2.0;
else
theta /= -2.0;
double w3 = cos(theta);
sin_theta = sin(theta);
double x3 = x_lab_[0] * sin_theta;
double y3 = x_lab_[1] * sin_theta;
double z3 = x_lab_[2] * sin_theta;
double w4 = w1*w3 - x1*x3 - y1*y3 - z1*z3;
double x4 = w1*x3 + x1*w3 + y1*z3 - z1*y3;
double y4 = w1*y3 - x1*z3 + y1*w3 + z1*x3;
double z4 = w1*z3 + x1*y3 - y1*x3 + z1*w3;
voxel_Q_[voxel].push_back( w4 );
voxel_Q_[voxel].push_back( x4 );
voxel_Q_[voxel].push_back( y4 );
voxel_Q_[voxel].push_back( z4 );
//mprintf("DEBUG1: sidx= %u voxel= %i wxyz4= %g %g %g %g\n", sidx, voxel, w4, x4, y4, z4);
//mprintf("DEBUG2: wxyz3= %g %g %g %g wxyz2= %g %g %g %g wxyz1= %g %g %g\n",
// w3, x3, y3, z3,
// w2, x2, y2, z2,
// w1, x1, y1, z1);
// NOTE: No need for nw_angle_ here, it is same as N_waters_
gist_euler_.Stop();
// ----- DIPOLE --------------------------
gist_dipole_.Start();
//mprintf("DEBUG1: voxel %i dipole %f %f %f\n", voxel,
// O_XYZ[0]*q_O_ + H1_XYZ[0]*q_H1_ + H2_XYZ[0]*q_H2_,
// O_XYZ[1]*q_O_ + H1_XYZ[1]*q_H1_ + H2_XYZ[1]*q_H2_,
// O_XYZ[2]*q_O_ + H1_XYZ[2]*q_H1_ + H2_XYZ[2]*q_H2_);
double DPX = 0.0;
double DPY = 0.0;
double DPZ = 0.0;
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
const double* XYZ = frm.Frm().XYZ( oidx+IDX );
DPX += XYZ[0] * Q_[IDX];
DPY += XYZ[1] * Q_[IDX];
DPZ += XYZ[2] * Q_[IDX];
}
dipolex_->UpdateVoxel(voxel, DPX);
dipoley_->UpdateVoxel(voxel, DPY);
dipolez_->UpdateVoxel(voxel, DPZ);
gist_dipole_.Stop();
// ---------------------------------------
}
// Water is at most 1.5A away from grid, so we need to check for H
// even if O is outside grid.
if (gO_->Bin().Calc( H1_XYZ[0], H1_XYZ[1], H1_XYZ[2], bin_i, bin_j, bin_k ) )
N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++;
if (gO_->Bin().Calc( H2_XYZ[0], H2_XYZ[1], H2_XYZ[2], bin_i, bin_j, bin_k ) )
N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++;
} // END water is within 1.5 Ang of grid
} // END loop over each solvent molecule
// Do solute grid assignment for PME
if (usePme_) {
U_onGrid_idxs_.clear();
gist_grid_.Start();
for (unsigned int s = 0; s != U_idxs_.size(); s++)
{
int uidx = U_idxs_[s]; // the solute atom index
atom_voxel_[uidx] = OFF_GRID_;
const double* u_XYZ = frm.Frm().XYZ( uidx );
// get the vector of this solute atom to the grid origin
Vec3 U_G( u_XYZ[0] - Origin[0],
u_XYZ[1] - Origin[1],
u_XYZ[2] - Origin[2]);
//size_t bin_i, bin_j, bin_k;
if ( U_G[0] <= G_max_[0] && U_G[0] >= -1.5 &&
U_G[1] <= G_max_[1] && U_G[1] >= -1.5 &&
U_G[2] <= G_max_[2] && U_G[2] >- -1.5)
{
if ( gO_->Bin().Calc(u_XYZ[0],u_XYZ[1],u_XYZ[2],bin_i,bin_j,bin_k)) // used the gO class function to calcaute voxel index
{
int voxel = (int)gO_->CalcIndex(bin_i,bin_j,bin_k);
atom_voxel_[uidx] = voxel; // asign the voxel index to the solute atom
//U_ON_GRID_ +=1; // add +1 to the number of atom on the GIST Grid
N_solute_atoms_[voxel] +=1; // add +1 to the solute atom num in this voxel
U_onGrid_idxs_.push_back(uidx); // The index of the solute atom on GIST Grid
}
}
}
gist_grid_.Stop();
}
# ifndef CUDA
// Do order calculation if requested.
// Do not do this for CUDA since CUDA nonbond routine handles the order calc.
// NOTE: This has to be done before the nonbond energy calc since
// the nonbond calc can modify the on-grid coordinates (for minimum
// image convention when cell is non-orthogonal).
gist_order_.Start();
if (doOrder_) Order(frm.Frm());
gist_order_.Stop();
# endif
// Do nonbond energy calc if not skipping energy
gist_nonbond_.Start();
if (!skipE_) {
if (usePme_) {
// PME
NonbondEnergy_pme( frm.Frm() );
} else {
// Non-PME
# ifdef CUDA
NonbondCuda(frm);
# else
NonbondEnergy(frm.Frm(), *CurrentParm_);
# endif
}
}
gist_nonbond_.Stop();
gist_action_.Stop();
return Action::OK;
}
/** Translational entropy calc between given water and all waters in voxel 2.
* \param VX voxel 1 water X
* \param VY voxel 1 water Y
* \param VZ voxel 1 water Z
* \param W4 voxel 1 water W4
* \param X4 voxel 1 water X4
* \param Y4 voxel 1 water Y4
* \param Z4 voxel 1 water Z4
* \param voxel2 Index of second voxel
*/
void Action_GIST::TransEntropy(float VX, float VY, float VZ,
float W4, float X4, float Y4, float Z4,
int voxel2, double& NNd, double& NNs) const
{
int nw_tot = N_waters_[voxel2];
Farray const& V_XYZ = voxel_xyz_[voxel2];
Farray const& V_Q = voxel_Q_[voxel2];
for (int n1 = 0; n1 != nw_tot; n1++)
{
int i1 = n1 * 3; // index into V_XYZ for n1
double dx = (double)(VX - V_XYZ[i1 ]);
double dy = (double)(VY - V_XYZ[i1+1]);
double dz = (double)(VZ - V_XYZ[i1+2]);
double dd = dx*dx+dy*dy+dz*dz;
if (dd < NNd && dd > 0) { NNd = dd; }
int q1 = n1 * 4; // index into V_Q for n1
double rR = 2.0 * acos( fabs(W4 * V_Q[q1 ] +
X4 * V_Q[q1+1] +
Y4 * V_Q[q1+2] +
Z4 * V_Q[q1+3] )); //add fabs for quaternions distance calculation
double ds = rR*rR + dd;
if (ds < NNs && ds > 0) { NNs = ds; }
}
}
// Action_GIST::SumEVV()
void Action_GIST::SumEVV() {
if (E_VV_VDW_.size() > 1) {
for (unsigned int gr_pt = 0; gr_pt != MAX_GRID_PT_; gr_pt++) {
for (unsigned int thread = 1; thread < E_VV_VDW_.size(); thread++) {
E_UV_VDW_[0][gr_pt] += E_UV_VDW_[thread][gr_pt];
E_UV_Elec_[0][gr_pt] += E_UV_Elec_[thread][gr_pt];
E_VV_VDW_[0][gr_pt] += E_VV_VDW_[thread][gr_pt];
E_VV_Elec_[0][gr_pt] += E_VV_Elec_[thread][gr_pt];
neighbor_[0][gr_pt] += neighbor_[thread][gr_pt];
}
}
}
}
/** Calculate average voxel energy for PME grids. */
void Action_GIST::CalcAvgVoxelEnergy_PME(double Vvox, DataSet_GridFlt& PME_dens, DataSet_GridFlt& U_PME_dens, Farray& PME_norm)
const
{
double PME_tot =0.0;
double U_PME_tot = 0.0;
mprintf("\t Calculating average voxel energies: \n");
ProgressBar E_progress(MAX_GRID_PT_);
for ( unsigned int gr_pt =0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
E_progress.Update(gr_pt);
int nw_total = N_waters_[gr_pt];
if (nw_total >=1)
{
PME_dens[gr_pt] = E_pme_[gr_pt] / (NFRAME_ * Vvox);
PME_norm[gr_pt] = E_pme_[gr_pt] / nw_total;
PME_tot += PME_dens[gr_pt];
}else{
PME_dens[gr_pt]=0;
PME_norm[gr_pt]=0;
}
int ns_total = N_solute_atoms_[gr_pt];
if (ns_total >=1)
{
U_PME_dens[gr_pt] = U_E_pme_[gr_pt] / (NFRAME_ * Vvox);
U_PME_tot += U_PME_dens[gr_pt];
}else{
U_PME_dens[gr_pt]=0;
}
}
PME_tot *=Vvox;
U_PME_tot *=Vvox;
infofile_->Printf("Ensemble total water energy on the grid: %9.5f Kcal/mol \n", PME_tot);
infofile_->Printf("Ensemble total solute energy on the grid: %9.5f Kcal/mol \n",U_PME_tot);
// infofile_->Printf("Ensemble solute's total potential energy : %9.5f Kcal/mol \n", solute_potential_energy_ / NFRAME_);
// infofile_->Printf("Ensemble system's total potential energy: %9.5f Kcal/mol \n", system_potential_energy_/NFRAME_);
}
/** Calculate average voxel energy for GIST grids. */
void Action_GIST::CalcAvgVoxelEnergy(double Vvox, DataSet_GridFlt& Eww_dens, DataSet_GridFlt& Esw_dens,
Farray& Eww_norm, Farray& Esw_norm,
DataSet_GridDbl& qtet,
DataSet_GridFlt& neighbor_norm, Farray& neighbor_dens)
{
#ifndef CUDA
Darray const& E_UV_VDW = E_UV_VDW_[0];
Darray const& E_UV_Elec = E_UV_Elec_[0];
Darray const& E_VV_VDW = E_VV_VDW_[0];
Darray const& E_VV_Elec = E_VV_Elec_[0];
#endif
Farray const& Neighbor = neighbor_[0];
#ifndef CUDA
// Sum values from other threads if necessary
SumEVV();
#endif
double Eswtot = 0.0;
double Ewwtot = 0.0;
mprintf("\tCalculating average voxel energies:\n");
ProgressBar E_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
E_progress.Update( gr_pt );
//mprintf("DEBUG1: VV vdw=%f elec=%f\n", E_VV_VDW_[gr_pt], E_VV_Elec_[gr_pt]);
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
if (nw_total > 0) {
#ifndef CUDA
Esw_dens[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / (NFRAME_ * Vvox);
Esw_norm[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / nw_total;
Eww_dens[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * NFRAME_ * Vvox);
Eww_norm[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * nw_total);
#else
double esw = this->Esw_->operator[](gr_pt);
double eww = this->Eww_->operator[](gr_pt);
Esw_dens[gr_pt] = esw / (this->NFRAME_ * Vvox);
Esw_norm[gr_pt] = esw / nw_total;
Eww_dens[gr_pt] = eww / (this->NFRAME_ * Vvox);
Eww_norm[gr_pt] = eww / nw_total;
#endif
Eswtot += Esw_dens[gr_pt];
Ewwtot += Eww_dens[gr_pt];
} else {
Esw_dens[gr_pt]=0;
Esw_norm[gr_pt]=0;
Eww_norm[gr_pt]=0;
Eww_dens[gr_pt]=0;
}
// Compute the average number of water neighbor and average order parameter.
if (nw_total > 0) {
qtet[gr_pt] /= nw_total;
//mprintf("DEBUG1: neighbor= %8.1f nw_total= %8i\n", neighbor[gr_pt], nw_total);
neighbor_norm[gr_pt] = (double)Neighbor[gr_pt] / nw_total;
}
neighbor_dens[gr_pt] = (double)Neighbor[gr_pt] / (NFRAME_ * Vvox);
} // END loop over all grid points (voxels)
Eswtot *= Vvox;
Ewwtot *= Vvox;
infofile_->Printf("Total water-solute energy of the grid: Esw = %9.5f kcal/mol\n", Eswtot);
infofile_->Printf("Total unreferenced water-water energy of the grid: Eww = %9.5f kcal/mol\n",
Ewwtot);
}
/** Handle averaging for grids and output from GIST. */
void Action_GIST::Print() {
gist_print_.Start();
double Vvox = gO_->Bin().VoxelVolume();
mprintf(" GIST OUTPUT:\n");
// The variables are kept outside, so that they are declared for later use.
// Calculate orientational entropy
DataSet_GridFlt& dTSorient_dens = static_cast<DataSet_GridFlt&>( *dTSorient_ );
Farray dTSorient_norm( MAX_GRID_PT_, 0.0 );
double dTSorienttot = 0;
int nwtt = 0;
double dTSo = 0;
if (! this->skipS_) {
// LOOP over all voxels
mprintf("\tCalculating orientational entropy:\n");
ProgressBar oe_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
oe_progress.Update( gr_pt );
dTSorient_dens[gr_pt] = 0;
dTSorient_norm[gr_pt] = 0;
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
nwtt += nw_total;
//mprintf("DEBUG1: %u nw_total %i\n", gr_pt, nw_total);
if (nw_total > 1) {
for (int n0 = 0; n0 < nw_total; n0++)
{
double NNr = 10000;
int q0 = n0 * 4; // Index into voxel_Q_ for n0
for (int n1 = 0; n1 < nw_total; n1++)
{
if (n0 != n1) {
int q1 = n1 * 4; // Index into voxel_Q_ for n1
//mprintf("DEBUG1:\t\t q1= %8i {%12.4f %12.4f %12.4f %12.4f} q0= %8i {%12.4f %12.4f %12.4f %12.4f}\n",
// q1, voxel_Q_[gr_pt][q1 ], voxel_Q_[gr_pt][q1+1], voxel_Q_[gr_pt][q1+2], voxel_Q_[gr_pt][q1+3],
// q0, voxel_Q_[gr_pt][q0 ], voxel_Q_[gr_pt][q0+1], voxel_Q_[gr_pt][q0+2], voxel_Q_[gr_pt][q0+3]);
double rR = 2.0 * acos( fabs(voxel_Q_[gr_pt][q1 ] * voxel_Q_[gr_pt][q0 ]
+ voxel_Q_[gr_pt][q1+1] * voxel_Q_[gr_pt][q0+1]
+ voxel_Q_[gr_pt][q1+2] * voxel_Q_[gr_pt][q0+2]
+ voxel_Q_[gr_pt][q1+3] * voxel_Q_[gr_pt][q0+3] )); // add fabs for quaternion distance calculation
//mprintf("DEBUG1:\t\t %8i %8i %g\n", n0, n1, rR);
if (rR > 0 && rR < NNr) NNr = rR;
}
} // END inner loop over all waters for this voxel
if (NNr < 9999 && NNr > 0) {
double dbl = log(NNr*NNr*NNr*nw_total / (3.0*Constants::TWOPI));
//mprintf("DEBUG1: %u nw_total= %i NNr= %f dbl= %f\n", gr_pt, nw_total, NNr, dbl);
dTSorient_norm[gr_pt] += dbl;
dTSo += dbl;
}
} // END outer loop over all waters for this voxel
//mprintf("DEBUG1: dTSorient_norm %f\n", dTSorient_norm[gr_pt]);
dTSorient_norm[gr_pt] = Constants::GASK_KCAL * temperature_ *
((dTSorient_norm[gr_pt]/nw_total) + Constants::EULER_MASC);
double dtso_norm_nw = (double)dTSorient_norm[gr_pt] * (double)nw_total;
dTSorient_dens[gr_pt] = (dtso_norm_nw / (NFRAME_ * Vvox));
dTSorienttot += dTSorient_dens[gr_pt];
//mprintf("DEBUG1: %f\n", dTSorienttot);
}
} // END loop over all grid points (voxels)
dTSorienttot *= Vvox;
infofile_->Printf("Maximum number of waters found in one voxel for %d frames = %d\n",
NFRAME_, max_nwat_);
infofile_->Printf("Total referenced orientational entropy of the grid:"
" dTSorient = %9.5f kcal/mol, Nf=%d\n", dTSorienttot, NFRAME_);
}
// Compute translational entropy for each voxel
double dTStranstot = 0.0;
double dTSt = 0.0;
double dTSs = 0.0;
int nwts = 0;
unsigned int nx = gO_->NX();
unsigned int ny = gO_->NY();
unsigned int nz = gO_->NZ();
unsigned int addx = ny * nz;
unsigned int addy = nz;
unsigned int addz = 1;
DataSet_GridFlt& gO = static_cast<DataSet_GridFlt&>( *gO_ );
DataSet_GridFlt& gH = static_cast<DataSet_GridFlt&>( *gH_ );
DataSet_GridFlt& dTStrans = static_cast<DataSet_GridFlt&>( *dTStrans_ );
DataSet_GridFlt& dTSsix = static_cast<DataSet_GridFlt&>( *dTSsix_ );
Farray dTStrans_norm( MAX_GRID_PT_, 0.0 );
Farray dTSsix_norm( MAX_GRID_PT_, 0.0 );
// Loop over all grid points
if (! this->skipS_)
mprintf("\tCalculating translational entropy:\n");
else
mprintf("Calculating Densities:\n");
ProgressBar te_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
te_progress.Update( gr_pt );
int numplane = gr_pt / addx;
double W_dens = 1.0 * N_waters_[gr_pt] / (NFRAME_*Vvox);
gO[gr_pt] = W_dens / BULK_DENS_;
gH[gr_pt] = 1.0 * N_hydrogens_[gr_pt] / (NFRAME_*Vvox*2*BULK_DENS_);
if (! this->skipS_) {
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
for (int n0 = 0; n0 < nw_total; n0++)
{
double NNd = 10000;
double NNs = 10000;
int i0 = n0 * 3; // index into voxel_xyz_ for n0
float VX = voxel_xyz_[gr_pt][i0 ];
float VY = voxel_xyz_[gr_pt][i0+1];
float VZ = voxel_xyz_[gr_pt][i0+2];
int q0 = n0 * 4; // index into voxel_Q_ for n0
float W4 = voxel_Q_[gr_pt][q0 ];
float X4 = voxel_Q_[gr_pt][q0+1];
float Y4 = voxel_Q_[gr_pt][q0+2];
float Z4 = voxel_Q_[gr_pt][q0+3];
// First do own voxel
for (int n1 = 0; n1 < nw_total; n1++) {
if ( n1 != n0) {
int i1 = n1 * 3; // index into voxel_xyz_ for n1
double dx = (double)(VX - voxel_xyz_[gr_pt][i1 ]);
double dy = (double)(VY - voxel_xyz_[gr_pt][i1+1]);
double dz = (double)(VZ - voxel_xyz_[gr_pt][i1+2]);
double dd = dx*dx+dy*dy+dz*dz;
if (dd < NNd && dd > 0) { NNd = dd; }
int q1 = n1 * 4; // index into voxel_Q_ for n1
double rR = 2 * acos( fabs(W4*voxel_Q_[gr_pt][q1 ] +
X4*voxel_Q_[gr_pt][q1+1] +
Y4*voxel_Q_[gr_pt][q1+2] +
Z4*voxel_Q_[gr_pt][q1+3] )); //add fabs for quaternion distance calculation
double ds = rR*rR + dd;
if (ds < NNs && ds > 0) { NNs = ds; }
}
} // END self loop over all waters for this voxel
//mprintf("DEBUG1: self NNd=%f NNs=%f\n", NNd, NNs);
// Determine which directions are possible.
bool cannotAddZ = (nz == 0 || ( gr_pt%nz == nz-1 ));
bool cannotAddY = ((nz == 0 || ny-1 == 0) || ( gr_pt%(nz*(ny-1)+(numplane*addx)) < nz));
bool cannotAddX = (gr_pt >= addx * (nx-1) && gr_pt < addx * nx );
bool cannotSubZ = (nz == 0 || gr_pt%nz == 0);
bool cannotSubY = ((nz == 0 || ny == 0) || (gr_pt%addx < nz));
bool cannotSubX = ((nz == 0 || ny == 0) || (gr_pt < addx));
bool boundary = ( cannotAddZ || cannotAddY || cannotAddX ||
cannotSubZ || cannotSubY || cannotSubX );
if (!boundary) {
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy - addx, NNd, NNs);
// add the 8 more voxels for NNr searching
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy - addz, NNd, NNs);
NNd = sqrt(NNd);
NNs = sqrt(NNs);
if (NNd < 3 && NNd > 0/*NNd < 9999 && NNd > 0*/) {
double dbl = log((NNd*NNd*NNd*NFRAME_*4*Constants::PI*BULK_DENS_)/3);
dTStrans_norm[gr_pt] += dbl;
dTSt += dbl;
dbl = log((NNs*NNs*NNs*NNs*NNs*NNs*NFRAME_*Constants::PI*BULK_DENS_)/48);
dTSsix_norm[gr_pt] += dbl;
dTSs += dbl;
//mprintf("DEBUG1: dbl=%f NNs=%f\n", dbl, NNs);
}
}
} // END loop over all waters for this voxel
if (dTStrans_norm[gr_pt] != 0) {
nwts += nw_total;
dTStrans_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTStrans_norm[gr_pt]/nw_total) +
Constants::EULER_MASC );
dTSsix_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTSsix_norm[gr_pt]/nw_total) +
Constants::EULER_MASC );
}
double dtst_norm_nw = (double)dTStrans_norm[gr_pt] * (double)nw_total;
dTStrans[gr_pt] = (dtst_norm_nw / (NFRAME_*Vvox));
double dtss_norm_nw = (double)dTSsix_norm[gr_pt] * (double)nw_total;
dTSsix[gr_pt] = (dtss_norm_nw / (NFRAME_*Vvox));
dTStranstot += dTStrans[gr_pt];
} // END loop over all grid points (voxels)
}
if (!this->skipS_) {
dTStranstot *= Vvox;
double dTSst = 0.0;
double dTStt = 0.0;
if (nwts > 0) {
dTSst = Constants::GASK_KCAL*temperature_*((dTSs/nwts) + Constants::EULER_MASC);
dTStt = Constants::GASK_KCAL*temperature_*((dTSt/nwts) + Constants::EULER_MASC);
}
double dTSot = Constants::GASK_KCAL*temperature_*((dTSo/nwtt) + Constants::EULER_MASC);
infofile_->Printf("watcount in vol = %d\n", nwtt);
infofile_->Printf("watcount in subvol = %d\n", nwts);
infofile_->Printf("Total referenced translational entropy of the grid:"
" dTStrans = %9.5f kcal/mol, Nf=%d\n", dTStranstot, NFRAME_);
infofile_->Printf("Total 6d if all one vox: %9.5f kcal/mol\n", dTSst);
infofile_->Printf("Total t if all one vox: %9.5f kcal/mol\n", dTStt);
infofile_->Printf("Total o if all one vox: %9.5f kcal/mol\n", dTSot);
}
// Compute average voxel energy. Allocate these sets even if skipping energy
// to be consistent with previous output.
DataSet_GridFlt& PME_dens = static_cast<DataSet_GridFlt&>( *PME_);
DataSet_GridFlt& U_PME_dens = static_cast<DataSet_GridFlt&>( *U_PME_);
DataSet_GridFlt& Esw_dens = static_cast<DataSet_GridFlt&>( *Esw_ );
DataSet_GridFlt& Eww_dens = static_cast<DataSet_GridFlt&>( *Eww_ );
DataSet_GridFlt& neighbor_norm = static_cast<DataSet_GridFlt&>( *neighbor_norm_ );
DataSet_GridDbl& qtet = static_cast<DataSet_GridDbl&>( *order_norm_ );
Farray Esw_norm( MAX_GRID_PT_, 0.0 );
Farray Eww_norm( MAX_GRID_PT_, 0.0 );
Farray PME_norm( MAX_GRID_PT_,0.0);
Farray neighbor_dens( MAX_GRID_PT_, 0.0 );
if (!skipE_) {
if (usePme_) {
CalcAvgVoxelEnergy_PME(Vvox, PME_dens, U_PME_dens, PME_norm);
}// else {
CalcAvgVoxelEnergy(Vvox, Eww_dens, Esw_dens, Eww_norm, Esw_norm, qtet,
neighbor_norm, neighbor_dens);
//}
}
// Compute average dipole density.
DataSet_GridFlt& pol = static_cast<DataSet_GridFlt&>( *dipole_ );
DataSet_GridDbl& dipolex = static_cast<DataSet_GridDbl&>( *dipolex_ );
DataSet_GridDbl& dipoley = static_cast<DataSet_GridDbl&>( *dipoley_ );
DataSet_GridDbl& dipolez = static_cast<DataSet_GridDbl&>( *dipolez_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
dipolex[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
dipoley[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
dipolez[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
pol[gr_pt] = sqrt( dipolex[gr_pt]*dipolex[gr_pt] +
dipoley[gr_pt]*dipoley[gr_pt] +
dipolez[gr_pt]*dipolez[gr_pt] );
}
// Write the GIST output file.
// TODO: Make a data file format?
if (datafile_ != 0) {
mprintf("\tWriting GIST results for each voxel:\n");
// Create the format strings.
std::string fmtstr =
intFmt_.Fmt() + // grid point
" " + fltFmt_.Fmt() + // grid X
" " + fltFmt_.Fmt() + // grid Y
" " + fltFmt_.Fmt() + // grid Z
" " + intFmt_.Fmt() + // # waters
" " + fltFmt_.Fmt() + // gO
" " + fltFmt_.Fmt() + // gH
" " + fltFmt_.Fmt() + // dTStrans
" " + fltFmt_.Fmt() + // dTStrans_norm
" " + fltFmt_.Fmt() + // dTSorient_dens
" " + fltFmt_.Fmt() + // dTSorient_norm
" " + fltFmt_.Fmt() + // dTSsix
" " + fltFmt_.Fmt() + // dTSsix_norm
" " + fltFmt_.Fmt() + // Esw_dens
" " + fltFmt_.Fmt() + // Esw_norm
" " + fltFmt_.Fmt() + // Eww_dens
" " + fltFmt_.Fmt(); // EWW_norm
if (usePme_) {
fmtstr +=
" " + fltFmt_.Fmt() + // PME_dens
+ " " + fltFmt_.Fmt(); // PME_norm
}
fmtstr +=
" " + fltFmt_.Fmt() + // dipolex
" " + fltFmt_.Fmt() + // dipoley
" " + fltFmt_.Fmt() + // dipolez
" " + fltFmt_.Fmt() + // pol
" " + fltFmt_.Fmt() + // neighbor_dens
" " + fltFmt_.Fmt() + // neighbor_norm
" " + fltFmt_.Fmt() + // qtet
" \n"; // NEWLINE
if (debug_ > 0) mprintf("DEBUG: Fmt='%s'\n", fmtstr.c_str());
const char* gistOutputVersion;
if (usePme_)
gistOutputVersion = "v3";
else
gistOutputVersion = "v2";
// Do the header
datafile_->Printf("GIST Output %s "
"spacing=%.4f center=%.6f,%.6f,%.6f dims=%i,%i,%i \n"
"voxel xcoord ycoord zcoord population g_O g_H"
" dTStrans-dens(kcal/mol/A^3) dTStrans-norm(kcal/mol)"
" dTSorient-dens(kcal/mol/A^3) dTSorient-norm(kcal/mol)"
" dTSsix-dens(kcal/mol/A^3) dTSsix-norm(kcal/mol)"
" Esw-dens(kcal/mol/A^3) Esw-norm(kcal/mol)"
" Eww-dens(kcal/mol/A^3) Eww-norm-unref(kcal/mol)",
gistOutputVersion, gridspacing_,
gridcntr_[0], gridcntr_[1], gridcntr_[2],
(int)griddim_[0], (int)griddim_[1], (int)griddim_[2]);
if (usePme_)
datafile_->Printf(" PME-dens(kcal/mol/A^3) PME-norm(kcal/mol)");
datafile_->Printf(" Dipole_x-dens(D/A^3) Dipole_y-dens(D/A^3) Dipole_z-dens(D/A^3)"
" Dipole-dens(D/A^3) neighbor-dens(1/A^3) neighbor-norm order-norm\n");
// Loop over voxels
ProgressBar O_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
O_progress.Update( gr_pt );
size_t i, j, k;
gO_->ReverseIndex( gr_pt, i, j, k );
Vec3 XYZ = gO_->Bin().Center( i, j, k );
if (usePme_) {
datafile_->Printf(fmtstr.c_str(),
gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt],
dTStrans[gr_pt], dTStrans_norm[gr_pt],
dTSorient_dens[gr_pt], dTSorient_norm[gr_pt],
dTSsix[gr_pt], dTSsix_norm[gr_pt],
Esw_dens[gr_pt], Esw_norm[gr_pt],
Eww_dens[gr_pt], Eww_norm[gr_pt],
PME_dens[gr_pt], PME_norm[gr_pt],
dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt],
pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]);
} else {
datafile_->Printf(fmtstr.c_str(),
gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt],
dTStrans[gr_pt], dTStrans_norm[gr_pt],
dTSorient_dens[gr_pt], dTSorient_norm[gr_pt],
dTSsix[gr_pt], dTSsix_norm[gr_pt],
Esw_dens[gr_pt], Esw_norm[gr_pt],
Eww_dens[gr_pt], Eww_norm[gr_pt],
dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt],
pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]);
}
} // END loop over voxels
} // END datafile_ not null
// Write water-water interaction energy matrix
if (ww_Eij_ != 0) {
DataSet_MatrixFlt& ww_Eij = static_cast<DataSet_MatrixFlt&>( *ww_Eij_ );
double fac = 1.0 / (double)(NFRAME_ * 2);
for (unsigned int idx = 0; idx != ww_Eij.Size(); idx++) {
if (fabs(ww_Eij[idx]) < Constants::SMALL)
ww_Eij[idx] = 0.0;
else {
double val = (double)ww_Eij[idx];
ww_Eij[idx] = (float)(val * fac);
}
}
// Eij matrix output, skip any zeros.
for (unsigned int a = 1; a < MAX_GRID_PT_; a++) {
for (unsigned int l = 0; l < a; l++) {
double dbl = ww_Eij_->GetElement(a, l);
if (dbl != 0)
eijfile_->Printf("%10d %10d %12.5E\n", a, l, dbl);
}
}
}
gist_print_.Stop();
double total = gist_init_.Total() + gist_setup_.Total() +
gist_action_.Total() + gist_print_.Total();
mprintf("\tGIST timings:\n");
gist_init_.WriteTiming(1, "Init: ", total);
gist_setup_.WriteTiming(1, "Setup: ", total);
gist_action_.WriteTiming(1, "Action:", total);
gist_grid_.WriteTiming(2, "Grid: ", gist_action_.Total());
gist_nonbond_.WriteTiming(2, "Nonbond:", gist_action_.Total());
# ifdef LIBPME
if (usePme_)
gistPme_.Timing( gist_nonbond_.Total() );
# endif
//gist_nonbond_dist_.WriteTiming(3, "Dist2:", gist_nonbond_.Total());
//gist_nonbond_UV_.WriteTiming(3, "UV:", gist_nonbond_.Total());
//gist_nonbond_VV_.WriteTiming(3, "VV:", gist_nonbond_.Total());
//gist_nonbond_OV_.WriteTiming(3, "OV:", gist_nonbond_.Total());
gist_euler_.WriteTiming(2, "Euler: ", gist_action_.Total());
gist_dipole_.WriteTiming(2, "Dipole: ", gist_action_.Total());
gist_order_.WriteTiming(2, "Order: ", gist_action_.Total());
gist_print_.WriteTiming(1, "Print:", total);
mprintf("TIME:\tTotal: %.4f s\n", total);
#ifdef CUDA
this->freeGPUMemory();
#endif
}
#ifdef CUDA
void Action_GIST::NonbondCuda(ActionFrame frm) {
// Simply to get the information for the energetic calculations
std::vector<float> eww_result(this->numberAtoms_);
std::vector<float> esw_result(this->numberAtoms_);
std::vector<std::vector<int> > order_indices;
this->gist_nonbond_.Start();
float *recip = NULL;
float *ucell = NULL;
int boxinfo;
// Check Boxinfo and write the necessary data into recip, ucell and boxinfo.
switch(imageOpt_.ImagingType()) {
case ImageOption::NONORTHO:
recip = new float[9];
ucell = new float[9];
for (int i = 0; i < 9; ++i) {
ucell[i] = (float) frm.Frm().BoxCrd().UnitCell()[i];
recip[i] = (float) frm.Frm().BoxCrd().FracCell()[i];
}
boxinfo = 2;
break;
case ImageOption::ORTHO:
recip = new float[9];
recip[0] = frm.Frm().BoxCrd().Param(Box::X);
recip[1] = frm.Frm().BoxCrd().Param(Box::Y);
recip[2] = frm.Frm().BoxCrd().Param(Box::Z);
ucell = NULL;
boxinfo = 1;
break;
case ImageOption::NO_IMAGE:
recip = NULL;
ucell = NULL;
boxinfo = 0;
break;
default:
mprinterr("Error: Unexpected box information found.");
return;
}
std::vector<int> result_o = std::vector<int>(4 * this->numberAtoms_);
std::vector<int> result_n = std::vector<int>(this->numberAtoms_);
// Call the GPU Wrapper, which subsequently calls the kernel, after setup operations.
// Must create arrays from the vectors, does that by getting the address of the first element of the vector.
std::vector<std::vector<float> > e_result = doActionCudaEnergy(frm.Frm().xAddress(), this->NBindex_c_, this->numberAtomTypes_, this->paramsLJ_c_, this->molecule_c_, boxinfo, recip, ucell, this->numberAtoms_, this->min_c_,
this->max_c_, this->headAtomType_,this->NeighborCut2_, &(result_o[0]), &(result_n[0]), this->result_w_c_,
this->result_s_c_, this->result_O_c_, this->result_N_c_, this->doOrder_);
eww_result = e_result.at(0);
esw_result = e_result.at(1);
if (this->doOrder_) {
int counter = 0;
for (unsigned int i = 0; i < (4 * this->numberAtoms_); i += 4) {
++counter;
std::vector<int> temp;
for (unsigned int j = 0; j < 4; ++j) {
temp.push_back(result_o.at(i + j));
}
order_indices.push_back(temp);
}
}
delete[] recip; // Free memory
delete[] ucell; // Free memory
for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++) {
int headAtomIndex = O_idxs_[sidx];
size_t bin_i, bin_j, bin_k;
const double *vec = frm.Frm().XYZ(headAtomIndex);
int voxel = -1;
if (this->gO_->Bin().Calc(vec[0], vec[1], vec[2], bin_i, bin_j, bin_k)) {
voxel = this->gO_->CalcIndex(bin_i, bin_j, bin_k);
this->neighbor_.at(0).at(voxel) += result_n.at(headAtomIndex);
// This is not nice, as it assumes that O is set before the two Hydrogens
// might be the case, but is still not nice (in my opinion)
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
this->Esw_->UpdateVoxel(voxel, esw_result.at(headAtomIndex + IDX));
this->Eww_->UpdateVoxel(voxel, eww_result.at(headAtomIndex + IDX));
}
// Order calculation
if (this->doOrder_) {
double sum = 0;
Vec3 cent( frm.Frm().xAddress() + (headAtomIndex) * 3 );
std::vector<Vec3> vectors;
switch(imageOpt_.ImagingType()) {
case ImageOption::NONORTHO:
case ImageOption::ORTHO:
{
Vec3 vec(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
}
break;
default:
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3) ) - cent );
}
for (int i = 0; i < 3; ++i) {
for (int j = i + 1; j < 4; ++j) {
double cosThet = (vectors.at(i) * vectors.at(j)) / sqrt(vectors.at(i).Magnitude2() * vectors.at(j).Magnitude2());
sum += (cosThet + 1.0/3) * (cosThet + 1.0/3);
}
}
this->order_norm_->UpdateVoxel(voxel, 1.0 - (3.0/8.0) * sum);
}
}
}
this->gist_nonbond_.Stop();
}
/**
* Frees all the Memory on the GPU.
*/
void Action_GIST::freeGPUMemory(void) {
freeCuda(this->NBindex_c_);
freeCuda(this->molecule_c_);
freeCuda(this->paramsLJ_c_);
freeCuda(this->max_c_);
freeCuda(this->min_c_);
freeCuda(this->result_w_c_);
freeCuda(this->result_s_c_);
freeCuda(this->result_O_c_);
freeCuda(this->result_N_c_);
this->NBindex_c_ = NULL;
this->molecule_c_ = NULL;
this->paramsLJ_c_ = NULL;
this->max_c_ = NULL;
this->min_c_ = NULL;
this->result_w_c_= NULL;
this->result_s_c_= NULL;
this->result_O_c_ = NULL;
this->result_N_c_ = NULL;
}
/**
* Copies data from the CPU to the GPU.
* @throws: CudaException
*/
void Action_GIST::copyToGPU(void) {
try {
copyMemoryToDevice(&(this->NBIndex_[0]), this->NBindex_c_, this->NBIndex_.size() * sizeof(int));
copyMemoryToDeviceStruct(&(this->charges_[0]), &(this->atomTypes_[0]), this->solvent_, &(this->molecule_[0]), this->numberAtoms_, &(this->molecule_c_),
&(this->lJParamsA_[0]), &(this->lJParamsB_[0]), this->lJParamsA_.size(), &(this->paramsLJ_c_));
} catch (CudaException &ce) {
this->freeGPUMemory();
mprinterr("Error: Could not copy data to the device.\n");
throw ce;
} catch (std::exception &e) {
this->freeGPUMemory();
throw e;
}
}
#endif
| Java |
<?php
/**
* Kiwitrees: Web based Family History software
* Copyright (C) 2012 to 2022 kiwitrees.net
*
* Derived from webtrees (www.webtrees.net)
* Copyright (C) 2010 to 2012 webtrees development team
*
* Derived from PhpGedView (phpgedview.sourceforge.net)
* Copyright (C) 2002 to 2010 PGV Development Team
*
* Kiwitrees 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 Kiwitrees. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('KT_KIWITREES')) {
header('HTTP/1.0 403 Forbidden');
exit;
}
// add new custom_lang table
self::exec(
"CREATE TABLE IF NOT EXISTS `##custom_lang`(".
" custom_lang_id INTEGER NOT NULL AUTO_INCREMENT,".
" language VARCHAR(10) NOT NULL,".
" standard_text LONGTEXT NOT NULL,".
" custom_text LONGTEXT NOT NULL,".
" updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,".
" PRIMARY KEY (custom_lang_id)".
") COLLATE utf8_unicode_ci ENGINE=InnoDB"
);
// Update the version to indicate success
KT_Site::preference($schema_name, $next_version);
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Fri Mar 04 14:41:00 EST 2016 -->
<title>ChanceCellInfoFormatter</title>
<meta name="date" content="2016-03-04">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ChanceCellInfoFormatter";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ChanceCellInfoFormatter.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/FreeParkingCellInfoFormatter.html" title="class in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html" target="_top">Frames</a></li>
<li><a href="ChanceCellInfoFormatter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">edu.towson.cis.cosc603.project2.monopoly.gui</div>
<h2 title="Class ChanceCellInfoFormatter" class="title">Class ChanceCellInfoFormatter</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>edu.towson.cis.cosc603.project2.monopoly.gui.ChanceCellInfoFormatter</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">ChanceCellInfoFormatter</span>
extends java.lang.Object
implements <a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html#CHANCE_CELL_LABEL">CHANCE_CELL_LABEL</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html#ChanceCellInfoFormatter()">ChanceCellInfoFormatter</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html#format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">format</a></strong>(<a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/IOwnable.html" title="interface in edu.towson.cis.cosc603.project2.monopoly">IOwnable</a> cell)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="CHANCE_CELL_LABEL">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CHANCE_CELL_LABEL</h4>
<pre>public static final java.lang.String CHANCE_CELL_LABEL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#edu.towson.cis.cosc603.project2.monopoly.gui.ChanceCellInfoFormatter.CHANCE_CELL_LABEL">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ChanceCellInfoFormatter()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ChanceCellInfoFormatter</h4>
<pre>public ChanceCellInfoFormatter()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>format</h4>
<pre>public java.lang.String format(<a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/IOwnable.html" title="interface in edu.towson.cis.cosc603.project2.monopoly">IOwnable</a> cell)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html#format(edu.towson.cis.cosc603.project2.monopoly.IOwnable)">format</a></code> in interface <code><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui">CellInfoFormatter</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ChanceCellInfoFormatter.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/CellInfoFormatter.html" title="interface in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../edu/towson/cis/cosc603/project2/monopoly/gui/FreeParkingCellInfoFormatter.html" title="class in edu.towson.cis.cosc603.project2.monopoly.gui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?edu/towson/cis/cosc603/project2/monopoly/gui/ChanceCellInfoFormatter.html" target="_top">Frames</a></li>
<li><a href="ChanceCellInfoFormatter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
README
======
`vcert` A web-based certificate authority mangement system built atop OpenSSL.
Copyright Alan Viars 2013
Open Source License: MPL See LICENSE.txt
Last Updated: November 4, 2013
About
-----
`vcert` is a web-based (Django) Certificate Authority (or CA) that uses OpenSSL
under the hood. The site DirectCA.org runs vcert. It was built specifically to
build x509 certificates compatible with the Direct Project. It is written in
Python and Django and can run atop Apache2 or other webserver.
`vcert` can be used to manage a trust anchor (i.e. a registration authority or
HISP) or a root CA.
`vcert` supports revocation via certificate revocation lists (CRLs). A CRL is
created for each trust anchor and is published to a URL.
This software was designed to assist in testing for compliance with the Direct
Project's Applicability Statement. Perhaps you are not working in Health IT at
all and are just looking for a simple way to manage certificates. You may well
be able to use this project for that purpose.
CODE CONTRIBUTIONS & PULL REQUEST WELCOME!
Installation Part 1 - Download and Initial Setup
------------------------------------------------
`vcert` has a number of dependencies including OpenSSL, Python,
and Django. This software was tested with OpenSSL version 1.0.1, Python 2.7
and Django 1.5. SQLite is the default database and it was tested
with SQLite version 3. The following instructions assume Ubuntu 13.04 is the
operating system, but it is possible to use others. (If anyone wants to
contribute Windows, Mac, or other operating system instructions please do so.)
Here is how to get started on Ubuntu 13.04. From the terminal, start by
installing OpenSSL. This is likely already installed, but installation
instructions are added here for clarity.
sudo apt-get install openssl
Now install pip and make sure its up to date.
sudo apt-get install python-pip
sudo pip install --upgrade pip
Install git and then clone the master repository.
sudo apt-get install git-core
git clone https://github.com/videntity/vcert.git
Now change into the project's directory.
cd vcert
Let's install the necessary python libraries including Django from the
project's requirements file.
sudo pip install -r vcert/requirements.txt
Now that Django is installed lets setup our database. Be sure and say yes when
asking to create an administrative account as this will be used in the CA's
administration.
python manage.py syncdb
A directory for OpenSSL's CA must be created. We will do so by creating a
symbolic link between `/opt/ca` and `vcert/apps/certificates/ca` directories.
sudo ln -s vcert/apps/certificates/ca /opt/
Now copy settings_local_example.py to settings_example.py.
cp settings_local_example.py settings_example.py
You can at this point try out the server at this point with
`python manage.py runserver`, but your settings_local.py settings will need to
be customized before everything will work as expected.
Installation Part 2 - Django Settings
-------------------------------------
The file `settings.py` contains default settings, where the file
`settings_local.py` add and overwrites what is in `settings.py` via Python
imports.
One of the main changes is replacing `examaple.com` with your own domain. You'll
also want to setup email settings for outgoing email notifications and setup web
locations for publishing certificates and CRLs.
Certificates and CRLs get published via Amazon Web Service's (AWS) Simple
Storage Service (S3) and email notifications are sent via Simple Email Service
(SES). The email setup is easily changed, but the certificate and CRL
publishing requires S3. `vcert` assumes you create three S3 buckets with "vanity"
URLs. They are `ca` for CRLs and the CA's public certificate, `pubcerts` for public
certificates issued, and `privcerts` for private certificates. For illustration,
if you want to host your CA on the domain `example.com`, then you would create the
buckets `ca.example.com`, `privcerts.example.com` and `pubcerts.example.com`.
You need to map the DNS entries accordingly to create the "vanity" URL. This is
accomplished within AWS management console for S3 and in your DNS provider's
website.
Please see the in-line comments inside `settings_local.py` for instructions
on what the various settings do.
Installlation Part 3 - OpenSSL CA Configuration
-----------------------------------------------
There are stil a few of items that need to be addressed:
Most notably you need to do the following:
Create and/or install the root CA's (or subordinate certificate's) private
certificate and change settings_local.py accordingly. Here is how to generate a
new CA keypair with a password on the pricate key. It assumes the domain
`ca.example.com` and uses the configuration file
`/opt/ca/conf/ca.example.com.cnf`. Before this next step, you will likely want
to make adjustment there such the changing "example.com" to your domain, setting
organizational name, city, state, and so on. Here are the step.
cd /opt/ca
openssl req -nodes -config conf/ca.example.com.cnf -days 7330 -x509 -newkey rsa:4096 -out public/ca.example.com.pem -outform PEM
openssl rsa -des3 -in ./private/ca.example.comKey.pem -out ./private/ca.example.comKey.pem
You will end up with the CA's public key in '/opt/ca/public' and the private key
in '/opt/ca/private'.
You need to publish the CA's public certificate and CRL somehere. `ca`
(e.g. `ca.example.com`) is a reasonable place. In the above example, we used
the configuration file `ca.example.com.cnf`. You can use openssl command line
to create the CRL for your CA.
Installation Part 4 - Setting up Cron for CRL Updates
-------------------------------------------------------
In order to make the CRL updates automatic, we will use cron to execute a script
to perform the update. Edit your crontab like so.
crontab -r
Now add the following line to your cron file.
0 */2 * * * /home/ubuntu/django-apps/vcert/scripts/buildcrl.sh >> /home/ubuntu/crl.log
This assumes your `vcert` project is located at `/home/ubuntu/django-apps/vcert/`.
and the output of this operation is written to `/home/ubuntu/crl.log`. Adjust
these paths to fit your local environment. With this setting we are updating
the CRLs every 30 minutes. Note that each "Trust Anchor" has its own CRL.
Run the Application
-------------------
Now you can run the `vcert` in development mode:
python manage.py runserver
Production Deployment
---------------------
The convention is to deploy `vcert` on server named `console` (e.g. `console.example.com`).
Please refer to Django's documentation for more information on deploying Django
https://docs.djangoproject.com/en/dev/howto/deployment/
Security
--------
`vcert` makes no security claims and is provided AS-IS with NO WARRANTY. Django
has a number of security features that 'vcert' uses. It is recommended that you
use a unique `SECRET_KEY` and that you host the service on HTTPS using a valid
certificate. User authentication is accomplished via django's standard `auth`
which uses salted and hashed passwords.
In order to enable a user to act as an administraor (i.e. verify/approve
certificates) you need to give access to the Django admin to said user.
(`http://127.0.0.1:8000/admin` in a development
configuration). You can so this in two ways:
1. Make this user a superuser (with access to all models).
2. Set the is_staff flag and enable access on the `Certificate` models.
See https://docs.djangoproject.com/en/dev/topics/auth/ for more information on
authentication in Django.
Operation
---------
`vcert` operation is quite simple. Any user with a CA account can create a new
"Trust anchor". A trust anchor is the child certificate of the `vcerts`
certificate with signing authority. (Remember this is configured in
settings_local.py) After the Trust anchor request is made an email is sent to
the CA's verifier (`CA_VERIFIER_EMAIL` in`settings_local.py`).
What you do for "verification" is up to you. After the
verifier verifies the information, then the verifier finds the certificate in
question within the Django admin, checks the "verify" box and then clicks save.
(How you do verification is up to you). When this happens, certificates are
published and an email notification is sent to the person requesting the
certificate. Then the user may create leaf nodes off of the Trust Archor from
his or her account. These, too, go through the same verification notification
and verification process before they may be accessed by the requestor.
As written, `vcert` requires an invitation code to create an account. This is
accomplished in the Django admin. Click the section that says "Invitations"
under "Accounts", then click "Add invitation", then provide an invitation code
and the email to which it should be sent. Click "Save" and an email with the
code will be sent. Anyone can use the invitation code. In other words, it does
not require the new user to use the email in the invitation to register.
Happy CA-ing!
@aviars
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.