repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
DravitLochan/accounts.susi.ai
src/utils/ChatMessageUtils.js
986
export function convertRawMessage(rawMessage, currentThreadID) { return { ...rawMessage, date: new Date(rawMessage.timestamp), isRead: rawMessage.threadID === currentThreadID }; }; export function getCreatedMessageData(text, currentThreadID) { var timestamp = Date.now(); return { id: 'm_' + timestamp, threadID: currentThreadID, authorName: 'You', date: new Date(timestamp), text: text, isRead: true, type: 'message' }; }; export function getSUSIMessageData(message, currentThreadID) { var timestamp = Date.now(); let receivedMessage = { id: 'm_' + timestamp, threadID: currentThreadID, authorName: 'SUSI', // hard coded for the example text: message.text, response: message.response, actions: message.actions, websearchresults: message.websearchresults, date: new Date(timestamp), isRead: true, responseTime: message.responseTime, type: 'message' }; return receivedMessage; }
lgpl-2.1
plast-lab/soot
src/main/java/soot/coffi/Instruction_If_icmpge.java
2261
package soot.coffi; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 Clark Verbrugge * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Instruction subclasses are used to represent parsed bytecode; each bytecode operation has a corresponding subclass of * Instruction. * <p> * Each subclass is derived from one of * <ul> * <li>Instruction</li> * <li>Instruction_noargs (an Instruction with no embedded arguments)</li> * <li>Instruction_byte (an Instruction with a single byte data argument)</li> * <li>Instruction_bytevar (a byte argument specifying a local variable)</li> * <li>Instruction_byteindex (a byte argument specifying a constant pool index)</li> * <li>Instruction_int (an Instruction with a single short data argument)</li> * <li>Instruction_intvar (a short argument specifying a local variable)</li> * <li>Instruction_intindex (a short argument specifying a constant pool index)</li> * <li>Instruction_intbranch (a short argument specifying a code offset)</li> * <li>Instruction_longbranch (an int argument specifying a code offset)</li> * </ul> * * @author Clark Verbrugge * @see Instruction * @see Instruction_noargs * @see Instruction_byte * @see Instruction_bytevar * @see Instruction_byteindex * @see Instruction_int * @see Instruction_intvar * @see Instruction_intindex * @see Instruction_intbranch * @see Instruction_longbranch * @see Instruction_Unknown */ class Instruction_If_icmpge extends Instruction_intbranch { public Instruction_If_icmpge() { super((byte) ByteCode.IF_ICMPGE); name = "if_icmpge"; } }
lgpl-2.1
radekp/qt
src/gui/graphicsview/qgraphicssceneindex.cpp
24608
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /*! \class QGraphicsSceneIndex \brief The QGraphicsSceneIndex class provides a base class to implement a custom indexing algorithm for discovering items in QGraphicsScene. \since 4.6 \ingroup graphicsview-api \internal The QGraphicsSceneIndex class provides a base class to implement a custom indexing algorithm for discovering items in QGraphicsScene. You need to subclass it and reimplement addItem, removeItem, estimateItems and items in order to have an functional indexing. \sa QGraphicsScene, QGraphicsView */ #include "qdebug.h" #include "qgraphicsscene.h" #include "qgraphicsitem_p.h" #include "qgraphicsscene_p.h" #include "qgraphicswidget.h" #include "qgraphicssceneindex_p.h" #include "qgraphicsscenebsptreeindex_p.h" #ifndef QT_NO_GRAPHICSVIEW QT_BEGIN_NAMESPACE class QGraphicsSceneIndexRectIntersector : public QGraphicsSceneIndexIntersector { public: bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode, const QTransform &deviceTransform) const { QRectF brect = item->boundingRect(); _q_adjustRect(&brect); // ### Add test for this (without making things slower?) Q_UNUSED(exposeRect); bool keep = true; const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item); if (itemd->itemIsUntransformable()) { // Untransformable items; map the scene rect to item coordinates. const QTransform transform = item->deviceTransform(deviceTransform); QRectF itemRect = (deviceTransform * transform.inverted()).mapRect(sceneRect); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = itemRect.contains(brect) && itemRect != brect; else keep = itemRect.intersects(brect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath itemPath; itemPath.addRect(itemRect); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode); } } else { Q_ASSERT(!itemd->dirtySceneTransform); const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly ? brect.translated(itemd->sceneTransform.dx(), itemd->sceneTransform.dy()) : itemd->sceneTransform.mapRect(brect); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = sceneRect != brect && sceneRect.contains(itemSceneBoundingRect); else keep = sceneRect.intersects(itemSceneBoundingRect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath rectPath; rectPath.addRect(sceneRect); if (itemd->sceneTransformTranslateOnly) rectPath.translate(-itemd->sceneTransform.dx(), -itemd->sceneTransform.dy()); else rectPath = itemd->sceneTransform.inverted().map(rectPath); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, rectPath, mode); } } return keep; } QRectF sceneRect; }; class QGraphicsSceneIndexPointIntersector : public QGraphicsSceneIndexIntersector { public: bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode, const QTransform &deviceTransform) const { QRectF brect = item->boundingRect(); _q_adjustRect(&brect); // ### Add test for this (without making things slower?) Q_UNUSED(exposeRect); bool keep = false; const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item); if (itemd->itemIsUntransformable()) { // Untransformable items; map the scene point to item coordinates. const QTransform transform = item->deviceTransform(deviceTransform); QPointF itemPoint = (deviceTransform * transform.inverted()).map(scenePoint); keep = brect.contains(itemPoint); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath pointPath; pointPath.addRect(QRectF(itemPoint, QSizeF(1, 1))); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, pointPath, mode); } } else { Q_ASSERT(!itemd->dirtySceneTransform); QRectF sceneBoundingRect = itemd->sceneTransformTranslateOnly ? brect.translated(itemd->sceneTransform.dx(), itemd->sceneTransform.dy()) : itemd->sceneTransform.mapRect(brect); keep = sceneBoundingRect.intersects(QRectF(scenePoint, QSizeF(1, 1))); if (keep) { QPointF p = itemd->sceneTransformTranslateOnly ? QPointF(scenePoint.x() - itemd->sceneTransform.dx(), scenePoint.y() - itemd->sceneTransform.dy()) : itemd->sceneTransform.inverted().map(scenePoint); keep = item->contains(p); } } return keep; } QPointF scenePoint; }; class QGraphicsSceneIndexPathIntersector : public QGraphicsSceneIndexIntersector { public: bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode, const QTransform &deviceTransform) const { QRectF brect = item->boundingRect(); _q_adjustRect(&brect); // ### Add test for this (without making things slower?) Q_UNUSED(exposeRect); bool keep = true; const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item); if (itemd->itemIsUntransformable()) { // Untransformable items; map the scene rect to item coordinates. const QTransform transform = item->deviceTransform(deviceTransform); QPainterPath itemPath = (deviceTransform * transform.inverted()).map(scenePath); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = itemPath.contains(brect); else keep = itemPath.intersects(brect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode); } else { Q_ASSERT(!itemd->dirtySceneTransform); const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly ? brect.translated(itemd->sceneTransform.dx(), itemd->sceneTransform.dy()) : itemd->sceneTransform.mapRect(brect); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = scenePath.contains(itemSceneBoundingRect); else keep = scenePath.intersects(itemSceneBoundingRect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath itemPath = itemd->sceneTransformTranslateOnly ? scenePath.translated(-itemd->sceneTransform.dx(), -itemd->sceneTransform.dy()) : itemd->sceneTransform.inverted().map(scenePath); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode); } } return keep; } QPainterPath scenePath; }; /*! Constructs a private scene index. */ QGraphicsSceneIndexPrivate::QGraphicsSceneIndexPrivate(QGraphicsScene *scene) : scene(scene) { pointIntersector = new QGraphicsSceneIndexPointIntersector; rectIntersector = new QGraphicsSceneIndexRectIntersector; pathIntersector = new QGraphicsSceneIndexPathIntersector; } /*! Destructor of private scene index. */ QGraphicsSceneIndexPrivate::~QGraphicsSceneIndexPrivate() { delete pointIntersector; delete rectIntersector; delete pathIntersector; } /*! \internal Checks if item collides with the path and mode, but also checks that if it doesn't collide, maybe its frame rect will. */ bool QGraphicsSceneIndexPrivate::itemCollidesWithPath(const QGraphicsItem *item, const QPainterPath &path, Qt::ItemSelectionMode mode) { if (item->collidesWithPath(path, mode)) return true; if (item->isWidget()) { // Check if this is a window, and if its frame rect collides. const QGraphicsWidget *widget = static_cast<const QGraphicsWidget *>(item); if (widget->isWindow()) { QRectF frameRect = widget->windowFrameRect(); QPainterPath framePath; framePath.addRect(frameRect); bool intersects = path.intersects(frameRect); if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect) return intersects || path.contains(frameRect.topLeft()) || framePath.contains(path.elementAt(0)); return !intersects && path.contains(frameRect.topLeft()); } } return false; } /*! \internal This function returns the items in ascending order. */ void QGraphicsSceneIndexPrivate::recursive_items_helper(QGraphicsItem *item, QRectF exposeRect, QGraphicsSceneIndexIntersector *intersector, QList<QGraphicsItem *> *items, const QTransform &viewTransform, Qt::ItemSelectionMode mode, qreal parentOpacity) const { Q_ASSERT(item); if (!item->d_ptr->visible) return; const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity); const bool itemIsFullyTransparent = (opacity < 0.0001); const bool itemHasChildren = !item->d_ptr->children.isEmpty(); if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity())) return; // Update the item's scene transform if dirty. const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable(); const bool wasDirtyParentSceneTransform = item->d_ptr->dirtySceneTransform && !itemIsUntransformable; if (wasDirtyParentSceneTransform) { item->d_ptr->updateSceneTransformFromParent(); Q_ASSERT(!item->d_ptr->dirtySceneTransform); } const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape); bool processItem = !itemIsFullyTransparent; if (processItem) { processItem = intersector->intersect(item, exposeRect, mode, viewTransform); if (!processItem && (!itemHasChildren || itemClipsChildrenToShape)) { if (wasDirtyParentSceneTransform) item->d_ptr->invalidateChildrenSceneTransform(); return; } } // else we know for sure this item has children we must process. int i = 0; if (itemHasChildren) { // Sort children. item->d_ptr->ensureSortedChildren(); // Clip to shape. if (itemClipsChildrenToShape && !itemIsUntransformable) { QPainterPath mappedShape = item->d_ptr->sceneTransformTranslateOnly ? item->shape().translated(item->d_ptr->sceneTransform.dx(), item->d_ptr->sceneTransform.dy()) : item->d_ptr->sceneTransform.map(item->shape()); exposeRect &= mappedShape.controlPointRect(); } // Process children behind for (i = 0; i < item->d_ptr->children.size(); ++i) { QGraphicsItem *child = item->d_ptr->children.at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) break; if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity)) continue; recursive_items_helper(child, exposeRect, intersector, items, viewTransform, mode, opacity); } } // Process item if (processItem) items->append(item); // Process children in front if (itemHasChildren) { for (; i < item->d_ptr->children.size(); ++i) { QGraphicsItem *child = item->d_ptr->children.at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity)) continue; recursive_items_helper(child, exposeRect, intersector, items, viewTransform, mode, opacity); } } } void QGraphicsSceneIndexPrivate::init() { if (!scene) return; QObject::connect(scene, SIGNAL(sceneRectChanged(QRectF)), q_func(), SLOT(updateSceneRect(QRectF))); } /*! Constructs an abstract scene index for a given \a scene. */ QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsScene *scene) : QObject(*new QGraphicsSceneIndexPrivate(scene), scene) { d_func()->init(); } /*! \internal */ QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsSceneIndexPrivate &dd, QGraphicsScene *scene) : QObject(dd, scene) { d_func()->init(); } /*! Destroys the scene index. */ QGraphicsSceneIndex::~QGraphicsSceneIndex() { } /*! Returns the scene of this index. */ QGraphicsScene* QGraphicsSceneIndex::scene() const { Q_D(const QGraphicsSceneIndex); return d->scene; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const Returns all visible items that, depending on \a mode, are at the specified \a pos and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with \a pos are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QList<QGraphicsItem *> itemList; d->pointIntersector->scenePoint = pos; d->items_helper(QRectF(pos, QSizeF(1, 1)), d->pointIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const \overload Returns all visible items that, depending on \a mode, are either inside or intersect with the specified \a rect and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained by \a rect are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QRectF exposeRect = rect; _q_adjustRect(&exposeRect); QList<QGraphicsItem *> itemList; d->rectIntersector->sceneRect = rect; d->items_helper(exposeRect, d->rectIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const \overload Returns all visible items that, depending on \a mode, are either inside or intersect with the specified \a polygon and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained by \a polygon are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QList<QGraphicsItem *> itemList; QRectF exposeRect = polygon.boundingRect(); _q_adjustRect(&exposeRect); QPainterPath path; path.addPolygon(polygon); d->pathIntersector->scenePath = path; d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const \overload Returns all visible items that, depending on \a mode, are either inside or intersect with the specified \a path and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained by \a path are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QList<QGraphicsItem *> itemList; QRectF exposeRect = path.controlPointRect(); _q_adjustRect(&exposeRect); d->pathIntersector->scenePath = path; d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! This virtual function return an estimation of items at position \a point. This method return a list sorted using \a order. */ QList<QGraphicsItem *> QGraphicsSceneIndex::estimateItems(const QPointF &point, Qt::SortOrder order) const { return estimateItems(QRectF(point, QSize(1, 1)), order); } QList<QGraphicsItem *> QGraphicsSceneIndex::estimateTopLevelItems(const QRectF &rect, Qt::SortOrder order) const { Q_D(const QGraphicsSceneIndex); Q_UNUSED(rect); QGraphicsScenePrivate *scened = d->scene->d_func(); scened->ensureSortedTopLevelItems(); if (order == Qt::DescendingOrder) { QList<QGraphicsItem *> sorted; for (int i = scened->topLevelItems.size() - 1; i >= 0; --i) sorted << scened->topLevelItems.at(i); return sorted; } return scened->topLevelItems; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(Qt::SortOrder order = Qt::DescendingOrder) const This pure virtual function all items in the index and sort them using \a order. */ /*! Notifies the index that the scene's scene rect has changed. \a rect is thew new scene rect. \sa QGraphicsScene::sceneRect() */ void QGraphicsSceneIndex::updateSceneRect(const QRectF &rect) { Q_UNUSED(rect); } /*! This virtual function removes all items in the scene index. */ void QGraphicsSceneIndex::clear() { const QList<QGraphicsItem *> allItems = items(); for (int i = 0 ; i < allItems.size(); ++i) removeItem(allItems.at(i)); } /*! \fn virtual void QGraphicsSceneIndex::addItem(QGraphicsItem *item) = 0 This pure virtual function inserts an \a item to the scene index. \sa removeItem(), deleteItem() */ /*! \fn virtual void QGraphicsSceneIndex::removeItem(QGraphicsItem *item) = 0 This pure virtual function removes an \a item to the scene index. \sa addItem(), deleteItem() */ /*! This method is called when an \a item has been deleted. The default implementation call removeItem. Be carefull, if your implementation of removeItem use pure virtual method of QGraphicsItem like boundingRect(), then you should reimplement this method. \sa addItem(), removeItem() */ void QGraphicsSceneIndex::deleteItem(QGraphicsItem *item) { removeItem(item); } /*! This virtual function is called by QGraphicsItem to notify the index that some part of the \a item 's state changes. By reimplementing this function, your can react to a change, and in some cases, (depending on \a change,) adjustments in the index can be made. \a change is the parameter of the item that is changing. \a value is the value that changed; the type of the value depends on \a change. The default implementation does nothing. \sa QGraphicsItem::GraphicsItemChange */ void QGraphicsSceneIndex::itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const QVariant &value) { Q_UNUSED(item); Q_UNUSED(change); Q_UNUSED(value); } /*! Notify the index for a geometry change of an \a item. \sa QGraphicsItem::prepareGeometryChange() */ void QGraphicsSceneIndex::prepareBoundingRectChange(const QGraphicsItem *item) { Q_UNUSED(item); } QT_END_NAMESPACE #include "moc_qgraphicssceneindex_p.cpp" #endif // QT_NO_GRAPHICSVIEW
lgpl-2.1
BlesseNtumble/Traincraft-5
src/main/java/train/client/render/models/ModelFreightWagenDB.java
8722
package train.client.render.models; import net.minecraft.client.model.ModelBase; import net.minecraft.entity.Entity; import train.client.render.CustomModelRenderer; import train.common.core.handlers.ConfigHandler; public class ModelFreightWagenDB extends ModelBase { public ModelFreightWagenDB() { box = new CustomModelRenderer(70, 25, 256, 128); box.addBox(0F, 0F, 0F, 8, 4, 4); box.setPosition(-5F, 2F, 0F); box0 = new CustomModelRenderer(3, 27, 256, 128); box0.addBox(0F, 0F, 0F, 14, 5, 1); box0.setPosition(-23F, 1F, -6F); box1 = new CustomModelRenderer(189, 12, 256, 128); box1.addBox(0F, 0F, 0F, 8, 7, 0); box1.setPosition(-20F, 0F, 5F); box10 = new CustomModelRenderer(213, 80, 256, 128); box10.addBox(0F, 0F, 0F, 1, 5, 16); box10.setPosition(27F, 6F, -8F); box11 = new CustomModelRenderer(158, 77, 256, 128); box11.addBox(0F, 0F, 0F, 2, 3, 4); box11.setPosition(28F, 6F, -2F); box12 = new CustomModelRenderer(159, 87, 256, 128); box12.addBox(0F, 0F, 0F, 14, 17, 24); box12.setPosition(-7F, 8F, -12F); box13 = new CustomModelRenderer(0, 46, 256, 128); box13.addBox(0F, -2F, 0F, 54, 2, 6); box13.setPosition(-27F, 32F, -3F); box14 = new CustomModelRenderer(73, 69, 256, 128); box14.addBox(0F, 0F, 0F, 28, 2, 1); box14.setPosition(-19F, 25F, 11F); box15 = new CustomModelRenderer(0, 0, 256, 128); box15.addBox(0F, 0F, 0F, 1, 8, 1); box15.setPosition(5F, 2F, -8F); box15.rotateAngleX = -6.1086523819801535F; box16 = new CustomModelRenderer(1, 55, 256, 128); box16.addBox(0F, -2F, 0F, 54, 2, 5); box16.setPosition(-27F, 32F, 3F); box16.rotateAngleX = -6.09119908946021F; box17 = new CustomModelRenderer(1, 38, 256, 128); box17.addBox(0F, -2F, 0F, 54, 2, 5); box17.setPosition(-27F, 31F, 8F); box17.rotateAngleX = -5.480333851262195F; box18 = new CustomModelRenderer(1, 55, 256, 128); box18.addBox(0F, -2F, 0F, 54, 2, 5); box18.setPosition(27F, 32F, -3F); box18.rotateAngleX = -6.09119908946021F; box18.rotateAngleY = -3.141592653589793F; box19 = new CustomModelRenderer(1, 38, 256, 128); box19.addBox(0F, -2F, 0F, 54, 2, 5); box19.setPosition(27F, 31F, -8F); box19.rotateAngleX = -5.480333851262195F; box19.rotateAngleY = -3.141592653589793F; box2 = new CustomModelRenderer(96, 1, 256, 128); box2.addBox(0F, 0F, 0F, 2, 2, 14); box2.setPosition(15F, 2F, -7F); box20 = new CustomModelRenderer(187, 66, 256, 128); box20.addBox(0F, 0F, 0F, 1, 5, 16); box20.setPosition(-28F, 6F, -8F); box21 = new CustomModelRenderer(73, 69, 256, 128); box21.addBox(0F, 0F, 0F, 28, 2, 1); box21.setPosition(-9F, 25F, -12F); box22 = new CustomModelRenderer(0, 65, 256, 128); box22.addBox(0F, 0F, 0F, 1, 20, 1); box22.setPosition(-28F, 11F, -4F); box23 = new CustomModelRenderer(0, 65, 256, 128); box23.addBox(0F, 0F, 0F, 1, 20, 1); box23.setPosition(-28F, 11F, 3F); box24 = new CustomModelRenderer(0, 83, 256, 128); box24.addBox(0F, 0F, 0F, 54, 23, 22); box24.setPosition(-27F, 8F, -11F); box25 = new CustomModelRenderer(146, 80, 256, 128); box25.addBox(0F, 0F, 0F, 1, 3, 3); box25.setPosition(28F, 7F, -7F); box26 = new CustomModelRenderer(104, 42, 256, 128); box26.addBox(0F, 0F, 0F, 54, 2, 22); box26.setPosition(-27F, 6F, -11F); box27 = new CustomModelRenderer(134, 92, 256, 128); box27.addBox(0F, 0F, 0F, 14, 1, 3); box27.setPosition(-7F, 2F, -10F); box28 = new CustomModelRenderer(0, 65, 256, 128); box28.addBox(0F, 0F, 0F, 1, 20, 1); box28.setPosition(27F, 11F, -4F); box29 = new CustomModelRenderer(0, 65, 256, 128); box29.addBox(0F, 0F, 0F, 1, 20, 1); box29.setPosition(27F, 11F, 3F); box3 = new CustomModelRenderer(96, 1, 256, 128); box3.addBox(0F, 0F, 0F, 2, 2, 14); box3.setPosition(-17F, 2F, -7F); box30 = new CustomModelRenderer(73, 74, 256, 128); box30.addBox(0F, 0F, 0F, 12, 1, 1); box30.setPosition(7F, 8F, -12F); box31 = new CustomModelRenderer(73, 74, 256, 128); box31.addBox(0F, 0F, 0F, 12, 1, 1); box31.setPosition(-19F, 8F, 11F); box35 = new CustomModelRenderer(189, 12, 256, 128); box35.addBox(0F, 0F, 0F, 8, 7, 0); box35.setPosition(12F, 0F, 5F); box36 = new CustomModelRenderer(134, 92, 256, 128); box36.addBox(0F, 0F, 0F, 14, 1, 3); box36.setPosition(-7F, 2F, 7F); box38 = new CustomModelRenderer(146, 80, 256, 128); box38.addBox(0F, 0F, 0F, 1, 3, 3); box38.setPosition(28F, 7F, 4F); box4 = new CustomModelRenderer(36, 27, 256, 128); box4.addBox(0F, 0F, 0F, 14, 5, 1); box4.setPosition(-23F, 1F, 5F); box40 = new CustomModelRenderer(138, 80, 256, 128); box40.addBox(0F, 0F, 0F, 1, 3, 3); box40.setPosition(-29F, 7F, -7F); box42 = new CustomModelRenderer(138, 80, 256, 128); box42.addBox(0F, 0F, 0F, 1, 3, 3); box42.setPosition(-29F, 7F, 4F); box44 = new CustomModelRenderer(158, 77, 256, 128); box44.addBox(0F, 0F, 0F, 2, 3, 4); box44.setPosition(-30F, 6F, -2F); box46 = new CustomModelRenderer(0, 0, 256, 128); box46.addBox(0F, 0F, 0F, 1, 8, 1); box46.setPosition(-5F, 2F, 8F); box46.rotateAngleX = -6.1086523819801535F; box46.rotateAngleY = -3.141592653589793F; box5 = new CustomModelRenderer(189, 12, 256, 128); box5.addBox(0F, 0F, 0F, 8, 7, 0); box5.setPosition(12F, 0F, -5F); box55 = new CustomModelRenderer(0, 0, 256, 128); box55.addBox(0F, 0F, 0F, 1, 8, 1); box55.setPosition(6F, 2F, 8F); box55.rotateAngleX = -6.1086523819801535F; box55.rotateAngleY = -3.141592653589793F; box6 = new CustomModelRenderer(36, 27, 256, 128); box6.addBox(0F, 0F, 0F, 14, 5, 1); box6.setPosition(9F, 1F, 5F); box63 = new CustomModelRenderer(189, 12, 256, 128); box63.addBox(0F, 0F, 0F, 8, 7, 0); box63.setPosition(-20F, 0F, -5F); box7 = new CustomModelRenderer(0, 0, 256, 128); box7.addBox(0F, 0F, 0F, 1, 8, 1); box7.setPosition(-6F, 2F, -8F); box7.rotateAngleX = -6.1086523819801535F; box8 = new CustomModelRenderer(3, 27, 256, 128); box8.addBox(0F, 0F, 0F, 14, 5, 1); box8.setPosition(9F, 1F, -6F); box9 = new CustomModelRenderer(118, 21, 256, 128); box9.addBox(0F, 0F, 0F, 54, 3, 14); box9.setPosition(-27F, 6F, -7F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { if (ConfigHandler.FLICKERING) { super.render(entity, f, f1, f2, f3, f4, f5); } box.render(f5); box0.render(f5); box1.render(f5); box10.render(f5); box11.render(f5); box12.render(f5); box13.render(f5); box14.render(f5); box15.render(f5); box16.render(f5); box17.render(f5); box18.render(f5); box19.render(f5); box2.render(f5); box20.render(f5); box21.render(f5); box22.render(f5); box23.render(f5); box24.render(f5); box25.render(f5); box26.render(f5); box27.render(f5); box28.render(f5); box29.render(f5); box3.render(f5); box30.render(f5); box31.render(f5); box35.render(f5); box36.render(f5); box38.render(f5); box4.render(f5); box40.render(f5); box42.render(f5); box44.render(f5); box46.render(f5); box5.render(f5); box55.render(f5); box6.render(f5); box63.render(f5); box7.render(f5); box8.render(f5); box9.render(f5); } public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5) {} public CustomModelRenderer box; public CustomModelRenderer box0; public CustomModelRenderer box1; public CustomModelRenderer box10; public CustomModelRenderer box11; public CustomModelRenderer box12; public CustomModelRenderer box13; public CustomModelRenderer box14; public CustomModelRenderer box15; public CustomModelRenderer box16; public CustomModelRenderer box17; public CustomModelRenderer box18; public CustomModelRenderer box19; public CustomModelRenderer box2; public CustomModelRenderer box20; public CustomModelRenderer box21; public CustomModelRenderer box22; public CustomModelRenderer box23; public CustomModelRenderer box24; public CustomModelRenderer box25; public CustomModelRenderer box26; public CustomModelRenderer box27; public CustomModelRenderer box28; public CustomModelRenderer box29; public CustomModelRenderer box3; public CustomModelRenderer box30; public CustomModelRenderer box31; public CustomModelRenderer box35; public CustomModelRenderer box36; public CustomModelRenderer box38; public CustomModelRenderer box4; public CustomModelRenderer box40; public CustomModelRenderer box42; public CustomModelRenderer box44; public CustomModelRenderer box46; public CustomModelRenderer box5; public CustomModelRenderer box55; public CustomModelRenderer box6; public CustomModelRenderer box63; public CustomModelRenderer box7; public CustomModelRenderer box8; public CustomModelRenderer box9; }
lgpl-2.1
Universefei/Terralib-analysis
src/terralib/image_processing/TePDIPrincipalComponentsFusion.hpp
3696
/* TerraLib - a library for developing GIS applications. Copyright 2001, 2002, 2003 INPE and Tecgraf/PUC-Rio. This code is part of the TerraLib library. 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. You should have received a copy of the GNU Lesser General Public License along with this library. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The library provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this library and its documentation. */ #ifndef TEPDIPRINCIPALCOMPONENTSFUSION_HPP #define TEPDIPRINCIPALCOMPONENTSFUSION_HPP #include "TePDIAlgorithm.hpp" /** * @brief This is the class for principal components generation. * @author Felipe Castro da Silva <[email protected]> * @ingroup PDIFusionAlgorithms * * @note The required parameters are: * * @param input_rasters (TePDITypes::TePDIRasterVectorType) - Low resolution rasters. * @param bands (std::vector< int >) - The bands from each low resolution raster. * @param output_raster (TePDITypes::TePDIRasterPtrType) - High resolution fused raster. * @param reference_raster (TePDITypes::TePDIRasterPtrType) - High resolution raster. * @param reference_raster_band (int) - Reference raster band number. * @param resampling_type (TePDIInterpolator::InterpMethod) - * Resampling type. * @param fit_histogram (bool) - Fit the reference histogram to the * low resolution rasters histograms (better collor quality). * * @note The optional parameters are: * * @param output_rasters (TePDITypes::TePDIRasterVectorType) - High resolution fused rasters, each one represents one band/channel, if this parameter is set the output_raster parameter will be ignored. * */ class PDI_DLL TePDIPrincipalComponentsFusion : public TePDIAlgorithm { public : /** * @brief Default Constructor. * */ TePDIPrincipalComponentsFusion(); /** * @brief Default Destructor */ ~TePDIPrincipalComponentsFusion(); /** * @brief Checks if the supplied parameters fits the requirements of each * PDI algorithm implementation. * * @note Error log messages must be generated. No exceptions generated. * * @param parameters The parameters to be checked. * @return true if the parameters are OK. false if not. */ bool CheckParameters( const TePDIParameters& parameters ) const; protected : /** * @brief Decide the direction of the analysis based on the analysis_type parameter. * * @return true if OK. false on error. */ bool RunImplementation(); /** * @brief Reset the internal state to the initial state. * * @param params The new parameters referente at initial state. */ void ResetState( const TePDIParameters& params ); }; /** @example TePDIFusion_test.cpp * Fusion algorithms test. */ #endif //TEPDIPRINCIPALCOMPONENTS_HPP
lgpl-2.1
przemko/prolog-standard-herbrand
src/herbrand.pl
4568
% herbrand.pl % % Generating elements of the Herbrand's universe and the Herbrand's % base. % % Author: Przemyslaw Kobylanski <[email protected]> % % FORMULA ::= '[]' | '[' CLAUSES ']' % CLAUSES ::= CLAUSE | CLAUSE ',' CLAUSES % CLAUSE ::= '[]' | '[' LITERALSE ']' % LITERALS ::= LITERAL | LITERAL ',' LITERALS % LITERAL ::= ATOM | '\+' ATOM % ATOM ::= SYMBOL | SYMBOL '(' TERMS ')' % TERMS ::= TERM | TERM ',' TERMS % TERM ::= VARIABLE | SYMBOL | SYMBOL '(' TERMS ')' % VARIABLE ::= identifier starting with an upper case letter % SYMBOL ::= identifier starting with an lower case letter :- module(herbrand, [ signature/2, herbrand_universe/2, herbrand_base/2 ]). % signature(+Formula, -Signature) if % Signature is a signature for the given Formula (set of clauses) % % Examples: % ?- signature([[nat(a)], [nat(s(X)), \+nat(X)]], S). % S = [pred(nat/1), fun(a/0), fun(s/1)]. % ?- signature([[append([], X, X)], [append([X | L1], L2, [X | L3]), % \+append(L1, L2, L3)]], S). % S = [pred(append/3), fun([]/0), fun('.'/2)]. % signature(Clauses, Signature) :- sig(Clauses, [], S), ( member(fun(_/0), S) -> Signature = S ; Signature = [fun(a/0) | S]). sig([], SIG, SIG). sig([C | L], SIG, SIG2) :- sig2(C, SIG, SIG1), sig(L, SIG1, SIG2). sig2([], SIG, SIG). sig2([A | L], SIG, SIG2) :- sig3(A, SIG, SIG1), sig2(L, SIG1, SIG2). sig3(\+ A, SIG, SIG1) :- !, sig4(A, SIG, SIG1). sig3(A, SIG, SIG1) :- sig4(A, SIG, SIG1). sig4(A, SIG, SIG2) :- A =.. [Pred | Args], length(Args, N), insert_pred(SIG, Pred/N, SIG1), sig5(Args, SIG1, SIG2). sig5([], SIG, SIG). sig5([A | L], SIG, SIG2) :- sig6(A, SIG, SIG1), sig5(L, SIG1, SIG2). sig6(X, SIG, SIG) :- var(X), !. sig6(T, SIG, SIG2) :- T =.. [F | L], length(L, N), insert_fun(SIG, F/N, SIG1), sig5(L, SIG1, SIG2). insert_pred([], P/N, [pred(P/N)]). insert_pred([pred(P/N) | L], P/N, [pred(P/N) | L]) :- !. insert_pred([A | L1], P/N, [A | L2]) :- insert_pred(L1, P/N, L2). insert_fun([], F/N, [fun(F/N)]). insert_fun([fun(F/N) | L], F/N, [fun(F/N) | L]) :- !. insert_fun([A | L1], F/N, [A | L2]) :- insert_fun(L1, F/N, L2). % herbrand_universe(+Signature, -GroundTerm) if % GroundTerm is an element of the Herbrand's Universe for the given % Signature % % Example: % ?- herbrand_universe([fun(a/0), fun(f/1), fun(g/2)], X). % X = a ; % X = f(a) ; % X = g(a, a) ; % X = f(f(a)) ; % X = f(g(a, a)) ; % X = g(a, f(a)) ; % X = g(a, g(a, a)) ; % X = g(f(a), a) ; % X = g(g(a, a), a) ; % X = g(f(a), f(a)) ; % X = g(f(a), g(a, a)) ; % X = g(g(a, a), f(a)) ; % X = g(g(a, a), g(a, a)) ; % ... % herbrand_universe(Signature, GroundTerm) :- member(fun(_/N), Signature), N > 0, !, nat(I), hh(I, Signature, GroundTerm). herbrand_universe(Signature, Constant) :- member(fun(Constant/0), Signature). h(I, SIG, C) :- I >= 0, member(fun(C/0), SIG). h(I, SIG, T) :- I > 0, I1 is I-1, member(fun(F/N), SIG), N > 0, length(L, N), T =.. [F | L], h2(L, I1, SIG). hh(0, SIG, C) :- member(fun(C/0), SIG). hh(I, SIG, T) :- I > 0, I1 is I-1, I2 is I-2, member(fun(F/N), SIG), N > 0, length(L, N), T =.. [F | L], split(L, L1, L2), L1 \= [], hh2(L1, I1, SIG), h2(L2, I2, SIG). h2([], _, _). h2([T | L], I, SIG) :- h(I, SIG, T), h2(L, I, SIG). hh2([], _, _). hh2([T | L], I, SIG) :- hh(I, SIG, T), hh2(L, I, SIG). split([], [], []). split([A | L], L1, [A | L2]) :- split(L, L1, L2). split([A | L], [A | L1], L2) :- split(L, L1, L2). % herbrand_base(+Signature, -GroundAtom) if % GroundAtom is an element of the Herbrand's Base for the given % Signature % % Example: % ?- herbrand_base([pred(p/2), fun(a/0), fun(f/1), fun(g/2)], X). % X = p(a, a) ; % X = p(a, f(a)) ; % X = p(a, g(a, a)) ; % X = p(f(a), a) ; % X = p(g(a, a), a) ; % X = p(f(a), f(a)) ; % X = p(f(a), g(a, a)) ; % X = p(g(a, a), f(a)) ; % X = p(g(a, a), g(a, a)) ; % X = p(a, f(f(a))) ; % X = p(f(a), f(f(a))) ; % X = p(g(a, a), f(f(a))) ; % X = p(a, f(g(a, a))) ; % X = p(f(a), f(g(a, a))) ; % X = p(g(a, a), f(g(a, a))) ; % X = p(a, g(a, f(a))) ; % ... % herbrand_base(Signature, GroundAtom) :- member(fun(_/M), Signature), M > 0, !, nat(I), I1 is I-1, member(pred(P/N), Signature), length(L, N), GroundAtom =.. [P | L], split(L, L1, L2), L1 \= [], hh2(L1, I, Signature), h2(L2, I1, Signature). herbrand_base(Signature, GroundAtom) :- member(pred(P/N), Signature), length(L, N), GroundAtom =.. [P | L], h2(L, 0, Signature). % nat(-N) if % N is a natural number % nat(0). nat(N) :- nat(N1), N is N1+1.
lgpl-2.1
davidlazar/musl
src/math/acoshf.c
1172
/* origin: FreeBSD /usr/src/lib/msun/src/e_acoshf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include "libm.h" static const float ln2 = 6.9314718246e-01; /* 0x3f317218 */ float acoshf(float x) { float t; int32_t hx; GET_FLOAT_WORD(hx, x); if (hx < 0x3f800000) { /* x < 1 */ return (x-x)/(x-x); } else if (hx >= 0x4d800000) { /* x > 2**28 */ if (hx >= 0x7f800000) /* x is inf of NaN */ return x + x; return logf(x) + ln2; /* acosh(huge)=log(2x) */ } else if (hx == 0x3f800000) { return 0.0f; /* acosh(1) = 0 */ } else if (hx > 0x40000000) { /* 2**28 > x > 2 */ t = x*x; return logf(2.0f*x - 1.0f/(x+sqrtf(t-1.0f))); } else { /* 1 < x < 2 */ t = x-1.0f; return log1pf(t + sqrtf(2.0f*t+t*t)); } }
lgpl-2.1
davidlazar/musl
src/complex/ccosl.c
250
#include "libm.h" #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 long double complex ccosl(long double complex z) { return ccos(z); } #else long double complex ccosl(long double complex z) { return ccoshl(cpackl(-cimagl(z), creall(z))); } #endif
lgpl-2.1
ChangSF/BestSects
Assets/Plugins/XLua/Gen/XLuaTestNoGcWrap.cs
13715
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace CSObjectWrap { using Utils = XLua.Utils; public class XLuaTestNoGcWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Utils.BeginObjectRegister(typeof(XLuaTest.NoGc), L, translator, 0, 5, 5, 5); Utils.RegisterFunc(L, Utils.METHOD_IDX, "FloatParamMethod", _m_FloatParamMethod); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Vector3ParamMethod", _m_Vector3ParamMethod); Utils.RegisterFunc(L, Utils.METHOD_IDX, "StructParamMethod", _m_StructParamMethod); Utils.RegisterFunc(L, Utils.METHOD_IDX, "EnumParamMethod", _m_EnumParamMethod); Utils.RegisterFunc(L, Utils.METHOD_IDX, "DecimalParamMethod", _m_DecimalParamMethod); Utils.RegisterFunc(L, Utils.GETTER_IDX, "a1", _g_get_a1); Utils.RegisterFunc(L, Utils.GETTER_IDX, "a2", _g_get_a2); Utils.RegisterFunc(L, Utils.GETTER_IDX, "a3", _g_get_a3); Utils.RegisterFunc(L, Utils.GETTER_IDX, "a4", _g_get_a4); Utils.RegisterFunc(L, Utils.GETTER_IDX, "a5", _g_get_a5); Utils.RegisterFunc(L, Utils.SETTER_IDX, "a1", _s_set_a1); Utils.RegisterFunc(L, Utils.SETTER_IDX, "a2", _s_set_a2); Utils.RegisterFunc(L, Utils.SETTER_IDX, "a3", _s_set_a3); Utils.RegisterFunc(L, Utils.SETTER_IDX, "a4", _s_set_a4); Utils.RegisterFunc(L, Utils.SETTER_IDX, "a5", _s_set_a5); Utils.EndObjectRegister(typeof(XLuaTest.NoGc), L, translator, null, null, null, null, null); Utils.BeginClassRegister(typeof(XLuaTest.NoGc), L, __CreateInstance, 1, 0, 0); Utils.RegisterObject(L, translator, Utils.CLS_IDX, "UnderlyingSystemType", typeof(XLuaTest.NoGc)); Utils.EndClassRegister(typeof(XLuaTest.NoGc), L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { if(LuaAPI.lua_gettop(L) == 1) { XLuaTest.NoGc __cl_gen_ret = new XLuaTest.NoGc(); translator.Push(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLuaTest.NoGc constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_FloatParamMethod(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); try { { float p = (float)LuaAPI.lua_tonumber(L, 2); float __cl_gen_ret = __cl_gen_to_be_invoked.FloatParamMethod( p ); LuaAPI.lua_pushnumber(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Vector3ParamMethod(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); try { { UnityEngine.Vector3 p;translator.Get(L, 2, out p); UnityEngine.Vector3 __cl_gen_ret = __cl_gen_to_be_invoked.Vector3ParamMethod( p ); translator.PushUnityEngineVector3(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StructParamMethod(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); try { { XLuaTest.MyStruct p;translator.Get(L, 2, out p); XLuaTest.MyStruct __cl_gen_ret = __cl_gen_to_be_invoked.StructParamMethod( p ); translator.PushXLuaTestMyStruct(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_EnumParamMethod(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); try { { XLuaTest.MyEnum p;translator.Get(L, 2, out p); XLuaTest.MyEnum __cl_gen_ret = __cl_gen_to_be_invoked.EnumParamMethod( p ); translator.PushXLuaTestMyEnum(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_DecimalParamMethod(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); try { { decimal p;translator.Get(L, 2, out p); decimal __cl_gen_ret = __cl_gen_to_be_invoked.DecimalParamMethod( p ); translator.PushDecimal(L, __cl_gen_ret); return 1; } } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_a1(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); translator.Push(L, __cl_gen_to_be_invoked.a1); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_a2(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); translator.Push(L, __cl_gen_to_be_invoked.a2); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_a3(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); translator.Push(L, __cl_gen_to_be_invoked.a3); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_a4(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); translator.Push(L, __cl_gen_to_be_invoked.a4); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_a5(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); translator.Push(L, __cl_gen_to_be_invoked.a5); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_a1(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); __cl_gen_to_be_invoked.a1 = (double[])translator.GetObject(L, 2, typeof(double[])); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_a2(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); __cl_gen_to_be_invoked.a2 = (UnityEngine.Vector3[])translator.GetObject(L, 2, typeof(UnityEngine.Vector3[])); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_a3(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); __cl_gen_to_be_invoked.a3 = (XLuaTest.MyStruct[])translator.GetObject(L, 2, typeof(XLuaTest.MyStruct[])); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_a4(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); __cl_gen_to_be_invoked.a4 = (XLuaTest.MyEnum[])translator.GetObject(L, 2, typeof(XLuaTest.MyEnum[])); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_a5(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); try { XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1); __cl_gen_to_be_invoked.a5 = (decimal[])translator.GetObject(L, 2, typeof(decimal[])); } catch(System.Exception __gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); } return 0; } } }
lgpl-3.0
cerinunn/pdart
extra_plots/plot_seismograms.py
10680
#!/usr/bin/env python from __future__ import print_function import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from datetime import datetime, timedelta from obspy.core.utcdatetime import UTCDateTime from matplotlib import gridspec from pdart.view import stream_from_directory from obspy import read_inventory import os from obspy.core import read # start_time = UTCDateTime('1971-02-07T00:45:00') from pdart.diffusion.view_single_seismogram import remove_response # update 25-08-21 def single_seismogram(title): # 1969-11-20T22:17:17.7 # onset is 42.4 s Lognonne 2003 onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') # +42.4 # onset = UTCDateTime('1969-11-20T22:17:700000Z') start_time = onset - timedelta(minutes=2) stations = ['S12'] channels = ['MHZ'] end_time = start_time + timedelta(minutes=15) stream = stream_from_directory( top_level_dir='/Users/cnunn/lunar_data/PDART_CONTINUOUS_MAIN_TAPES', start_time=start_time, stations=stations, channels=channels, end_time=end_time) ######## fig = plt.figure(figsize=(15, 4)) gs = gridspec.GridSpec(5, 1, hspace=0.001) ax0 = plt.subplot(gs[0]) trace_MHZ = stream.select(channel='MHZ')[0] ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k') ax0.set_xlim(-2*60, 15*60) ax0.set_xticks(np.arange(0,15*60,6*50)) ax0.set_xticks(np.arange(-180,15*60,60), minor=True) ax0.set_title(title, fontsize=20) ax0.set_yticks(np.arange(480, 560, 20)) # ax0.set_yticks(np.arange(460,580,20), minor=True) ax0.set_ylim(510-50, 510+50) ax0.set_ylabel('DU', fontsize=14) ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"), fontsize=13, horizontalalignment="left", verticalalignment="top", xycoords="axes fraction") xticklabels = (ax0.get_xticklabels()) plt.setp(xticklabels, visible=False) ax0.tick_params(length=6, width=1, which='minor') ax0.yaxis.set_label_coords(-0.04, 0.5) ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16, xycoords="axes fraction", horizontalalignment='left', verticalalignment='center') plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.12) plt.savefig('Apollo12_LM_impact_XXXX.png') plt.show() # def single_seismogram_remove_response_short(title): # # # peaked mode # inv_name = "/Users/cnunn/lunar_data/IRIS_dataless_seed/XA.1969-1977.xml" # # onset is 42.4 s Lognonne 2003 # onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') # start_time = onset - timedelta(minutes=2) # # XXXX # station = 'S12' # channel = 'MHZ' # pre_filt = [0.1, 0.3,0.7,1] # # end_time = UTCDateTime('1971:02:07T02:35.25') # # end_time = onset + timedelta(minutes=60) # # # 1969-11-20T22:17:17.7 # # stream = remove_response_from_seismogram(inv_name=inv_name, # start_time=start_time, # station=station, # channel=channel, # pre_filt=pre_filt, # water_level=None, # end_time=end_time, # plot=False) # # ######## # # fig = plt.figure(figsize=(15, 4)) # gs = gridspec.GridSpec(1, 1, hspace=0.001) # # ax0 = plt.subplot(gs[0]) # # trace_MHZ = stream.select(channel='MHZ')[0] # ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k') # ax0.set_xlim(-2*60, 5*60) # # print('short') # ax0.set_xticks(np.arange(0,6*60,6*50),minor=False) # ax0.set_xticks(np.arange(-180,6*60,60), minor=True) # ax0.set_title(title, fontsize=20) # # # ax0.set_yticks(np.arange(480, 560, 20)) # # ax0.set_yticks(np.arange(460,580,20), minor=True) # ax0.set_ylim(-1.1e-8, 1.01e-8) # ax0.set_ylabel('Displacement [m]', fontsize=14) # ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"), # fontsize=13, horizontalalignment="left", verticalalignment="top", # xycoords="axes fraction") # # # xticklabels = (ax0.get_xticklabels()) # # plt.setp(xticklabels, visible=False) # # ax0.tick_params(length=3, width=1, which='minor') # ax0.tick_params(length=6, width=1, which='major') # # ax0.yaxis.set_label_coords(-0.04, 0.5) # # ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16, # xycoords="axes fraction", horizontalalignment='left', # verticalalignment='center') # # ax0.set_xlabel('Time after impact [s]', fontsize=14) # ax0.yaxis.set_label_coords(-0.04, 0.5) # # plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.12) # plt.savefig('Apollo12_LM_impact_XXXX.png') # plt.show() def single_seismogram_remove_response(title,onset,pick=None): # peaked mode inv_name = "/Users/cnunn/lunar_data/IRIS_dataless_seed/XA.1969-1977.xml" onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') start_time = onset - timedelta(minutes=2) # XXXX station = 'S12' channel = 'MHZ' pre_filt = [0.1, 0.3,0.7,1] # end_time = UTCDateTime('1971:02:07T02:35.25') end_time = onset + timedelta(minutes=60) # 1969-11-20T22:17:17.7 # reset the timing # make a correction # find actual time of onset # print(onset.time) stream = remove_response_from_seismogram(inv_name=inv_name, start_time=start_time, station=station, channel=channel, pre_filt=pre_filt, water_level=None, end_time=end_time, plot=False) ######## fig = plt.figure(figsize=(15, 4)) gs = gridspec.GridSpec(1, 1, hspace=0.001) ax0 = plt.subplot(gs[0]) trace_MHZ = stream.select(channel='MHZ')[0] ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k') ax0.set_xlim(-2*60, 60*60) ax0.set_xticks(np.arange(0,61*60,6*50),minor=False) ax0.set_xticks(np.arange(-180,61*60,60), minor=True) # pick_markP = pick - onset # plt.gca().axvline(x=pick_markP, # color='r', linewidth=2) ax0.set_title(title, fontsize=20) # ax0.set_yticks(np.arange(480, 560, 20)) # ax0.set_yticks(np.arange(460,580,20), minor=True) ax0.set_ylim(-1.1e-8, 1.01e-8) ax0.set_ylabel('Displacement [m]', fontsize=14) ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"), fontsize=13, horizontalalignment="left", verticalalignment="top", xycoords="axes fraction") # xticklabels = (ax0.get_xticklabels()) # plt.setp(xticklabels, visible=False) ax0.tick_params(length=3, width=1, which='minor') ax0.tick_params(length=6, width=1, which='major') ax0.yaxis.set_label_coords(-0.04, 0.5) ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16, xycoords="axes fraction", horizontalalignment='left', verticalalignment='center') ax0.set_xlabel('Time after impact [s]', fontsize=14) ax0.yaxis.set_label_coords(-0.04, 0.5) ax0.plot(times_to_seconds(trace_MHZ.times()), times_to_seconds(trace_MHZ.data-trace_MHZ.stats.starttime.timestamp), color='k') plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.13) plt.savefig('../extra_plots_output/Apollo12_LM_impact_XXXX.png') plt.show() # def times_to_minutes(times_in_seconds): # return ((times_in_seconds / 60) - 2) # copied from /Users/cnunn/python_packages/pdart/extra_plots/view_response.py def remove_response_from_seismogram( inv_name, start_time, station, channel, pre_filt, end_time=None, outfile=None, output='DISP', water_level=None, plot=True): # read the response file inv = read_inventory(inv_name) if end_time is None: time_interval = timedelta(hours=3) end_time = start_time + time_interval # xa.s12..att.1969.324.0.mseed filename = '%s.%s.*.%s.%s.%03d.0.mseed' % ('xa',station.lower(), channel.lower(), str(start_time.year), start_time.julday) filename = os.path.join('/Users/cnunn/lunar_data/PDART_CONTINUOUS_MAIN_TAPES',station.lower(),str(start_time.year),str(start_time.julday),filename) stream = read(filename) stream = stream.select(channel=channel) stream.trim(starttime=start_time, endtime=end_time) # remove location (ground station) for tr in stream: tr.stats.location = '' # detrend stream.detrend('linear') # taper the edges # if there are gaps in the seismogram - EVERY short trace will be tapered # this is required to remove the response later # stream.taper(max_percentage=0.05, type='cosine') # experiment with tapering? not tapering preserves the overall shape better # but it may required # merge the streams stream.merge() if stream.count() > 1: print('Too many streams - exiting') # find the gaps in the trace if isinstance(stream[0].data,np.ma.MaskedArray): mask = np.ma.getmask(stream[0].data) else: mask = None # split the stream, then refill it with zeros on the gaps stream = stream.split() stream = stream.merge(fill_value=0) # for i, n in enumerate(stream[0].times()): # # print(n) # stream[0].data[i]=np.sin(2*np.pi*(1/25)*n) stream.attach_response(inv) # print('here') # zero_mean=False - because the trace can be asymmetric - remove the mean ourselves # do not taper here - it doesn't work well with the masked arrays - often required # when there are gaps - if necessary taper first # water level - this probably doesn't have much impact - because we are pre filtering # stream.remove_response(pre_filt=pre_filt,output="DISP",water_level=30,zero_mean=False,taper=False,plot=True,fig=outfile) for tr in stream: remove_response(tr, pre_filt=pre_filt,output=output,water_level=water_level,zero_mean=False,taper=False,plot=plot,fig=outfile) for tr in stream: tr.stats.location = 'changed' if mask is not None: stream[0].data = np.ma.array(stream[0].data, mask = mask) print(stream) return stream def times_to_seconds(times_in_seconds): return (times_in_seconds - 120) if __name__ == "__main__": # single_seismogram(title='Impact of Apollo 12 Lunar Ascent Module') onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') # <pick publicID="smi:nunn19/pick/00001/lognonne03/S12/P"> pick = UTCDateTime('1969-11-20T22:17:42.400000Z') arrival_time = pick - onset print(arrival_time) single_seismogram_remove_response(title='Impact of Apollo 12 Lunar Ascent Module',onset=onset,pick=pick) # single_seismogram_remove_response_short(title='Impact of Apollo 12 Lunar Ascent Module')
lgpl-3.0
SonarSource/sonarqube
server/sonar-main/src/main/java/org/sonar/application/es/EsConnectorImpl.java
4727
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import com.google.common.net.HostAndPort; import java.io.IOException; import java.util.Arrays; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.client.BasicCredentialsProvider; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.elasticsearch.core.TimeValue.timeValueSeconds; public class EsConnectorImpl implements EsConnector { private static final String ES_USERNAME = "elastic"; private static final Logger LOG = LoggerFactory.getLogger(EsConnectorImpl.class); private final AtomicReference<RestHighLevelClient> restClient = new AtomicReference<>(null); private final Set<HostAndPort> hostAndPorts; private final String searchPassword; public EsConnectorImpl(Set<HostAndPort> hostAndPorts, @Nullable String searchPassword) { this.hostAndPorts = hostAndPorts; this.searchPassword = searchPassword; } @Override public Optional<ClusterHealthStatus> getClusterHealthStatus() { try { ClusterHealthResponse healthResponse = getRestHighLevelClient().cluster() .health(new ClusterHealthRequest().waitForYellowStatus().timeout(timeValueSeconds(30)), RequestOptions.DEFAULT); return Optional.of(healthResponse.getStatus()); } catch (IOException e) { LOG.trace("Failed to check health status ", e); return Optional.empty(); } } @Override public void stop() { RestHighLevelClient restHighLevelClient = restClient.get(); if (restHighLevelClient != null) { try { restHighLevelClient.close(); } catch (IOException e) { LOG.warn("Error occurred while closing Rest Client", e); } } } private RestHighLevelClient getRestHighLevelClient() { RestHighLevelClient res = this.restClient.get(); if (res != null) { return res; } RestHighLevelClient restHighLevelClient = buildRestHighLevelClient(); this.restClient.set(restHighLevelClient); return restHighLevelClient; } private RestHighLevelClient buildRestHighLevelClient() { HttpHost[] httpHosts = hostAndPorts.stream() .map(hostAndPort -> new HttpHost(hostAndPort.getHost(), hostAndPort.getPortOrDefault(9001))) .toArray(HttpHost[]::new); if (LOG.isDebugEnabled()) { String addresses = Arrays.stream(httpHosts) .map(t -> t.getHostName() + ":" + t.getPort()) .collect(Collectors.joining(", ")); LOG.debug("Connected to Elasticsearch node: [{}]", addresses); } RestClientBuilder builder = RestClient.builder(httpHosts) .setHttpClientConfigCallback(httpClientBuilder -> { if (searchPassword != null) { BasicCredentialsProvider provider = getBasicCredentialsProvider(searchPassword); httpClientBuilder.setDefaultCredentialsProvider(provider); } return httpClientBuilder; }); return new RestHighLevelClient(builder); } private static BasicCredentialsProvider getBasicCredentialsProvider(String searchPassword) { BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ES_USERNAME, searchPassword)); return provider; } }
lgpl-3.0
cismet/cids-custom-wrrl-db-mv
src/main/java/de/cismet/cids/custom/wrrl_db_mv/util/gup/VermeidungsgruppeRWBandMember.java
6828
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.custom.wrrl_db_mv.util.gup; import Sirius.navigator.tools.CacheException; import Sirius.navigator.tools.MetaObjectCache; import Sirius.server.middleware.types.MetaClass; import Sirius.server.middleware.types.MetaObject; import org.jdesktop.swingx.painter.CompoundPainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.RectanglePainter; import java.awt.Color; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import javax.swing.JMenuItem; import de.cismet.cids.custom.wrrl_db_mv.commons.WRRLUtil; import de.cismet.cids.custom.wrrl_db_mv.util.CidsBeanSupport; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.navigator.utils.ClassCacheMultiple; /** * DOCUMENT ME! * * @author therter * @version $Revision$, $Date$ */ public class VermeidungsgruppeRWBandMember extends LineBandMember { //~ Static fields/initializers --------------------------------------------- private static final MetaClass VERMEIDUNGSGRUPPE = ClassCacheMultiple.getMetaClass( WRRLUtil.DOMAIN_NAME, "VERMEIDUNGSGRUPPE"); //~ Instance fields -------------------------------------------------------- private JMenuItem[] menuItems; //~ Constructors ----------------------------------------------------------- /** * Creates new form MassnahmenBandMember. * * @param parent DOCUMENT ME! */ public VermeidungsgruppeRWBandMember(final VermeidungsgruppeRWBand parent) { super(parent); lineFieldName = "linie"; } /** * Creates new form MassnahmenBandMember. * * @param parent DOCUMENT ME! * @param readOnly DOCUMENT ME! */ public VermeidungsgruppeRWBandMember(final VermeidungsgruppeRWBand parent, final boolean readOnly) { super(parent, readOnly); lineFieldName = "linie"; } //~ Methods ---------------------------------------------------------------- @Override public void setCidsBean(final CidsBean cidsBean) { super.setCidsBean(cidsBean); setToolTipText(bean.getProperty("vermeidungsgruppe.name") + ""); } /** * DOCUMENT ME! */ @Override protected void determineBackgroundColour() { if ((bean.getProperty("vermeidungsgruppe") == null) || (bean.getProperty("vermeidungsgruppe.color") == null)) { setDefaultBackground(); return; } final String color = (String)bean.getProperty("vermeidungsgruppe.color"); if (color != null) { try { setBackgroundPainter(new MattePainter(Color.decode(color))); } catch (NumberFormatException e) { LOG.error("Error while parsing the color.", e); setDefaultBackground(); } } unselectedBackgroundPainter = getBackgroundPainter(); selectedBackgroundPainter = new CompoundPainter( unselectedBackgroundPainter, new RectanglePainter( 3, 3, 3, 3, 3, 3, true, new Color(100, 100, 100, 100), 2f, new Color(50, 50, 50, 100))); setBackgroundPainter(unselectedBackgroundPainter); } /** * DOCUMENT ME! * * @param id DOCUMENT ME! */ private void setVermeidungsgruppe(final String id) { try { final String query = "select " + VERMEIDUNGSGRUPPE.getID() + "," + VERMEIDUNGSGRUPPE.getPrimaryKey() + " from " + VERMEIDUNGSGRUPPE.getTableName(); // NOI18N final MetaObject[] metaObjects = MetaObjectCache.getInstance() .getMetaObjectsByQuery(query, WRRLUtil.DOMAIN_NAME); CidsBean b = null; if (metaObjects != null) { for (final MetaObject tmp : metaObjects) { if (tmp.getBean().getProperty("id").toString().equals(id)) { b = tmp.getBean(); break; } } } bean.setProperty("vermeidungsgruppe", b); } catch (Exception e) { LOG.error("Error while setting property massnahme.", e); } } /** * DOCUMENT ME! */ @Override protected void configurePopupMenu() { try { final String query = "select " + VERMEIDUNGSGRUPPE.getID() + "," + VERMEIDUNGSGRUPPE.getPrimaryKey() + " from " + VERMEIDUNGSGRUPPE.getTableName(); // NOI18N final MetaObject[] metaObjects = MetaObjectCache.getInstance() .getMetaObjectsByQuery(query, WRRLUtil.DOMAIN_NAME); menuItems = new JMenuItem[metaObjects.length]; for (int i = 0; i < metaObjects.length; ++i) { menuItems[i] = new JMenuItem(metaObjects[i].getBean().toString()); menuItems[i].addActionListener(this); menuItems[i].setActionCommand(String.valueOf(metaObjects[i].getID())); popup.add(menuItems[i]); } } catch (CacheException e) { LOG.error("Cache Exception", e); } popup.addSeparator(); super.configurePopupMenu(); } @Override public void actionPerformed(final ActionEvent e) { boolean found = false; for (final JMenuItem tmp : menuItems) { if (e.getSource() == tmp) { found = true; setVermeidungsgruppe(tmp.getActionCommand()); fireBandMemberChanged(false); break; } } if (!found) { super.actionPerformed(e); } newMode = false; } @Override public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals("vermeidungsgruppe")) { determineBackgroundColour(); setSelected(isSelected); setToolTipText(bean.getProperty("vermeidungsgruppe.name") + ""); } else { super.propertyChange(evt); } } /** * DOCUMENT ME! * * @param bean DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ @Override protected CidsBean cloneBean(final CidsBean bean) throws Exception { return CidsBeanSupport.cloneCidsBean(bean, false); } }
lgpl-3.0
SirmaITT/conservation-space-1.7.0
docker/sep-ui/src/idoc/system-tabs/mailbox/services/personal-mailbox-info-observer/personal-mailbox-info-observer.js
1622
import {Inject, Injectable} from 'app/app'; import {BootstrapService} from 'services/bootstrap-service'; import {UserService} from 'security/user-service'; import {Eventbus} from 'services/eventbus/eventbus'; import {PersonalMailboxUpdatedEvent} from 'idoc/system-tabs/mailbox/events/personal-mailbox-updated-event'; import {MailboxInfoService} from 'services/rest/mailbox-info-service'; import {PollingUtils} from 'common/polling-utils'; import {Configuration} from 'common/application-config'; @Injectable() @Inject(Eventbus, MailboxInfoService, UserService, PollingUtils, Configuration) export class PersonalMailboxInfoObserver extends BootstrapService { constructor(eventbus, mailboxInfoService, userService, pollingUtils, configuration) { super(); this.eventbus = eventbus; this.mailboxInfoService = mailboxInfoService; this.userService = userService; this.pollingUtils = pollingUtils; this.pollingInterval = configuration.get(Configuration.MAILBOX_STATUS_POLL_INTERVAL); } initialize() { this.userService.getCurrentUser().then((response) => { if (response.mailboxSupportable) { this.pollingUtils.pollInfinite('personal_mailbox_unread_messages_count', this.handleMessagesStatusUpdate.bind(this), this.pollingInterval, false); } }); } handleMessagesStatusUpdate() { this.userService.getCurrentUser().then((response) => { return this.mailboxInfoService.getUnreadMessagesCount(response.emailAddress, {skipInterceptor: true}); }).then((response) => { this.eventbus.publish(new PersonalMailboxUpdatedEvent(response.data)); }); } }
lgpl-3.0
luisgoncalves/xades4j
src/main/java/xades4j/production/SignedDataObjectsProcessor.java
10850
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j 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 any later version. * * XAdES4j 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 XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.production; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.xml.security.signature.*; import org.apache.xml.security.transforms.Transforms; import org.apache.xml.security.utils.resolver.ResourceResolverSpi; import org.w3c.dom.Document; import xades4j.UnsupportedAlgorithmException; import xades4j.XAdES4jXMLSigException; import xades4j.algorithms.Algorithm; import xades4j.properties.DataObjectDesc; import xades4j.utils.ResolverAnonymous; import xades4j.utils.TransformUtils; import xades4j.xml.marshalling.algorithms.AlgorithmsParametersMarshallingProvider; import javax.inject.Inject; /** * Helper class that processes a set of data object descriptions. * * @author Luís */ final class SignedDataObjectsProcessor { static final class Result { final Map<DataObjectDesc, Reference> referenceMappings; final Set<Manifest> manifests; public Result(Map<DataObjectDesc, Reference> referenceMappings, Set<Manifest> manifests) { this.referenceMappings = Collections.unmodifiableMap(referenceMappings); this.manifests = Collections.unmodifiableSet(manifests); } } private final SignatureAlgorithms signatureAlgorithms; private final AlgorithmsParametersMarshallingProvider algorithmsParametersMarshaller; @Inject SignedDataObjectsProcessor(SignatureAlgorithms signatureAlgorithms, AlgorithmsParametersMarshallingProvider algorithmsParametersMarshaller) { this.signatureAlgorithms = signatureAlgorithms; this.algorithmsParametersMarshaller = algorithmsParametersMarshaller; } /** * Processes the signed data objects and adds the corresponding {@code Reference}s * and {@code Object}s to the signature. This method must be invoked before * adding any other {@code Reference}s to the signature. * * @return result with reference mappings resulting from the data object descriptions and manifests to be digested * @throws UnsupportedAlgorithmException if the reference digest algorithm is not supported * @throws IllegalStateException if the signature already contains {@code Reference}s * @throws XAdES4jXMLSigException if a Manifest cannot be digested */ SignedDataObjectsProcessor.Result process( SignedDataObjects signedDataObjects, XMLSignature xmlSignature) throws UnsupportedAlgorithmException, XAdES4jXMLSigException { if (xmlSignature.getSignedInfo().getLength() != 0) { throw new IllegalStateException("XMLSignature already contains references"); } return process( signedDataObjects.getDataObjectsDescs(), xmlSignature.getSignedInfo(), xmlSignature.getId(), signedDataObjects.getResourceResolvers(), xmlSignature, false); } private SignedDataObjectsProcessor.Result process( Collection<? extends DataObjectDesc> dataObjects, Manifest container, String idPrefix, List<ResourceResolverSpi> resourceResolvers, XMLSignature xmlSignature, boolean hasNullURIReference) throws UnsupportedAlgorithmException, XAdES4jXMLSigException { Map<DataObjectDesc, Reference> referenceMappings = new IdentityHashMap<DataObjectDesc, Reference>(dataObjects.size()); Set<Manifest> manifests = new HashSet<Manifest>(); for (ResourceResolverSpi resolver : resourceResolvers) { container.addResourceResolver(resolver); } String digestMethodUri = this.signatureAlgorithms.getDigestAlgorithmForDataObjectReferences(); /**/ try { for (DataObjectDesc dataObjDesc : dataObjects) { String refUri, refType; int index = container.getLength(); if (dataObjDesc instanceof DataObjectReference) { // If the data object info is a DataObjectReference, the Reference uri // and type are the ones specified on the object. DataObjectReference dataObjRef = (DataObjectReference) dataObjDesc; refUri = dataObjRef.getUri(); refType = dataObjRef.getType(); } else if (dataObjDesc instanceof EnvelopedXmlObject) { // If the data object info is a EnvelopedXmlObject we need to create a ds:Object to embed it. // The Reference uri will refer the new ds:Object's id. EnvelopedXmlObject envXmlObj = (EnvelopedXmlObject) dataObjDesc; String xmlObjId = String.format("%s-object%d", idPrefix, index); ObjectContainer xmlObj = new ObjectContainer(container.getDocument()); xmlObj.setId(xmlObjId); xmlObj.appendChild(envXmlObj.getContent()); xmlObj.setMimeType(envXmlObj.getMimeType()); xmlObj.setEncoding(envXmlObj.getEncoding()); xmlSignature.appendObject(xmlObj); refUri = '#' + xmlObjId; refType = Reference.OBJECT_URI; } else if (dataObjDesc instanceof AnonymousDataObjectReference) { if (hasNullURIReference) { // This shouldn't happen because SignedDataObjects does the validation. throw new IllegalStateException("Multiple AnonymousDataObjectReference detected"); } hasNullURIReference = true; refUri = refType = null; AnonymousDataObjectReference anonymousRef = (AnonymousDataObjectReference) dataObjDesc; container.addResourceResolver(new ResolverAnonymous(anonymousRef.getDataStream())); } else if (dataObjDesc instanceof EnvelopedManifest) { // If the data object info is a EnvelopedManifest we need to create a ds:Manifest and a ds:Object // to embed it. The Reference uri will refer the manifest's id. EnvelopedManifest envManifest = (EnvelopedManifest) dataObjDesc; String xmlManifestId = String.format("%s-manifest%d", idPrefix, index); Manifest xmlManifest = new Manifest(container.getDocument()); xmlManifest.setId(xmlManifestId); SignedDataObjectsProcessor.Result manifestResult = process( envManifest.getDataObjects(), xmlManifest, xmlManifestId, resourceResolvers, xmlSignature, hasNullURIReference); ObjectContainer xmlObj = new ObjectContainer(container.getDocument()); xmlObj.appendChild(xmlManifest.getElement()); xmlSignature.appendObject(xmlObj); manifests.add(xmlManifest); manifests.addAll(manifestResult.manifests); refUri = '#' + xmlManifestId; refType = Reference.MANIFEST_URI; } else { throw new ClassCastException("Unsupported SignedDataObjectDesc. Must be one of DataObjectReference, EnvelopedXmlObject, EnvelopedManifest and AnonymousDataObjectReference"); } Transforms transforms = processTransforms(dataObjDesc, container.getDocument()); // Add the Reference. References need an ID because data object properties may refer them. container.addDocument( xmlSignature.getBaseURI(), refUri, transforms, digestMethodUri, String.format("%s-ref%d", idPrefix, index), // id refType); // SignedDataObjects and EnvelopedManifest don't allow repeated instances, so there's no // need to check for duplicate entries on the map. Reference ref = container.item(index); referenceMappings.put(dataObjDesc, ref); } } catch (XMLSignatureException ex) { // -> xmlSignature.appendObject(xmlObj): not thrown when signing. // -> xmlSignature.addDocument(...): appears to be thrown when the digest // algorithm is not supported. throw new UnsupportedAlgorithmException( "Digest algorithm not supported in the XML Signature provider", digestMethodUri, ex); } catch (org.apache.xml.security.exceptions.XMLSecurityException ex) { // -> xmlSignature.getSignedInfo().item(...): shouldn't be thrown // when signing. throw new IllegalStateException(ex); } return new Result(referenceMappings, manifests); } private Transforms processTransforms( DataObjectDesc dataObjDesc, Document document) throws UnsupportedAlgorithmException { Collection<Algorithm> transforms = dataObjDesc.getTransforms(); if (transforms.isEmpty()) { return null; } return TransformUtils.createTransforms(document, this.algorithmsParametersMarshaller, transforms); } }
lgpl-3.0
trigrass2/STM32491_CPLR
Firmware/Common/bsp/qpc_lwip_port/netif/eth_driver.c
19240
/** * @file eth_driver.c * @brief This file contains QPC LWIP Ethernet layer for an STM32F4xx board * with a Texas Instruments DP83848 Ethernet PHY * This file is derived from the ``ethernetif.c'' skeleton Ethernet network * interface driver for lwIP. * * @date 08/25/2014 * @author Harry Rostovtsev * @email [email protected] * Copyright (C) 2014 Datacard. All rights reserved. * * @addtogroup groupLWIP_QPC_Eth * @{ */ /* Includes ------------------------------------------------------------------*/ #include "netif/eth_driver.h" #include "stm32f4x7_eth.h" #include "stm32f4x7_eth_bsp.h" #include "project_includes.h" /* Compile-time called macros ------------------------------------------------*/ DBG_DEFINE_THIS_MODULE( DC3_DBG_MODL_ETH ); /* For debug system to ID this module */ /** * @brief Sanity Check: This interface driver will NOT work if the following * defines are incorrect. */ #if (PBUF_LINK_HLEN != 16) #error "PBUF_LINK_HLEN must be 16 for this interface driver!" #endif #if (ETH_PAD_SIZE != 2) #error "ETH_PAD_SIZE must be 2 for this interface driver!" #endif /* Private typedefs ----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private variables and Local objects ---------------------------------------*/ /**< Ethernet Rx & Tx DMA Descriptors */ extern ETH_DMADESCTypeDef DMARxDscrTab[ETH_RXBUFNB], DMATxDscrTab[ETH_TXBUFNB]; /**< Ethernet Receive buffers */ extern uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE]; /**< Ethernet Transmit buffers */ extern uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE]; /**< Global pointers to track current transmit and receive descriptors */ extern ETH_DMADESCTypeDef *DMATxDescToSet; extern ETH_DMADESCTypeDef *DMARxDescToGet; /**< Global pointer for last received frame infos */ extern ETH_DMA_Rx_Frame_infos *DMA_RX_FRAME_infos; /****************************************************************************/ /* Static variables */ /****************************************************************************/ /**< LWIP Pbuf constructor */ static void PbufQueue_ctor(PbufQueue *me); /**< LWIP Pbuf queue put */ static uint8_t PbufQueue_put(PbufQueue *me, struct pbuf *p); /**< LWIP Pbuf queue get */ static struct pbuf* PbufQueue_get(PbufQueue *me); static struct netif l_netif; /**< the single network interface */ static QActive* l_active; /**< active object associated with this driver */ static PbufQueue l_txq; /**< queue of pbufs for transmission */ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ struct netif *eth_driver_init( QActive *active, u8_t macaddr[NETIF_MAX_HWADDR_LEN] ) { struct ip_addr ipaddr; struct ip_addr netmask; struct ip_addr gw; lwip_init(); /* initialize the lwIP stack */ /* set MAC address in the network interface... */ l_netif.hwaddr_len = NETIF_MAX_HWADDR_LEN; MEMCPY(&l_netif.hwaddr[0], macaddr, NETIF_MAX_HWADDR_LEN); l_active = active; /*save the active object associated with this driver */ #if LWIP_NETIF_HOSTNAME l_netif.hostname = "CB"; /* initialize interface hostname */ #endif /* * Initialize the snmp variables and counters inside the struct netif. * The last argument should be replaced with your link speed, in units * of bits per second. */ NETIF_INIT_SNMP(&l_netif, snmp_ifType_ethernet_csmacd, 100000000); /* We directly use etharp_output() here to save a function call. * You can instead declare your own function an call etharp_output() * from it if you have to do some checks before sending (e.g. if link * is available...) */ l_netif.output = &etharp_output; l_netif.linkoutput = &ethernetif_output; PbufQueue_ctor(&l_txq); /* initialize the TX pbuf queue */ #if (LWIP_DHCP == 0) && (LWIP_AUTOIP == 0) /* No mechanism of obtaining IP address specified, use static IP: */ IP4_ADDR(&ipaddr, STATIC_IPADDR0, STATIC_IPADDR1, STATIC_IPADDR2, STATIC_IPADDR3); IP4_ADDR(&netmask, STATIC_NET_MASK0, STATIC_NET_MASK1, STATIC_NET_MASK2, STATIC_NET_MASK3); IP4_ADDR(&gw, STATIC_GW_IPADDR0, STATIC_GW_IPADDR1, STATIC_GW_IPADDR2, STATIC_GW_IPADDR3); #else /* either DHCP or AUTOIP are configured, start with zero IP addresses: */ IP4_ADDR(&ipaddr, 0, 0, 0, 0); IP4_ADDR(&netmask, 0, 0, 0, 0); IP4_ADDR(&gw, 0, 0, 0, 0); #endif /* add and configure the Ethernet interface with default settings */ netif_add(&l_netif, &ipaddr, &netmask, &gw, /* configured IP addresses */ active, /* use this active object as the state */ &ethernetif_init, /* Ethernet interface initialization */ &ip_input); /* standard IP input processing */ netif_set_default(&l_netif); netif_set_up(&l_netif); /* bring the interface up */ #if (LWIP_DHCP != 0) dhcp_start(&l_netif); /* start DHCP if configured in lwipopts.h */ /* NOTE: If LWIP_AUTOIP is configured in lwipopts.h and * LWIP_DHCP_AUTOIP_COOP is set as well, the DHCP process will start * AutoIP after DHCP fails for 59 seconds. */ #elif (LWIP_AUTOIP != 0) autoip_start(&l_netif); /* start AutoIP if configured in lwipopts.h */ #endif #if LINK_STATS ETH_DMAITConfig(ETH_DMA_IT_TU | ETH_DMA_IT_TU, ENABLE); #endif QS_OBJ_DICTIONARY(&l_Ethernet_IRQHandler); return(&l_netif); } /*..........................................................................*/ void eth_driver_read(void) { /* This is a fix for the slowdown issue due to a buildup of packets in the * DMA buffer. Normally, only one packet is read at a time and the rest sit * there eliminating useful buffers, eventually leading to a slowdown. Yeah, * GOTOs are bad. Get over it. */ GET_NEXT_FRAGMENT:; struct pbuf *p = low_level_receive(); if (p != NULL) { /* new packet received into the pbuf? */ if (ethernet_input(p, &l_netif) != ERR_OK) { /* pbuf not handled? */ LWIP_DEBUGF(NETIF_DEBUG, ("eth_driver_input: input error\n")); pbuf_free(p); /* free the pbuf */ p = NULL; } else { goto GET_NEXT_FRAGMENT; // See note at the beginning of function. } /* try to output a packet if TX fifo is empty and pbuf is available */ if( ETH_GetDMAFlagStatus(ETH_DMA_FLAG_TBU) == RESET) { p = PbufQueue_get(&l_txq); if (p != NULL) { low_level_transmit(&l_netif, p); pbuf_free(p); /* free the pbuf, lwIP knows nothing of it */ p = NULL; } } } /* re-enable the RX interrupt */ ETH_DMAITConfig(ETH_DMA_IT_NIS | ETH_DMA_IT_R, ENABLE); } /******************************************************************************/ void eth_driver_write(void) { if ( ETH_GetDMAFlagStatus(ETH_DMA_FLAG_TBU) == RESET) { /* TX fifo available*/ struct pbuf *p = PbufQueue_get(&l_txq); if (p != NULL) { /* pbuf found in the queue? */ low_level_transmit(&l_netif, p); pbuf_free(p); /* free the pbuf, lwIP knows nothing of it */ } } } /******************************************************************************/ err_t ethernetif_output(struct netif *netif, struct pbuf *p) { if (PbufQueue_isEmpty(&l_txq) && /* nothing in the TX queue? */ ETH_GetDMAFlagStatus(ETH_DMA_FLAG_TBU) == RESET) { /* TX empty? */ low_level_transmit(netif, p); /* send the pbuf right away */ /* the pbuf will be freed by the lwIP code */ } else { /* otherwise post the pbuf to the transmit queue */ if (PbufQueue_put(&l_txq, p)) { /*could the TX queue take the pbuf? */ pbuf_ref(p); /* reference the pbuf to spare it from freeing */ } else { /* no room in the queue */ /* the pbuf will be freed by the lwIP code */ return(ERR_MEM); } } return(ERR_OK); } /******************************************************************************/ err_t ethernetif_init(struct netif *netif) { LWIP_ASSERT("netif != NULL", (netif != NULL)); /* We directly use etharp_output() here to save a function call. * You can instead declare your own function an call etharp_output() * from it if you have to do some checks before sending (e.g. if link * is available...) */ netif->output = etharp_output; netif->linkoutput = (void *)low_level_transmit; /* Initialize the Ethernet PHY, MAC, and DMA hardware as well as any * necessary buffers */ low_level_init(netif); /* Set link status */ netif->flags |= NETIF_FLAG_LINK_UP; return(ERR_OK); } /******************************************************************************/ void low_level_transmit(struct netif *netif, struct pbuf *p) { struct pbuf *q; u32_t l = 0; u8 *buffer; /** * Fill in the first two bytes of the payload data (configured as padding * with ETH_PAD_SIZE = 2) with the total length of the payload data * (minus the Ethernet MAC layer header). */ //*((unsigned short *)(p->payload)) = p->tot_len - 16; #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif buffer = (u8 *)(DMATxDescToSet->Buffer1Addr); /* Copy data from the pbuf(s) into the TX Fifo. */ for (q = p; q != NULL; q = q->next) { /* Send the data from the pbuf to the interface, one pbuf at a time. The size of the data in each pbuf is kept in the ->len variable. */ //printf("q->payload=%p\n",(void *)(q->payload)); MEMCPY((u8_t*)&buffer[l], q->payload, q->len); l += q->len; } ETH_Prepare_Transmit_Descriptors(l); #if ETH_PAD_SIZE pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ #endif LINK_STATS_INC(link.xmit); } /******************************************************************************/ struct pbuf *low_level_receive(void) { #if LWIP_PTPD u32_t time_s, time_ns; /* Get the current timestamp if PTPD is enabled */ lwIPHostGetTime(&time_s, &time_ns); #endif __IO ETH_DMADESCTypeDef *DMARxNextDesc; struct pbuf *p = NULL, *q = NULL; u8 *buffer; u16_t len, l = 0, i =0; FrameTypeDef frame; /* Get received frame */ frame = ETH_Get_Received_Frame_interrupt(); /* Check if we really have something or not */ if (NULL == frame.descriptor) { return(p); } /* Obtain the size of the packet and put it into the "len" variable. */ len = frame.length; buffer = (u8 *)frame.buffer; /* check that frame has no error */ if ((frame.descriptor->Status & ETH_DMARxDesc_ES) == (uint32_t)RESET) { if (len) { #if ETH_PAD_SIZE len += ETH_PAD_SIZE; /* allow room for Ethernet padding */ #endif /* We allocate a pbuf chain of pbufs from the pool. */ p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); if (p != NULL) { #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif /* We iterate over the pbuf chain until we have read the entire * packet into the pbuf. */ for (q = p; q != NULL; q = q->next) { /* Read enough bytes to fill this pbuf in the chain. The * available data in the pbuf is given by the q->len * variable. */ MEMCPY((u8_t*) q->payload, (u8_t*)&buffer[l], q->len); l += q->len; } #if ETH_PAD_SIZE pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ #endif LINK_STATS_INC(link.recv); } else { LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); } /* End else */ } /* End if */ } /* End - check that frame has no error */ #if LWIP_PTPD /* Place the timestamp in the PBUF */ p->time_s = time_s; p->time_ns = time_ns; #endif /* Release descriptors to DMA */ /* Check if received frame with multiple DMA buffer segments */ if (DMA_RX_FRAME_infos->Seg_Count > 1) { DMARxNextDesc = DMA_RX_FRAME_infos->FS_Rx_Desc; } else { DMARxNextDesc = frame.descriptor; } /* Set Own bit in Rx descriptors: gives the buffers back to DMA */ for (i=0; i<DMA_RX_FRAME_infos->Seg_Count; i++) { DMARxNextDesc->Status = ETH_DMARxDesc_OWN; DMARxNextDesc = (ETH_DMADESCTypeDef *)(DMARxNextDesc->Buffer2NextDescAddr); } /* Clear Segment_Count */ DMA_RX_FRAME_infos->Seg_Count =0; /* When Rx Buffer unavailable flag is set: clear it and resume reception */ if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32)RESET) { /* Clear RBUS ETHERNET DMA flag */ ETH->DMASR = ETH_DMASR_RBUS; /* Resume DMA reception */ ETH->DMARPDR = 0; } return(p); } /******************************************************************************/ static void PbufQueue_ctor(PbufQueue *me) { me->qread = 0; me->qwrite = 0; me->overflow = 0; } /******************************************************************************/ static struct pbuf *PbufQueue_get(PbufQueue *me) { struct pbuf *pBuf; if (PbufQueue_isEmpty(me)) { /* Return a NULL pointer if the queue is empty. */ pBuf = (struct pbuf *)0; } else { /* * The queue is not empty so return the next frame from it * and adjust the read pointer accordingly. */ pBuf = me->ring[me->qread]; if ((++me->qread) == Q_DIM(me->ring)) { me->qread = 0; } } return(pBuf); } /******************************************************************************/ static uint8_t PbufQueue_put(PbufQueue *me, struct pbuf *p) { uint8_t next_qwrite = me->qwrite + 1; if (next_qwrite == Q_DIM(me->ring)) { next_qwrite = 0; } if (next_qwrite != me->qread) { /* * The queue isn't full so we add the new frame at the current * write position and move the write pointer. */ me->ring[me->qwrite] = p; if ((++me->qwrite) == Q_DIM(me->ring)) { me->qwrite = 0; } return(1); /* successfully posted the pbuf */ } else { /* * The stack is full so we are throwing away this value. * Keep track of the number of times this happens. */ ++me->overflow; return(0); /* could not post the pbuf */ } } /*..........................................................................*/ #if NETIF_DEBUG /* Print an IP header by using LWIP_DEBUGF * @param p an IP packet, p->payload pointing to the IP header */ /******************************************************************************/ void eth_driver_debug_print(struct pbuf *p) { struct eth_hdr *ethhdr = (struct eth_hdr *)p->payload; u16_t *plen = (u16_t *)p->payload; LWIP_DEBUGF(NETIF_DEBUG, ("ETH header:\n")); LWIP_DEBUGF(NETIF_DEBUG, ("Packet Length:%5"U16_F" \n",*plen)); LWIP_DEBUGF(NETIF_DEBUG, ("Destination: %02"X8_F"-%02"X8_F"-%02"X8_F "-%02"X8_F"-%02"X8_F"-%02"X8_F"\n", ethhdr->dest.addr[0], ethhdr->dest.addr[1], ethhdr->dest.addr[2], ethhdr->dest.addr[3], ethhdr->dest.addr[4], ethhdr->dest.addr[5])); LWIP_DEBUGF(NETIF_DEBUG, ("Source: %02"X8_F"-%02"X8_F"-%02"X8_F "-%02"X8_F"-%02"X8_F"-%02"X8_F"\n", ethhdr->src.addr[0], ethhdr->src.addr[1], ethhdr->src.addr[2], ethhdr->src.addr[3], ethhdr->src.addr[4], ethhdr->src.addr[5])); LWIP_DEBUGF(NETIF_DEBUG, ("Packet Type:0x%04"U16_F" \n", ethhdr->type)); } #endif /* NETIF_DEBUG */ /******************************************************************************/ void low_level_init(struct netif *netif) { uint32_t i; /* set MAC hardware address length */ netif->hwaddr_len = ETHARP_HWADDR_LEN; /* set MAC hardware address */ netif->hwaddr[0] = DEF_MAC_ADDR0; netif->hwaddr[1] = DEF_MAC_ADDR1; netif->hwaddr[2] = DEF_MAC_ADDR2; netif->hwaddr[3] = DEF_MAC_ADDR3; netif->hwaddr[4] = DEF_MAC_ADDR4; netif->hwaddr[5] = DEF_MAC_ADDR5; /* set netif maximum transfer unit */ netif->mtu = 1500; /* Accept broadcast address and ARP traffic */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; /* initialize MAC address in ethernet MAC */ ETH_MACAddressConfig(ETH_MAC_Address0, netif->hwaddr); /* Initialize Tx Descriptors list: Chain Mode */ ETH_DMATxDescChainInit(DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB); /* Initialize Rx Descriptors list: Chain Mode */ ETH_DMARxDescChainInit(DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB); /* Enable Ethernet Rx interrrupt */ for(i=0; i<ETH_RXBUFNB; i++) { ETH_DMARxDescReceiveITConfig(&DMARxDscrTab[i], ENABLE); } #ifdef CHECKSUM_BY_HARDWARE /* Enable the checksum insertion for the Tx frames */ for(i=0; i<ETH_TXBUFNB; i++) { ETH_DMATxDescChecksumInsertionConfig(&DMATxDscrTab[i], ETH_DMATxDesc_ChecksumTCPUDPICMPFull); } #endif /* Enable MAC and DMA transmission and reception */ ETH_Start(); dbg_slow_printf("Ethernet started...\n"); } /** * @} * end addtogroup groupLWIP_QPC_Eth */ /******************************************************************************/ inline void ETH_EventCallback( void ) { if ( ETH_GetDMAFlagStatus(ETH_DMA_FLAG_R) == SET) { ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS | ETH_DMA_IT_R);/* clear the interrupt sources */ static QEvent const evt_eth_rx = { LWIP_RX_READY_SIG, 0 }; QACTIVE_POST(l_active, &evt_eth_rx, &l_Ethernet_IRQHandler); ETH_DMAITConfig(ETH_DMA_IT_R, DISABLE); /* disable further RX */ } if ( ETH_GetDMAFlagStatus(ETH_DMA_FLAG_T) == SET) { ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS | ETH_DMA_IT_T);/* clear the interrupt sources */ static QEvent const evt_eth_tx = { LWIP_TX_READY_SIG, 0 }; QACTIVE_POST(l_active, &evt_eth_tx, &l_Ethernet_IRQHandler); } /* When Rx Buffer unavailable flag is set: clear it and resume reception. Taken from: * http://lists.gnu.org/archive/html/lwip-users/2012-09/msg00053.html */ if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32)RESET) { /* Clear RBUS ETHERNET DMA flag */ ETH->DMASR = ETH_DMASR_RBUS; /* Resume DMA reception. The register doesn't care what you write to it. */ ETH->DMARPDR = 0; } #if LINK_STATS if ( ETH_GetDMAFlagStatus(ETH_DMA_FLAG_RO) == SET) { static QEvent const evt_eth_er = { LWIP_RX_OVERRUN_SIG, 0 }; QACTIVE_POST(l_active, &evt_eth_er, &l_Ethernet_IRQHandler); } #endif } /******** Copyright (C) 2014 Datacard. All rights reserved *****END OF FILE****/
lgpl-3.0
maichain/listener
vendor/github.com/btcsuite/btcd/blockchain/error.go
11052
// Copyright (c) 2014-2016 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package blockchain import ( "fmt" ) // DeploymentError identifies an error that indicates a deployment ID was // specified that does not exist. type DeploymentError uint32 // Error returns the assertion error as a human-readable string and satisfies // the error interface. func (e DeploymentError) Error() string { return fmt.Sprintf("deployment ID %d does not exist", uint32(e)) } // AssertError identifies an error that indicates an internal code consistency // issue and should be treated as a critical and unrecoverable error. type AssertError string // Error returns the assertion error as a human-readable string and satisfies // the error interface. func (e AssertError) Error() string { return "assertion failed: " + string(e) } // ErrorCode identifies a kind of error. type ErrorCode int // These constants are used to identify a specific RuleError. const ( // ErrDuplicateBlock indicates a block with the same hash already // exists. ErrDuplicateBlock ErrorCode = iota // ErrBlockTooBig indicates the serialized block size exceeds the // maximum allowed size. ErrBlockTooBig // ErrBlockWeightTooHigh indicates that the block's computed weight // metric exceeds the maximum allowed value. ErrBlockWeightTooHigh // ErrBlockVersionTooOld indicates the block version is too old and is // no longer accepted since the majority of the network has upgraded // to a newer version. ErrBlockVersionTooOld // ErrInvalidTime indicates the time in the passed block has a precision // that is more than one second. The chain consensus rules require // timestamps to have a maximum precision of one second. ErrInvalidTime // ErrTimeTooOld indicates the time is either before the median time of // the last several blocks per the chain consensus rules or prior to the // most recent checkpoint. ErrTimeTooOld // ErrTimeTooNew indicates the time is too far in the future as compared // the current time. ErrTimeTooNew // ErrDifficultyTooLow indicates the difficulty for the block is lower // than the difficulty required by the most recent checkpoint. ErrDifficultyTooLow // ErrUnexpectedDifficulty indicates specified bits do not align with // the expected value either because it doesn't match the calculated // valued based on difficulty regarted rules or it is out of the valid // range. ErrUnexpectedDifficulty // ErrHighHash indicates the block does not hash to a value which is // lower than the required target difficultly. ErrHighHash // ErrBadMerkleRoot indicates the calculated merkle root does not match // the expected value. ErrBadMerkleRoot // ErrBadCheckpoint indicates a block that is expected to be at a // checkpoint height does not match the expected one. ErrBadCheckpoint // ErrForkTooOld indicates a block is attempting to fork the block chain // before the most recent checkpoint. ErrForkTooOld // ErrCheckpointTimeTooOld indicates a block has a timestamp before the // most recent checkpoint. ErrCheckpointTimeTooOld // ErrNoTransactions indicates the block does not have a least one // transaction. A valid block must have at least the coinbase // transaction. ErrNoTransactions // ErrTooManyTransactions indicates the block has more transactions than // are allowed. ErrTooManyTransactions // ErrNoTxInputs indicates a transaction does not have any inputs. A // valid transaction must have at least one input. ErrNoTxInputs // ErrNoTxOutputs indicates a transaction does not have any outputs. A // valid transaction must have at least one output. ErrNoTxOutputs // ErrTxTooBig indicates a transaction exceeds the maximum allowed size // when serialized. ErrTxTooBig // ErrBadTxOutValue indicates an output value for a transaction is // invalid in some way such as being out of range. ErrBadTxOutValue // ErrDuplicateTxInputs indicates a transaction references the same // input more than once. ErrDuplicateTxInputs // ErrBadTxInput indicates a transaction input is invalid in some way // such as referencing a previous transaction outpoint which is out of // range or not referencing one at all. ErrBadTxInput // ErrMissingTxOut indicates a transaction output referenced by an input // either does not exist or has already been spent. ErrMissingTxOut // ErrUnfinalizedTx indicates a transaction has not been finalized. // A valid block may only contain finalized transactions. ErrUnfinalizedTx // ErrDuplicateTx indicates a block contains an identical transaction // (or at least two transactions which hash to the same value). A // valid block may only contain unique transactions. ErrDuplicateTx // ErrOverwriteTx indicates a block contains a transaction that has // the same hash as a previous transaction which has not been fully // spent. ErrOverwriteTx // ErrImmatureSpend indicates a transaction is attempting to spend a // coinbase that has not yet reached the required maturity. ErrImmatureSpend // ErrSpendTooHigh indicates a transaction is attempting to spend more // value than the sum of all of its inputs. ErrSpendTooHigh // ErrBadFees indicates the total fees for a block are invalid due to // exceeding the maximum possible value. ErrBadFees // ErrTooManySigOps indicates the total number of signature operations // for a transaction or block exceed the maximum allowed limits. ErrTooManySigOps // ErrFirstTxNotCoinbase indicates the first transaction in a block // is not a coinbase transaction. ErrFirstTxNotCoinbase // ErrMultipleCoinbases indicates a block contains more than one // coinbase transaction. ErrMultipleCoinbases // ErrBadCoinbaseScriptLen indicates the length of the signature script // for a coinbase transaction is not within the valid range. ErrBadCoinbaseScriptLen // ErrBadCoinbaseValue indicates the amount of a coinbase value does // not match the expected value of the subsidy plus the sum of all fees. ErrBadCoinbaseValue // ErrMissingCoinbaseHeight indicates the coinbase transaction for a // block does not start with the serialized block block height as // required for version 2 and higher blocks. ErrMissingCoinbaseHeight // ErrBadCoinbaseHeight indicates the serialized block height in the // coinbase transaction for version 2 and higher blocks does not match // the expected value. ErrBadCoinbaseHeight // ErrScriptMalformed indicates a transaction script is malformed in // some way. For example, it might be longer than the maximum allowed // length or fail to parse. ErrScriptMalformed // ErrScriptValidation indicates the result of executing transaction // script failed. The error covers any failure when executing scripts // such signature verification failures and execution past the end of // the stack. ErrScriptValidation // ErrUnexpectedWitness indicates that a block includes transactions // with witness data, but doesn't also have a witness commitment within // the coinbase transaction. ErrUnexpectedWitness // ErrInvalidWitnessCommitment indicates that a block's witness // commitment is not well formed. ErrInvalidWitnessCommitment // ErrWitnessCommitmentMismatch indicates that the witness commitment // included in the block's coinbase transaction doesn't match the // manually computed witness commitment. ErrWitnessCommitmentMismatch // ErrPrevBlockNotBest indicates that the block's previous block is not the // current chain tip. This is not a block validation rule, but is required // for block proposals submitted via getblocktemplate RPC. ErrPrevBlockNotBest ) // Map of ErrorCode values back to their constant names for pretty printing. var errorCodeStrings = map[ErrorCode]string{ ErrDuplicateBlock: "ErrDuplicateBlock", ErrBlockTooBig: "ErrBlockTooBig", ErrBlockVersionTooOld: "ErrBlockVersionTooOld", ErrBlockWeightTooHigh: "ErrBlockWeightTooHigh", ErrInvalidTime: "ErrInvalidTime", ErrTimeTooOld: "ErrTimeTooOld", ErrTimeTooNew: "ErrTimeTooNew", ErrDifficultyTooLow: "ErrDifficultyTooLow", ErrUnexpectedDifficulty: "ErrUnexpectedDifficulty", ErrHighHash: "ErrHighHash", ErrBadMerkleRoot: "ErrBadMerkleRoot", ErrBadCheckpoint: "ErrBadCheckpoint", ErrForkTooOld: "ErrForkTooOld", ErrCheckpointTimeTooOld: "ErrCheckpointTimeTooOld", ErrNoTransactions: "ErrNoTransactions", ErrTooManyTransactions: "ErrTooManyTransactions", ErrNoTxInputs: "ErrNoTxInputs", ErrNoTxOutputs: "ErrNoTxOutputs", ErrTxTooBig: "ErrTxTooBig", ErrBadTxOutValue: "ErrBadTxOutValue", ErrDuplicateTxInputs: "ErrDuplicateTxInputs", ErrBadTxInput: "ErrBadTxInput", ErrMissingTxOut: "ErrMissingTxOut", ErrUnfinalizedTx: "ErrUnfinalizedTx", ErrDuplicateTx: "ErrDuplicateTx", ErrOverwriteTx: "ErrOverwriteTx", ErrImmatureSpend: "ErrImmatureSpend", ErrSpendTooHigh: "ErrSpendTooHigh", ErrBadFees: "ErrBadFees", ErrTooManySigOps: "ErrTooManySigOps", ErrFirstTxNotCoinbase: "ErrFirstTxNotCoinbase", ErrMultipleCoinbases: "ErrMultipleCoinbases", ErrBadCoinbaseScriptLen: "ErrBadCoinbaseScriptLen", ErrBadCoinbaseValue: "ErrBadCoinbaseValue", ErrMissingCoinbaseHeight: "ErrMissingCoinbaseHeight", ErrBadCoinbaseHeight: "ErrBadCoinbaseHeight", ErrScriptMalformed: "ErrScriptMalformed", ErrScriptValidation: "ErrScriptValidation", ErrUnexpectedWitness: "ErrUnexpectedWitness", ErrInvalidWitnessCommitment: "ErrInvalidWitnessCommitment", ErrWitnessCommitmentMismatch: "ErrWitnessCommitmentMismatch", ErrPrevBlockNotBest: "ErrPrevBlockNotBest", } // String returns the ErrorCode as a human-readable name. func (e ErrorCode) String() string { if s := errorCodeStrings[e]; s != "" { return s } return fmt.Sprintf("Unknown ErrorCode (%d)", int(e)) } // RuleError identifies a rule violation. It is used to indicate that // processing of a block or transaction failed due to one of the many validation // rules. The caller can use type assertions to determine if a failure was // specifically due to a rule violation and access the ErrorCode field to // ascertain the specific reason for the rule violation. type RuleError struct { ErrorCode ErrorCode // Describes the kind of error Description string // Human readable description of the issue } // Error satisfies the error interface and prints human-readable errors. func (e RuleError) Error() string { return e.Description } // ruleError creates an RuleError given a set of arguments. func ruleError(c ErrorCode, desc string) RuleError { return RuleError{ErrorCode: c, Description: desc} }
lgpl-3.0
MRChemSoft/mrcpp
src/treebuilders/ABGVCalculator.h
1687
/* * MRCPP, a numerical library based on multiresolution analysis and * the multiwavelet basis which provide low-scaling algorithms as well as * rigorous error control in numerical computations. * Copyright (C) 2021 Stig Rune Jensen, Jonas Juselius, Luca Frediani and contributors. * * This file is part of MRCPP. * * MRCPP 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. * * MRCPP 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 MRCPP. If not, see <https://www.gnu.org/licenses/>. * * For information on the complete list of contributors to MRCPP, see: * <https://mrcpp.readthedocs.io/> */ #pragma once #include "TreeCalculator.h" namespace mrcpp { class ABGVCalculator final : public TreeCalculator<2> { public: ABGVCalculator(const ScalingBasis &basis, double a, double b); private: const double A; ///< Left boundary conditions, ref. Alpert et al. const double B; ///< Right boundary conditions, ref. Alpert et al. Eigen::MatrixXd K; Eigen::VectorXd valueZero; Eigen::VectorXd valueOne; void calcNode(MWNode<2> &node) override; void calcKMatrix(const ScalingBasis &basis); void calcValueVectors(const ScalingBasis &basis); }; } // namespace mrcpp
lgpl-3.0
Neil5043/Minetweak
src/main/java/net/minecraft/src/CommandServerBanlist.java
2423
package net.minecraft.src; import net.minecraft.server.MinecraftServer; import java.util.List; public class CommandServerBanlist extends CommandBase { public String getCommandName() { return "banlist"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 3; } /** * Returns true if the given command sender is allowed to use this command. */ public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) { return (MinecraftServer.getServer().getConfigurationManager().getBannedIPs().isListActive() || MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().isListActive()) && super.canCommandSenderUseCommand(par1ICommandSender); } public String getCommandUsage(ICommandSender par1ICommandSender) { return "commands.banlist.usage"; } public void processCommand(ICommandSender par1ICommandSender, String[] par2ArrayOfStr) { if (par2ArrayOfStr.length >= 1 && par2ArrayOfStr[0].equalsIgnoreCase("ips")) { par1ICommandSender.func_110122_a(ChatMessageComponent.func_111082_b("commands.banlist.ips", new Object[] {Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().getBannedIPs().getBannedList().size())})); par1ICommandSender.func_110122_a(ChatMessageComponent.func_111066_d(joinNiceString(MinecraftServer.getServer().getConfigurationManager().getBannedIPs().getBannedList().keySet().toArray()))); } else { par1ICommandSender.func_110122_a(ChatMessageComponent.func_111082_b("commands.banlist.players", new Object[] {Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getBannedList().size())})); par1ICommandSender.func_110122_a(ChatMessageComponent.func_111066_d(joinNiceString(MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getBannedList().keySet().toArray()))); } } /** * Adds the strings available in this command to the given list of tab completion options. */ public List addTabCompletionOptions(ICommandSender par1ICommandSender, String[] par2ArrayOfStr) { return par2ArrayOfStr.length == 1 ? getListOfStringsMatchingLastWord(par2ArrayOfStr, new String[] {"players", "ips"}): null; } }
lgpl-3.0
HuaiJiang/pjm
test/integration/routing/previews_test.rb
1499
# Redmine - project management software # Copyright (C) 2006-2013 Jean-Philippe Lang # # 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 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. require File.expand_path('../../../test_helper', __FILE__) class RoutingPreviewsTest < ActionController::IntegrationTest def test_previews ["get", "post", "put"].each do |method| assert_routing( { :method => method, :path => "/issues/preview/new/123" }, { :controller => 'previews', :action => 'issue', :project_id => '123' } ) assert_routing( { :method => method, :path => "/issues/preview/edit/321" }, { :controller => 'previews', :action => 'issue', :id => '321' } ) end assert_routing( { :method => 'get', :path => "/news/preview" }, { :controller => 'previews', :action => 'news' } ) end end
lgpl-3.0
herrnikolov/SoftUni_-_DB_Fundamentals
21. Exam - Databases MSSQL Server Exam - 22 October 2017/21. Databases MSSQL Server Exam - 22 October 2017_Solutions.sql
5865
----Section 1. DDL (30 pts) CREATE DATABASE ReportService GO USE ReportService GO --01.Database design CREATE TABLE Users ( Id INT PRIMARY KEY IDENTITY NOT NULL, Username NVARCHAR(30) UNIQUE NOT NULL, [Password] NVARCHAR(50) NOT NULL, [Name] NVARCHAR(50), Gender CHAR(1) CHECK (Gender IN ('M', 'F')), BirthDate DATETIME, Age INT, Email NVARCHAR(50) ) CREATE TABLE Departments ( Id INT PRIMARY KEY IDENTITY NOT NULL, [Name] NVARCHAR(50) NOT NULL ) CREATE TABLE [Status] ( Id INT PRIMARY KEY IDENTITY NOT NULL, Label VARCHAR(30) NOT NULL ) CREATE TABLE Employees ( Id INT PRIMARY KEY IDENTITY NOT NULL, FirstName NVARCHAR(25), LastName NVARCHAR(25), Gender CHAR(1) CHECK (Gender IN ('M', 'F')), BirthDate DATETIME, Age INT, DepartmentId INT FOREIGN KEY REFERENCES Departments(Id) NOT NULL, ) CREATE TABLE Categories ( Id INT PRIMARY KEY IDENTITY NOT NULL, [Name] VARCHAR(50) NOT NULL, DepartmentId INT FOREIGN KEY REFERENCES Departments(Id), ) CREATE TABLE Reports ( Id INT PRIMARY KEY IDENTITY NOT NULL, CategoryId INT FOREIGN KEY REFERENCES Categories(Id) NOT NULL, StatusId INT FOREIGN KEY REFERENCES [Status](Id) NOT NULL, OpenDate DATETIME, CloseDate DATETIME, [Description] NVARCHAR(200), UserId INT FOREIGN KEY REFERENCES Users(Id) NOT NULL, EmployeeId INT FOREIGN KEY REFERENCES Employees(Id) ) GO ----Section 2. DML (10 pts) --02.Insert INSERT INTO Employees(FirstName,LastName,Gender,Birthdate,DepartmentId) VALUES ('Marlo','O’Malley', 'M', '9/21/1958', '1'), ('Niki', 'Stanaghan', 'F', '11/26/1969', '4'), ('Ayrton', 'Senna', 'M', '03/21/1960' , '9'), ('Ronnie', 'Peterson', 'M', '02/14/1944', '9'), ('Giovanna', 'Amati', 'F', '07/20/1959', '5') INSERT INTO Reports(CategoryId,StatusId,OpenDate,CloseDate,[Description],UserId,EmployeeId) VALUES ('1', '1', '04/13/2017', NULL, 'Stuck Road on Str.133', '6', '2'), ('6', '3', '09/05/2015', '12/06/2015', 'Charity trail running', '3', '5'), ('14', '2', '09/07/2015',NULL , 'Falling bricks on Str.58', '5', '2'), ('4', '3', '07/03/2017', '07/06/2017', 'Cut off streetlight on Str.11', '1', '1') GO --03. Update --SELECT * FROM Reports WHERE CategoryId=4 AND StatusId=1 UPDATE Reports SET StatusId = '2' WHERE CategoryId='4' AND StatusId='1' GO --Switch all report’s --status to “in progress” where it is currently “waiting” --for the “Streetlight” category (look up the category ID and status ID’s manually, there is no need to use table joins). --in progress = 2 --waiting = 1 --Streetlight = 1 --04. Delete --Delete all reports who have a status “blocked”. DELETE FROM Reports WHERE StatusId = '4' GO ----Section 3. Querying (40 pts) --05.Users by Age SELECT Username, Age FROM Users ORDER BY Age ASC, Username DESC GO --06. Unassigned Reports SELECT [Description], OpenDate FROM Reports WHERE EmployeeId IS NULL ORDER BY OpenDate, [Description] GO --07. Employees & Reports SELECT e.FirstName, e.LastName, r.[Description], CONVERT(VARCHAR(10), OpenDate, 120) FROM Employees AS e JOIN Reports AS R ON r.EmployeeId = e.Id ORDER BY e.Id, r.OpenDate, r.Id GO --08. Most Reported Category SELECT c.Name AS [CategoryName], COUNT(r.CategoryId) AS ReportsNumber FROM Categories AS c JOIN Reports AS r ON r.CategoryId=c.Id GROUP BY c.Name ORDER BY ReportsNumber DESC,CategoryName GO --09. Employees in Category SELECT c.Name AS CategoryName, COUNT(e.Id) FROM Categories AS c JOIN Departments AS d ON d.Id=c.DepartmentId JOIN Employees AS e ON e.DepartmentId=c.DepartmentId GROUP BY c.Name ORDER BY c.Name GO --10. Users per Employee SELECT e.FirstName + ' ' + e.LastName AS [Name], COUNT(DISTINCT r.UserId) AS [Users Number] FROM Employees AS e LEFT JOIN Reports AS r ON r.EmployeeId=e.Id GROUP BY e.FirstName + ' ' + e.LastName ORDER BY COUNT(DISTINCT r.UserId) DESC, e.FirstName + ' ' + e.LastName GO --11. Emergency Patrol SELECT r.OpenDate, r.[Description], u.Email FROM Reports AS r JOIN Users AS u ON u.Id=r.UserId JOIN Categories AS c ON c.Id=r.CategoryId JOIN Departments AS d ON d.Id=c.DepartmentId WHERE r.CloseDate IS NULL AND (LEN(r.Description) > 20 AND r.Description LIKE '%str%') AND d.Name IN ('Infrastructure', 'Emergency', 'Roads Maintenance') ORDER BY r.OpenDate, u.Email, r.Id GO --12.Birthday Report SELECT c.Name AS [Category Name] FROM Categories AS c JOIN Reports AS r ON r.CategoryId=c.Id JOIN Users AS u ON u.Id=r.UserId WHERE DAY(u.BirthDate) = DAY(r.OpenDate) AND MONTH(u.BirthDate) = MONTH(r.OpenDate) GROUP BY c.Name ORDER BY c.Name GO --or SELECT c.Name AS [Category Name] FROM Categories AS c JOIN Reports AS r ON r.CategoryId=c.Id JOIN Users AS u ON u.Id=r.UserId WHERE DATEPART(DAY, r.OpenDate) = DATEPART(DAY,u.BirthDate) AND DATEPART(MONTH, r.OpenDate) = DATEPART(MONTH,u.BirthDate) GROUP BY c.Name GO --13. Numbers Coincidence SELECT DISTINCT(u.Username) FROM Users AS u JOIN Reports AS r ON r.UserId=u.Id JOIN Categories AS c ON c.Id=r.CategoryId WHERE (ISNUMERIC(LEFT(u.Username, 1)) = 1 AND CAST(LEFT(u.Username, 1) AS INT) = r.CategoryId) OR (ISNUMERIC(RIGHT(u.Username, 1)) = 1 AND CAST(RIGHT(u.Username, 1) AS INT) = r.CategoryId) ORDER BY u.Username GO --or SELECT DISTINCT(u.Username) FROM Users AS u JOIN Reports AS r ON r.UserId=u.Id JOIN Categories AS c ON c.Id=r.CategoryId WHERE (u.Username LIKE '[0-9]%' AND CAST(r.CategoryId AS CHAR)=SUBSTRING(u.Username,1,1)) OR (u.Username LIKE '%[0-9]' AND CAST(r.CategoryId AS CHAR)=SUBSTRING(u.Username,LEN(u.UserName),1)) ORDER BY u.Username GO -- or SELECT DISTINCT(u.Username) FROM Users AS u JOIN Reports AS r ON r.UserId=u.Id JOIN Categories AS c ON c.Id=r.CategoryId WHERE (ISNUMERIC(LEFT(u.Username, 1)) = 1 AND CAST(LEFT(u.Username, 1) AS INT) = r.CategoryId) OR (ISNUMERIC(RIGHT(u.Username, 1)) = 1 AND CAST(RIGHT(u.Username, 1) AS INT) = r.CategoryId) ORDER BY u.Username GO --14. Open/Closed Statistics
lgpl-3.0
erelsgl/erel-sites
tnk1/ktuv/mj/18-15.html
16228
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1255' /> <meta charset='windows-1255' /> <meta http-equiv='Content-Script-Type' content='text/javascript' /> <meta http-equiv='revisit-after' content='15 days' /> <title>çëîéí, ðáåðéí åàéáøé âåôí</title> <link rel='stylesheet' type='text/css' href='../../../_script/klli.css' /> <link rel='stylesheet' type='text/css' href='../../../tnk1/_themes/klli.css' /> <meta property='og:url' content='https://tora.us.fm/tnk1/ktuv/mj/18-15.html'/> <meta name='author' content="àøàì" /> <meta name='receiver' content="" /> <meta name='jmQovc' content="tnk1/ktuv/mj/18-15.html" /> <meta name='tvnit' content="" /> <link rel='canonical' href='https://tora.us.fm/tnk1/ktuv/mj/18-15.html' /> </head> <!-- PHP Programming by Erel Segal-Halevi --> <body lang='he' dir='rtl' id = 'tnk1_ktuv_mj_18_15' class='kll_spr '> <div class='pnim'> <script type='text/javascript' src='../../../_script/vars.js'></script> <!--NiwutElyon0--> <div class='NiwutElyon'> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/ljon/index.html'>ìùåï äî÷øà</a>&gt;<a href='../../../tnk1/ljon/jorj/lbb2.html'>ì?á</a>&gt;<a href='../../../tnk1/kma/qjrim1/lv.html'>ìá=</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/prqim/ktuv.html'>ëúåáéí</a>&gt;<a href='../../../tnk1/prqim/t28.htm'>îùìé</a>&gt;<a href='../../../tnk1/ktuv/mjly/ljon.html'>ìùåï åñâðåï áñôø îùìé</a>&gt;<a href='../../../tnk1/ktuv/mjly/bituyim.html'>áéèåééí áñôø îùìé</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/klli/limud/index.html'>ìéîåã úð"ê</a>&gt;<a href='../../../tnk1/msr/3xinuk.html'>äåøàä</a>&gt;</div> </div> <!--NiwutElyon1--> <h1 id='h1'>çëîéí, ðáåðéí åàéáøé âåôí</h1> <div id='idfields'> <p>÷åã: áéàåø:îùìé éç15 áúð"ê</p> <p>ñåâ: ëìì_ñôø</p> <p>îàú: àøàì</p> <p>àì: </p> </div> <script type='text/javascript'>kotrt()</script> <div id='tokn'> <table class='inner_navigation'> <tr><td> <a href='00-00.html'><b>ñôø îùìé</b></a> &nbsp;&nbsp;&nbsp;ôø÷&nbsp;&nbsp; &nbsp;<a href='01-00.html'>à</a>&nbsp; &nbsp;<a href='02-00.html'>á</a>&nbsp; &nbsp;<a href='03-00.html'>â</a>&nbsp; &nbsp;<a href='04-00.html'>ã</a>&nbsp; &nbsp;<a href='05-00.html'>ä</a>&nbsp; &nbsp;<a href='06-00.html'>å</a>&nbsp; &nbsp;<a href='07-00.html'>æ</a>&nbsp; &nbsp;<a href='08-00.html'>ç</a>&nbsp; &nbsp;<a href='09-00.html'>è</a>&nbsp; &nbsp;<a href='10-00.html'>é</a>&nbsp; &nbsp;<a href='11-00.html'>éà</a>&nbsp; &nbsp;<a href='12-00.html'>éá</a>&nbsp; &nbsp;<a href='13-00.html'>éâ</a>&nbsp; &nbsp;<a href='14-00.html'>éã</a>&nbsp; &nbsp;<a href='15-00.html'>èå</a>&nbsp; &nbsp;<a href='16-00.html'>èæ</a>&nbsp; &nbsp;<a href='17-00.html'>éæ</a>&nbsp; &nbsp;<b>éç</b>&nbsp; &nbsp;<a href='19-00.html'>éè</a>&nbsp; &nbsp;<a href='20-00.html'>ë</a>&nbsp; &nbsp;<a href='21-00.html'>ëà</a>&nbsp; &nbsp;<a href='22-00.html'>ëá</a>&nbsp; &nbsp;<a href='23-00.html'>ëâ</a>&nbsp; &nbsp;<a href='24-00.html'>ëã</a>&nbsp; &nbsp;<a href='25-00.html'>ëä</a>&nbsp; &nbsp;<a href='26-00.html'>ëå</a>&nbsp; &nbsp;<a href='27-00.html'>ëæ</a>&nbsp; &nbsp;<a href='28-00.html'>ëç</a>&nbsp; &nbsp;<a href='29-00.html'>ëè</a>&nbsp; &nbsp;<a href='30-00.html'>ì</a>&nbsp; &nbsp;<a href='31-00.html'>ìà</a>&nbsp; </td></tr> <tr><td> &nbsp;<a href='18-00.html'>ôø÷ éç</a>&nbsp;&nbsp;&nbsp;&nbsp;ôñå÷&nbsp;&nbsp; &nbsp;<a href='18-01.html'>1</a>&nbsp; &nbsp;<a href='18-02.html'>2</a>&nbsp; &nbsp;<a href='18-03.html'>3</a>&nbsp; &nbsp;<a href='18-04.html'>4</a>&nbsp; &nbsp;<a href='18-05.html'>5</a>&nbsp; &nbsp;<a href='18-06.html'>6</a>&nbsp; &nbsp;<a href='18-07.html'>7</a>&nbsp; &nbsp;<a href='18-08.html'>8</a>&nbsp; &nbsp;<a href='18-09.html'>9</a>&nbsp; &nbsp;<a href='18-10.html'>10</a>&nbsp; &nbsp;<a href='18-11.html'>11</a>&nbsp; &nbsp;<a href='18-12.html'>12</a>&nbsp; &nbsp;<a href='18-13.html'>13</a>&nbsp; &nbsp;<a href='18-14.html'>14</a>&nbsp; &nbsp;<b>15</b>&nbsp; &nbsp;<a href='18-16.html'>16</a>&nbsp; &nbsp;<a href='18-17.html'>17</a>&nbsp; &nbsp;<a href='18-18.html'>18</a>&nbsp; &nbsp;<a href='18-19.html'>19</a>&nbsp; &nbsp;<a href='18-20.html'>20</a>&nbsp; &nbsp;<a href='18-21.html'>21</a>&nbsp; &nbsp;<a href='18-22.html'>22</a>&nbsp; &nbsp;<a href='18-23.html'>23</a>&nbsp; &nbsp;<a href='18-24.html'>24</a>&nbsp; </td></tr> </table><!-- inner_navigation --> <div class='page single_height'> <div class='verse_and_tirgumim'> <div class='verse'> <span class='verse_number'> éç15</span> <span class='verse_text'>ìÅá ðÈáåÉï éÄ÷ÀðÆä ãÌÈòÇú, åÀàÉæÆï çÂëÈîÄéí úÌÀáÇ÷ÌÆùÑ ãÌÈòÇú.</span> </div> <div class='short'> <div class='cell tirgum longcell'> <h2 class='subtitle'> &nbsp;ñâåìåú </h2> <div class='cellcontent'> <p> <strong>ìá</strong> ùì àãí <strong>ðáåï</strong> òåñ÷ ëì äæîï áîçùáåú <strong>ä÷åðåú</strong> (îééöøåú) <strong>îéãò</strong> åøòéåðåú çãùéí;&#160;&#160; <strong>åàåæï</strong> ùì àðùéí <strong>çëîéí îá÷ùú</strong> (îçôùú) ëì äæîï ìä÷ùéá åììîåã <strong>îéãò</strong> îàçøéí.</p> </div><!--cellcontent--> </div> <div class='cell mcudot longcell'> <h2 class='subtitle'> &nbsp;îöåãåú </h2> <div class='cellcontent'> <p>îé ùéù ìå <strong>ìá ðáåï</strong>, äðä îòöîå <strong>é÷ðä äãòú</strong> ááéðú äìá; &#160; àáì ä<strong>çëîéí</strong>, ùàéï áéãí àìà îä ùùîòå, äðä <strong>àæðí úá÷ù</strong> åúçæåø àçø ä<strong>ãòú</strong> ìùîåò îæåìú, ëé àéï ìäí áéðä ìäáéï îòöîí.</p> </div><!--cellcontent--> </div> </div><!--short--> </div><!--verse_and_tirgumim--> <br style='clear:both; line-height:0' /> <div class='long'> <div class='cell hqblot longcell'> <h2 class='subtitle'> &nbsp;ä÷áìåú </h2> <div class='cellcontent'> <p>äôñå÷ îáçéï áéï <strong>çëí</strong> ìáéï <strong>ðáåï</strong>: "<q class="mfrj">ùëì äàéù <strong>äðáåï</strong> <strong>é÷ðä ãòú</strong> ÷ãåùéí îòöîå, ëé îøåá ôìôåìå éåöéà ãáø îúåê ãáø; &#160; <strong>åäçëîéí</strong> <strong>éá÷ùå</strong> ìùîåò <strong>äãòú</strong> åììîåã àåúå îäéåãòéí ìùéòåøéí, ëé ãòúí ÷öøä ìäáéï æä îòöîí</q>" <small>(<a class="external text" href="http://he.wikisource.org/wiki/%D7%A8%D7%9C%D7%91%22%D7%92_%D7%A2%D7%9C_%D7%9E%D7%A9%D7%9C%D7%99_%D7%99%D7%97_%D7%98%D7%95">øìá"â</a>)</small>.</p> <p>äçëí åäðáåï ðáãìéí, áéï äùàø, áàéáøé-äâåó äòé÷øééí ùáäí äí îùúîùéí. </p> <p> <strong>äçëí</strong> îùúîù áòé÷ø áàåæðééí: </p> <ul><li> <a class="psuq" href="/tnk1/prqim/t2801.htm#5">îùìé à5</a>: "<q class="psuq"><strong>éÄùÑÀîÇò çÈëÈí</strong> åÀéåÉñÆó ìÆ÷Çç, åÀðÈáåÉï úÌÇçÀáÌËìåÉú éÄ÷ÀðÆä</q>" (<a href="/tnk1/ktuv/mj/01-05.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2802.htm#2">îùìé á2</a>: "<q class="psuq">ìÀäÇ÷ÀùÑÄéá <strong>ìÇçÈëÀîÈä àÈæÀðÆêÈ</strong>, úÌÇèÌÆä ìÄáÌÀêÈ ìÇúÌÀáåÌðÈä</q>" (<a href="/tnk1/ktuv/mj/02-01.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2812.htm#15">îùìé éá15</a>: "<q class="psuq">ãÌÆøÆêÀ àÁåÄéì éÈùÑÈø áÌÀòÅéðÈéå, <strong>åÀùÑÉîÅòÇ</strong> ìÀòÅöÈä <strong>çÈëÈí</strong></q>" (<a href="/tnk1/ktuv/mj/12-15.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2815.htm#31">îùìé èå31</a>: "<q class="psuq"><strong>àÉæÆï ùÑÉîÇòÇú</strong> úÌåÉëÇçÇú çÇéÌÄéí, áÌÀ÷ÆøÆá <strong>çÂëÈîÄéí</strong> úÌÈìÄéï</q>" (<a href="/tnk1/ktuv/mj/15-31.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2818.htm#15">îùìé éç15</a>: "<q class="psuq">ìÅá ðÈáåÉï éÄ÷ÀðÆä ãÌÈòÇú, <strong>åÀàÉæÆï çÂëÈîÄéí</strong> úÌÀáÇ÷ÌÆùÑ ãÌÈòÇú</q>" </li><li> <a class="psuq" href="/tnk1/prqim/t2823.htm#19">îùìé ëâ19</a>: "<q class="psuq"><strong>ùÑÀîÇò</strong> àÇúÌÈä áÀðÄé <strong>åÇçÂëÈí</strong>, åÀàÇùÌÑÅø áÌÇãÌÆøÆêÀ ìÄáÌÆêÈ</q>" (<a href="/tnk1/ktuv/mj/23-17.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2825.htm#12">îùìé ëä12</a>: "<q class="psuq">ðÆæÆí æÈäÈá åÇçÂìÄé ëÈúÆí îåÉëÄéçÇ <strong>çÈëÈí</strong> òÇì <strong>àÉæÆï ùÑÉîÈòÇú</strong></q>" (<a href="/tnk1/ktuv/mj/25-12.html">ôéøåè</a>)</li></ul> <p>åáàéáøé äãéáåø: </p> <ul><li> <a class="psuq" href="/tnk1/prqim/t2812.htm#18">îùìé éá18</a>: "<q class="psuq">éÅùÑ áÌåÉèÆä ëÌÀîÇãÀ÷ÀøåÉú çÈøÆá, <strong>åÌìÀùÑåÉï çÂëÈîÄéí</strong> îÇøÀôÌÅà</q>" (<a href="/tnk1/ktuv/mj/12-18.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2814.htm#3">îùìé éã3</a>: "<q class="psuq">áÌÀôÄé àÁåÄéì çÉèÆø âÌÇàÂåÈä, <strong>åÀùÒÄôÀúÅé çÂëÈîÄéí</strong> úÌÄùÑÀîåÌøÅí</q>" (<a href="/tnk1/ktuv/mj/14-03.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2815.htm#2">îùìé èå2</a>: "<q class="psuq"><strong>ìÀùÑåÉï çÂëÈîÄéí</strong> úÌÅéèÄéá ãÌÈòÇú, åÌôÄé ëÀñÄéìÄéí éÇáÌÄéòÇ àÄåÌÆìÆú</q>" (<a href="/tnk1/ktuv/mj/15-02.html">ôéøåè</a>) </li><li> <a class="psuq" href="/tnk1/prqim/t2815.htm#7">îùìé èå7</a>: "<q class="psuq"><strong>ùÒÄôÀúÅé çÂëÈîÄéí</strong> éÀæÈøåÌ ãÈòÇú, åÀìÅá ëÌÀñÄéìÄéí ìÉà ëÅï</q>" (<a href="/tnk1/ktuv/mj/15-07.html">ôéøåè</a>)</li></ul> <p>âí ëùäçëí îùúîù áìá, äîèøä ùìå äéà ìùôø àú äãáøéí ùäåà àåîø, ëê ùéäéå îùëðòéí éåúø, åéâøîå ìàðùéí øáéí éåúø ììîåã îäí ì÷ç: </p> <ul><li> <a class="psuq" href="/tnk1/prqim/t2816.htm#23">îùìé èæ23</a>: "<q class="psuq"><strong>ìÅá çÈëÈí</strong> éÇùÒÀëÌÄéì <strong>ôÌÄéäåÌ</strong>, åÀòÇì ùÒÀôÈúÈéå éÉñÄéó ìÆ÷Çç</q>" (<a href="/tnk1/ktuv/mj/16-23.html">ôéøåè</a>)</li></ul> <p> <strong>äðáåï</strong> îùúîù áòé÷ø áìá, ùäåà î÷åí äîçùáåú: </p> <ul><li> <a class="psuq" href="/tnk1/prqim/t2802.htm#2">îùìé á2</a>: "<q class="psuq">ìÀäÇ÷ÀùÑÄéá ìÇçÈëÀîÈä àÈæÀðÆêÈ, úÌÇèÌÆä <strong>ìÄáÌÀêÈ ìÇúÌÀáåÌðÈä</strong></q>" (<a href="/tnk1/ktuv/mj/02-01.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2814.htm#33">îùìé éã33</a>: "<q class="psuq"><strong>áÌÀìÅá ðÈáåÉï</strong> úÌÈðåÌçÇ çÈëÀîÈä, åÌáÀ÷ÆøÆá ëÌÀñÄéìÄéí úÌÄåÌÈãÅòÇ</q>" (<a href="/tnk1/ktuv/mj/14-33.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2815.htm#14">îùìé èå14</a>: "<q class="psuq"><strong>ìÅá ðÈáåÉï</strong> éÀáÇ÷ÌÆùÑ ãÌÈòÇú, åôðé[åÌôÄé] ëÀñÄéìÄéí éÄøÀòÆä àÄåÌÆìÆú</q>" (<a href="/tnk1/ktuv/mj/15-14.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2818.htm#15">îùìé éç15</a>: "<q class="psuq"><strong>ìÅá ðÈáåÉï</strong> éÄ÷ÀðÆä ãÌÈòÇú, åÀàÉæÆï çÂëÈîÄéí úÌÀáÇ÷ÌÆùÑ ãÌÈòÇú</q>"</li><li> <a class="psuq" href="/tnk1/prqim/t2819.htm#8">îùìé éè8</a>: "<q class="psuq">÷ÉðÆä <strong>ìÌÅá</strong> àÉäÅá ðÇôÀùÑåÉ, ùÑÉîÅø <strong>úÌÀáåÌðÈä</strong> ìÄîÀöÉà èåÉá</q>" (<a href="/tnk1/ktuv/mj/18-15.html">ôéøåè</a>)</li></ul> <p>ùðé ôñå÷éí òì <strong>îéí òîå÷éí</strong> îøàéí ùäçëîä ÷ùåøä éåúø ìãéáåøéí, åäúáåðä ÷ùåøä éåúø ììá:</p> <ul><li> <a class="psuq" href="/tnk1/prqim/t2818.htm#4">îùìé éç4</a>: "<q class="psuq">îÇéÄí òÂîË÷ÌÄéí ãÌÄáÀøÅé <strong>ôÄé</strong> àÄéùÑ, ðÇçÇì ðÉáÅòÇ îÀ÷åÉø <strong>çÈëÀîÈä</strong></q>" (<a href="/tnk1/ktuv/mj/18-04.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2820.htm#5">îùìé ë5</a>: "<q class="psuq">îÇéÄí òÂîË÷ÌÄéí òÅöÈä <strong>áÀìÆá</strong> àÄéùÑ, åÀàÄéùÑ <strong>úÌÀáåÌðÈä</strong> éÄãÀìÆðÌÈä</q>" (<a href="/tnk1/ktuv/mj/20-05.html">ôéøåè</a>) </li></ul> <p>éùðí ëîä ôñå÷éí éåöàé-ãåôï, ùáäí äáéðä åäúáåðä ÷ùåøåú ìãéáåø àå ìùîéòä: <br /> </p> <ul><li> <a class="psuq" href="/tnk1/prqim/t2802.htm#3">îùìé á3</a>: "<q class="psuq">ëÌÄé àÄí <strong>ìÇáÌÄéðÈä úÄ÷ÀøÈà</strong>, ìÇúÌÀáåÌðÈä úÌÄúÌÅï ÷åÉìÆêÈ</q>" (<a href="/tnk1/ktuv/mj/02-03.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2805.htm#1">îùìé ä1</a>: "<q class="psuq">áÌÀðÄé, ìÀçÈëÀîÈúÄé äÇ÷ÀùÑÄéáÈä, <strong>ìÄúÀáåÌðÈúÄé äÇè àÈæÀðÆêÈ</strong></q>" (<a href="/tnk1/ktuv/mj/05-01.html">ôéøåè</a>)</li><li> <a class="psuq" href="/tnk1/prqim/t2810.htm#13">îùìé é13</a>: "<q class="psuq"><strong>áÌÀùÒÄôÀúÅé ðÈáåÉï</strong> úÌÄîÌÈöÅà <strong>çÈëÀîÈä</strong>, åÀùÑÅáÆè ìÀâÅå çÂñÇø ìÅá</q>" (<a href="/tnk1/ktuv/mj/10-13.html">ôéøåè</a>) </li></ul> <p>ééúëï ùäëååðä äéà, ùäàãí öøéê ì÷øåà åìùîåò àú äîñ÷ðåú ùàðùéí àçøéí äñé÷å, ëãé ìäøçéá åìäòîé÷ àú äúáåðä ùìå. <br /> </p> <p>äôñå÷éí îìîãéí àåúðå ìäáçéï áëùøåðåú äééçåãééí ìëì úìîéã: éù úìîéãéí ùìåîãéí ò"é ÷ìéèú îéãò îáçåõ, åìëï äí îùúîùéí áëìé äãéáåø åäùîéòä; åéù úìîéãéí ùìåîãéí ò"é îçùáä åäñ÷ú îñ÷ðåú, åìëï äí îùúîùéí áòé÷ø áìá.</p> <p class="future">åáãøê äñåã: "<q class="mfrj">åìîä àîø é÷ðä ãòú àöì ìá ðáåï, åàöì àåæï çëîéí àîø úá÷ù ãòú? äèòí ðìò"ã, ìôé ùçéìå÷ äùðé òéèøéï ùäãòú ðëìì îäí, äåà îï äáéðä îîù... åìëï ìá ðáåï, ä÷øåá àìéä, é÷ðä àåúä áð÷ì. àáì àåæï çëîéí öøéëä ìá÷ù àú äãòú áëåç ääîùëä, áâéï ãàáà èîéø åâðéæ áúåê àéîà, åéù ääôñ÷ áéðúééí...</q>" <small class="small"> (øî"ã ååàìé)</small>.</p> </div><!--cellcontent--> </div> </div><!--long--> </div><!--page--> <table class='inner_navigation'> <tr><td> &nbsp;<a href='18-00.html'>ôø÷ éç</a>&nbsp;&nbsp;&nbsp;&nbsp;ôñå÷&nbsp;&nbsp; &nbsp;<a href='18-01.html'>1</a>&nbsp; &nbsp;<a href='18-02.html'>2</a>&nbsp; &nbsp;<a href='18-03.html'>3</a>&nbsp; &nbsp;<a href='18-04.html'>4</a>&nbsp; &nbsp;<a href='18-05.html'>5</a>&nbsp; &nbsp;<a href='18-06.html'>6</a>&nbsp; &nbsp;<a href='18-07.html'>7</a>&nbsp; &nbsp;<a href='18-08.html'>8</a>&nbsp; &nbsp;<a href='18-09.html'>9</a>&nbsp; &nbsp;<a href='18-10.html'>10</a>&nbsp; &nbsp;<a href='18-11.html'>11</a>&nbsp; &nbsp;<a href='18-12.html'>12</a>&nbsp; &nbsp;<a href='18-13.html'>13</a>&nbsp; &nbsp;<a href='18-14.html'>14</a>&nbsp; &nbsp;<b>15</b>&nbsp; &nbsp;<a href='18-16.html'>16</a>&nbsp; &nbsp;<a href='18-17.html'>17</a>&nbsp; &nbsp;<a href='18-18.html'>18</a>&nbsp; &nbsp;<a href='18-19.html'>19</a>&nbsp; &nbsp;<a href='18-20.html'>20</a>&nbsp; &nbsp;<a href='18-21.html'>21</a>&nbsp; &nbsp;<a href='18-22.html'>22</a>&nbsp; &nbsp;<a href='18-23.html'>23</a>&nbsp; &nbsp;<a href='18-24.html'>24</a>&nbsp; </td></tr> <tr><td> <a href='00-00.html'><b>ñôø îùìé</b></a> &nbsp;&nbsp;&nbsp;ôø÷&nbsp;&nbsp; &nbsp;<a href='01-00.html'>à</a>&nbsp; &nbsp;<a href='02-00.html'>á</a>&nbsp; &nbsp;<a href='03-00.html'>â</a>&nbsp; &nbsp;<a href='04-00.html'>ã</a>&nbsp; &nbsp;<a href='05-00.html'>ä</a>&nbsp; &nbsp;<a href='06-00.html'>å</a>&nbsp; &nbsp;<a href='07-00.html'>æ</a>&nbsp; &nbsp;<a href='08-00.html'>ç</a>&nbsp; &nbsp;<a href='09-00.html'>è</a>&nbsp; &nbsp;<a href='10-00.html'>é</a>&nbsp; &nbsp;<a href='11-00.html'>éà</a>&nbsp; &nbsp;<a href='12-00.html'>éá</a>&nbsp; &nbsp;<a href='13-00.html'>éâ</a>&nbsp; &nbsp;<a href='14-00.html'>éã</a>&nbsp; &nbsp;<a href='15-00.html'>èå</a>&nbsp; &nbsp;<a href='16-00.html'>èæ</a>&nbsp; &nbsp;<a href='17-00.html'>éæ</a>&nbsp; &nbsp;<b>éç</b>&nbsp; &nbsp;<a href='19-00.html'>éè</a>&nbsp; &nbsp;<a href='20-00.html'>ë</a>&nbsp; &nbsp;<a href='21-00.html'>ëà</a>&nbsp; &nbsp;<a href='22-00.html'>ëá</a>&nbsp; &nbsp;<a href='23-00.html'>ëâ</a>&nbsp; &nbsp;<a href='24-00.html'>ëã</a>&nbsp; &nbsp;<a href='25-00.html'>ëä</a>&nbsp; &nbsp;<a href='26-00.html'>ëå</a>&nbsp; &nbsp;<a href='27-00.html'>ëæ</a>&nbsp; &nbsp;<a href='28-00.html'>ëç</a>&nbsp; &nbsp;<a href='29-00.html'>ëè</a>&nbsp; &nbsp;<a href='30-00.html'>ì</a>&nbsp; &nbsp;<a href='31-00.html'>ìà</a>&nbsp; </td></tr> </table><!-- inner_navigation --> </div><!--tokn--> <h2 id='tguvot'>úâåáåú</h2> <ul id='ultguvot'> <li></li> </ul><!--end--> <script type='text/javascript'>tguva(); txtit()</script> </div><!--pnim--> </body> </html>
lgpl-3.0
logsniffer/logsniffer
logsniffer-core/src/main/java/com/logsniffer/util/SniffMePopulator.java
3418
/******************************************************************************* * logsniffer, open source tool for viewing, monitoring and analysing log data. * Copyright (c) 2015 Scaleborn UG, www.scaleborn.com * * logsniffer 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. * * logsniffer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.logsniffer.util; import java.io.File; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import com.logsniffer.app.ContextProvider; import com.logsniffer.app.DataSourceAppConfig.DBInitIndicator; import com.logsniffer.app.LogSnifferHome; import com.logsniffer.model.LogSourceProvider; import com.logsniffer.model.file.RollingLogsSource; import com.logsniffer.reader.filter.FilteredLogEntryReader; import com.logsniffer.reader.log4j.Log4jTextReader; /** * Registers LogSniffers own logs as source. * * @author mbok * */ @Component public class SniffMePopulator implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private LogSnifferHome home; @Autowired private LogSourceProvider sourceProvider; @Autowired private DBInitIndicator dbInitIndicator; @Autowired private ContextProvider dummy; @SuppressWarnings({ "unchecked", "rawtypes" }) public void populate() { final RollingLogsSource myLogSource = new RollingLogsSource(); myLogSource.setPattern(new File(home.getHomeDir(), "logs/logsniffer.log").getPath()); myLogSource.setName("logsniffer's own log"); final Log4jTextReader reader = new Log4jTextReader(); reader.setFormatPattern("%d %-5p [%c] %m%n"); final Map<String, String> specifiersFieldMapping = new HashMap<>(); specifiersFieldMapping.put("d", "date"); specifiersFieldMapping.put("p", "priority"); specifiersFieldMapping.put("c", "category"); specifiersFieldMapping.put("m", "message"); reader.setSpecifiersFieldMapping(specifiersFieldMapping); myLogSource.setReader(new FilteredLogEntryReader(reader, null)); sourceProvider.createSource(myLogSource); logger.info("Created source for LogSniffer's own log: {}", myLogSource); } @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { if (dbInitIndicator.isNewSchema()) { try { populate(); } catch (final Exception e) { logger.error("Failed to create logsniffer's own log", e); } } } }
lgpl-3.0
sdukaka/sdukakaBlog
test_decorator.py
664
# -*- coding: utf-8 -*- __author__ = 'sdukaka' #只是为了测试一下装饰器的作用 decorator import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2015-3-25') now() def logger(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator @logger('DEBUG') def today(): print('2015-3-25') today() print(today.__name__)
lgpl-3.0
mihasighi/celia
celia-11.04/samples/ref/intlist-fold-splitV/mset/Makefile
140
all: $(CINV)/bin/frama-c-Celia.byte -celia -celia-cinv-opt mset.prop $(CINV)/samples/c/intlist-fold-splitV.c clean: rm *.shp pan* *.txt
lgpl-3.0
fysiskhund/mjEngineCPP
jni/util/mjGraphicCharObjectResource.h
1243
#ifndef MJGRAPHICCHAROBJECTRESOURCE_H #define MJGRAPHICCHAROBJECTRESOURCE_H #include <vector> #include "../extLibs/util/mjMultiPlatform.h" #include "../extLibs/utf8-utils/utf8-utils.h" #include "../extLibs/logger/mjLog.h" #include "mjResource.h" #include "mjFontResource.h" #include "../graphics/mjModelMesh.h" #include <ft2build.h> #include FT_FREETYPE_H namespace mjEngine { class mjGraphicCharObjectResource : public mjResource { public: // Resource object-specific notes: // In this case the modifier will say which font and size it is. // modifier = (fontResource->identifier) + (fontSize * 100). // So there can be only 100 fonts loaded at a time. S'ok. // ---- GLuint texture; std::vector<mjModelMesh*> customMesh; float charWidth; float charHeight; float manualRelocation = 0; float charRatio; float bitmapLeft; float bitmapTop; float advanceX; mjFontResource* fontResource; int fontSize; unsigned long charToRenderLong; mjGraphicCharObjectResource(mjFontResource* fontResource, int fontSize, unsigned long charToRenderLong); private: void GenerateTexture(); }; } #endif // MJGRAPHICCHAROBJECTRESOURCE_H
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/ehstorguids/X64/guids00000063.c
468
// Created file "Lib\src\ehstorguids\X64\guids" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(GUID_PROCESSOR_PERF_HISTORY, 0x7d24baa7, 0x0b84, 0x480f, 0x84, 0x0c, 0x1b, 0x07, 0x43, 0xc0, 0x0f, 0x5f);
lgpl-3.0
SOASTA/BlazeDS
modules/core/src/java/flex/management/DefaultMBeanServerLocator.java
2377
/************************************************************************* * * ADOBE CONFIDENTIAL * __________________ * * Copyright 2002 - 2007 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. **************************************************************************/ package flex.management; import java.util.ArrayList; import java.util.Iterator; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import flex.messaging.log.Log; import flex.messaging.log.LogCategories; /** * The default implementation of an MBeanServerLocator. This implementation * returns the first MBeanServer from the list returned by MBeanServerFactory.findMBeanServer(null). * If no MBeanServers have been instantiated, this class will request the creation * of an MBeanServer and return a reference to it. * * @author shodgson */ public class DefaultMBeanServerLocator implements MBeanServerLocator { private MBeanServer server; /** {@inheritDoc} */ public synchronized MBeanServer getMBeanServer() { if (server == null) { // Use the first MBeanServer we can find. ArrayList servers = MBeanServerFactory.findMBeanServer(null); if (servers.size() > 0) { Iterator iterator = servers.iterator(); server = (MBeanServer)iterator.next(); } else { // As a last resort, try to create a new MBeanServer. server = MBeanServerFactory.createMBeanServer(); } if (Log.isDebug()) Log.getLogger(LogCategories.MANAGEMENT_MBEANSERVER).debug("Using MBeanServer: " + server); } return server; } }
lgpl-3.0
jamesni/fonts-tweak-tool
fontstweak/util.py
2700
# -*- coding: utf-8 -*- # util.py # Copyright (C) 2012 Red Hat, Inc. # # Authors: # Akira TAGOH <[email protected]> # # This library is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext import gi import os.path import string from collections import OrderedDict from fontstweak import FontsTweak from gi.repository import Gtk def N_(s): return s class FontsTweakUtil: @classmethod def find_file(self, uifile): path = os.path.dirname(os.path.realpath(__file__)) f = os.path.join(path, 'data', uifile) if not os.path.isfile(f): f = os.path.join(path, '..', 'data', uifile) if not os.path.isfile(f): f = os.path.join(FontsTweak.UIPATH, uifile) return f @classmethod def create_builder(self, uifile): builder = Gtk.Builder() builder.set_translation_domain(FontsTweak.GETTEXT_PACKAGE) builder.add_from_file(self.find_file(uifile)) return builder @classmethod def translate_text(self, text, lang): try: self.translations except AttributeError: self.translations = {} if self.translations.has_key(lang) == False: self.translations[lang] = gettext.translation( domain=FontsTweak.GETTEXT_PACKAGE, localedir=FontsTweak.LOCALEDIR, languages=[lang.replace('-', '_')], fallback=True, codeset="utf8") return unicode(self.translations[lang].gettext(text), "utf8") @classmethod def get_language_list(self, default): dict = OrderedDict() if default == True: dict[''] = N_('Default') try: fd = open(self.find_file('locale-list'), 'r') except: raise RuntimeError, "Unable to open locale-list" while True: line = fd.readline() if not line: break tokens = string.split(line) lang = str(tokens[0]).split('.')[0].replace('_', '-') dict[lang] = string.join(tokens[3:], ' ') return dict
lgpl-3.0
accesio/AIOUSB
AIOUSB/deprecated/java/com/acces/aiousb/USB_AI16_Family.java
7364
/* * $RCSfile: USB_AI16_Family.java,v $ * $Date: 2009/12/23 22:45:27 $ * $Revision: 1.15 $ * jEdit:tabSize=4:indentSize=4:collapseFolds=1: */ package com.acces.aiousb; // {{{ imports import java.io.*; import java.util.*; // }}} /** * Class USB_AI16_Family represents a USB-AI16-family device, which encompasses the following product IDs:<br> * {@link USBDeviceManager#USB_AI16_16A USB_AI16_16A}, {@link USBDeviceManager#USB_AI16_16E USB_AI16_16E}, * {@link USBDeviceManager#USB_AI12_16A USB_AI12_16A}, {@link USBDeviceManager#USB_AI12_16 USB_AI12_16}, * {@link USBDeviceManager#USB_AI12_16E USB_AI12_16E}, {@link USBDeviceManager#USB_AI16_64MA USB_AI16_64MA}, * {@link USBDeviceManager#USB_AI16_64ME USB_AI16_64ME}, {@link USBDeviceManager#USB_AI12_64MA USB_AI12_64MA},<br> * {@link USBDeviceManager#USB_AI12_64M USB_AI12_64M}, {@link USBDeviceManager#USB_AI12_64ME USB_AI12_64ME}, * {@link USBDeviceManager#USB_AI16_32A USB_AI16_32A}, {@link USBDeviceManager#USB_AI16_32E USB_AI16_32E}, * {@link USBDeviceManager#USB_AI12_32A USB_AI12_32A}, {@link USBDeviceManager#USB_AI12_32 USB_AI12_32}, * {@link USBDeviceManager#USB_AI12_32E USB_AI12_32E}, {@link USBDeviceManager#USB_AI16_64A USB_AI16_64A},<br> * {@link USBDeviceManager#USB_AI16_64E USB_AI16_64E}, {@link USBDeviceManager#USB_AI12_64A USB_AI12_64A}, * {@link USBDeviceManager#USB_AI12_64 USB_AI12_64}, {@link USBDeviceManager#USB_AI12_64E USB_AI12_64E}, * {@link USBDeviceManager#USB_AI16_96A USB_AI16_96A}, {@link USBDeviceManager#USB_AI16_96E USB_AI16_96E}, * {@link USBDeviceManager#USB_AI12_96A USB_AI12_96A}, {@link USBDeviceManager#USB_AI12_96 USB_AI12_96},<br> * {@link USBDeviceManager#USB_AI12_96E USB_AI12_96E}, {@link USBDeviceManager#USB_AI16_128A USB_AI16_128A}, * {@link USBDeviceManager#USB_AI16_128E USB_AI16_128E}, {@link USBDeviceManager#USB_AI12_128A USB_AI12_128A}, * {@link USBDeviceManager#USB_AI12_128 USB_AI12_128}, {@link USBDeviceManager#USB_AI12_128E USB_AI12_128E}.<br><br> * Instances of class <i>USB_AI16_Family</i> are automatically created by the USB device manager when they are * detected on the bus. You should use one of the <i>{@link USBDeviceManager}</i> search methods, such as * <i>{@link USBDeviceManager#getDeviceByProductID( int productID ) USBDeviceManager.getDeviceByProductID()}</i>, * to obtain a reference to a <i>USB_AI16_Family</i> instance. You can then cast the <i>{@link USBDevice}</i> * reference obtained from one of those methods to a <i>USB_AI16_Family</i> and make use of this class' methods, like so: * <pre>USBDevice[] devices = deviceManager.getDeviceByProductID( USBDeviceManager.USB_AI12_32A, USBDeviceManager.USB_AI12_32E ); *if( devices.length > 0 ) * USB_AI16_Family device = ( USB_AI16_Family ) devices[ 0 ];</pre> */ public class USB_AI16_Family extends USBDevice { // {{{ static members private static int[] supportedProductIDs; static { supportedProductIDs = new int[] { USBDeviceManager.USB_AI16_16A , USBDeviceManager.USB_AI16_16E , USBDeviceManager.USB_AI12_16A , USBDeviceManager.USB_AI12_16 , USBDeviceManager.USB_AI12_16E , USBDeviceManager.USB_AI16_64MA , USBDeviceManager.USB_AI16_64ME , USBDeviceManager.USB_AI12_64MA , USBDeviceManager.USB_AI12_64M , USBDeviceManager.USB_AI12_64ME , USBDeviceManager.USB_AI16_32A , USBDeviceManager.USB_AI16_32E , USBDeviceManager.USB_AI12_32A , USBDeviceManager.USB_AI12_32 , USBDeviceManager.USB_AI12_32E , USBDeviceManager.USB_AI16_64A , USBDeviceManager.USB_AI16_64E , USBDeviceManager.USB_AI12_64A , USBDeviceManager.USB_AI12_64 , USBDeviceManager.USB_AI12_64E , USBDeviceManager.USB_AI16_96A , USBDeviceManager.USB_AI16_96E , USBDeviceManager.USB_AI12_96A , USBDeviceManager.USB_AI12_96 , USBDeviceManager.USB_AI12_96E , USBDeviceManager.USB_AI16_128A , USBDeviceManager.USB_AI16_128E , USBDeviceManager.USB_AI12_128A , USBDeviceManager.USB_AI12_128 , USBDeviceManager.USB_AI12_128E }; // supportedProductIDs[] Arrays.sort( supportedProductIDs ); } // static // }}} // {{{ protected members protected AnalogInputSubsystem analogInputSubsystem; protected DigitalIOSubsystem digitalIOSubsystem; protected CounterSubsystem counterSubsystem; // }}} // {{{ protected methods protected USB_AI16_Family( int productID, int deviceIndex ) { super( productID, deviceIndex ); if( ! isSupportedProductID( productID ) ) throw new IllegalArgumentException( "Invalid product ID: " + productID ); analogInputSubsystem = new AnalogInputSubsystem( this ); digitalIOSubsystem = new DigitalIOSubsystem( this ); counterSubsystem = new CounterSubsystem( this ); } // USB_AI16_Family() // }}} // {{{ public methods /* * properties */ /** * Gets an array of all the product names supported by this USB device family. * <br><br>Although this method is <i>static</i>, an instance of USBDeviceManager must be created * and be "open" for use before this method can be used. This stipulation is imposed because the * underlying library must be initialized in order for product name/ID lookups to succeed, and that * initialization occurs only when an instance of USBDeviceManager is created and its * <i>{@link USBDeviceManager#open() open()}</i> method is called. * @return An array of product names, sorted in ascending order of product ID. */ public static String[] getSupportedProductNames() { return USBDeviceManager.productIDToName( supportedProductIDs ); } // getSupportedProductNames() /** * Gets an array of all the product IDs supported by this USB device family. * @return An array of product IDs, sorted in ascending order. */ public static int[] getSupportedProductIDs() { return supportedProductIDs.clone(); } // getSupportedProductIDs() /** * Tells if a given product ID is supported by this USB device family. * @param productID the product ID to check. * @return <i>True</i> if the given product ID is supported by this USB device family; otherwise, <i>false</i>. */ public static boolean isSupportedProductID( int productID ) { return Arrays.binarySearch( supportedProductIDs, productID ) >= 0; } // isSupportedProductID() /** * Prints the properties of this device and all of its subsystems. Mainly useful for diagnostic purposes. * @param stream the print stream where properties will be printed. * @return The print stream. */ public PrintStream print( PrintStream stream ) { super.print( stream ); analogInputSubsystem.print( stream ); digitalIOSubsystem.print( stream ); counterSubsystem.print( stream ); return stream; } // print() /* * subsystems */ /** * Gets a reference to the analog input subsystem of this device. * @return A reference to the analog input subsystem. */ public AnalogInputSubsystem adc() { return analogInputSubsystem; } // adc() /** * Gets a reference to the digital I/O subsystem of this device. * @return A reference to the digital I/O subsystem. */ public DigitalIOSubsystem dio() { return digitalIOSubsystem; } // dio() /** * Gets a reference to the counter/timer subsystem of this device. * @return A reference to the counter/timer subsystem. */ public CounterSubsystem ctr() { return counterSubsystem; } // ctr() // }}} } // class USB_AI16_Family /* end of file */
lgpl-3.0
aamaricci/SciFortran
src/lapack/dptts2.f
2821
SUBROUTINE DPTTS2( N, NRHS, D, E, B, LDB ) * * -- LAPACK routine (version 3.3.1) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * -- April 2011 -- * * .. Scalar Arguments .. INTEGER LDB, N, NRHS * .. * .. Array Arguments .. DOUBLE PRECISION B( LDB, * ), D( * ), E( * ) * .. * * Purpose * ======= * * DPTTS2 solves a tridiagonal system of the form * A * X = B * using the L*D*L**T factorization of A computed by DPTTRF. D is a * diagonal matrix specified in the vector D, L is a unit bidiagonal * matrix whose subdiagonal is specified in the vector E, and X and B * are N by NRHS matrices. * * Arguments * ========= * * N (input) INTEGER * The order of the tridiagonal matrix A. N >= 0. * * NRHS (input) INTEGER * The number of right hand sides, i.e., the number of columns * of the matrix B. NRHS >= 0. * * D (input) DOUBLE PRECISION array, dimension (N) * The n diagonal elements of the diagonal matrix D from the * L*D*L**T factorization of A. * * E (input) DOUBLE PRECISION array, dimension (N-1) * The (n-1) subdiagonal elements of the unit bidiagonal factor * L from the L*D*L**T factorization of A. E can also be regarded * as the superdiagonal of the unit bidiagonal factor U from the * factorization A = U**T*D*U. * * B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS) * On entry, the right hand side vectors B for the system of * linear equations. * On exit, the solution vectors, X. * * LDB (input) INTEGER * The leading dimension of the array B. LDB >= max(1,N). * * ===================================================================== * * .. Local Scalars .. INTEGER I, J * .. * .. External Subroutines .. EXTERNAL DSCAL * .. * .. Executable Statements .. * * Quick return if possible * IF( N.LE.1 ) THEN IF( N.EQ.1 ) $ CALL DSCAL( NRHS, 1.D0 / D( 1 ), B, LDB ) RETURN END IF * * Solve A * X = B using the factorization A = L*D*L**T, * overwriting each right hand side vector with its solution. * DO 30 J = 1, NRHS * * Solve L * x = b. * DO 10 I = 2, N B( I, J ) = B( I, J ) - B( I-1, J )*E( I-1 ) 10 CONTINUE * * Solve D * L**T * x = b. * B( N, J ) = B( N, J ) / D( N ) DO 20 I = N - 1, 1, -1 B( I, J ) = B( I, J ) / D( I ) - B( I+1, J )*E( I ) 20 CONTINUE 30 CONTINUE * RETURN * * End of DPTTS2 * END
lgpl-3.0
revelator/Revelation-Engine
neo/renderer/RenderWorld.h
20003
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code 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. Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #ifndef __RENDERWORLD_H__ #define __RENDERWORLD_H__ /* =============================================================================== Render World =============================================================================== */ #define PROC_FILE_EXT "proc" #define PROC_FILE_ID "mapProcFile003" // shader parms const int MAX_GLOBAL_SHADER_PARMS = 12; const int SHADERPARM_RED = 0; const int SHADERPARM_GREEN = 1; const int SHADERPARM_BLUE = 2; const int SHADERPARM_ALPHA = 3; const int SHADERPARM_TIMESCALE = 3; const int SHADERPARM_TIMEOFFSET = 4; const int SHADERPARM_DIVERSITY = 5; // random between 0.0 and 1.0 for some effects (muzzle flashes, etc) const int SHADERPARM_MODE = 7; // for selecting which shader passes to enable const int SHADERPARM_TIME_OF_DEATH = 7; // for the monster skin-burn-away effect enable and time offset // model parms const int SHADERPARM_MD5_SKINSCALE = 8; // for scaling vertex offsets on md5 models (jack skellington effect) const int SHADERPARM_MD3_FRAME = 8; const int SHADERPARM_MD3_LASTFRAME = 9; const int SHADERPARM_MD3_BACKLERP = 10; const int SHADERPARM_BEAM_END_X = 8; // for _beam models const int SHADERPARM_BEAM_END_Y = 9; const int SHADERPARM_BEAM_END_Z = 10; const int SHADERPARM_BEAM_WIDTH = 11; const int SHADERPARM_SPRITE_WIDTH = 8; const int SHADERPARM_SPRITE_HEIGHT = 9; const int SHADERPARM_PARTICLE_STOPTIME = 8; // don't spawn any more particles after this time // guis const int MAX_RENDERENTITY_GUI = 3; typedef bool(*deferredEntityCallback_t)(renderEntity_s *, const renderView_s *); typedef struct renderEntity_s { idRenderModel *hModel; // this can only be null if callback is set int entityNum; int bodyId; // Entities that are expensive to generate, like skeletal models, can be // deferred until their bounds are found to be in view, in the frustum // of a shadowing light that is in view, or contacted by a trace / overlay test. // This is also used to do visual cueing on items in the view // The renderView may be NULL if the callback is being issued for a non-view related // source. // The callback function should clear renderEntity->callback if it doesn't // want to be called again next time the entity is referenced (ie, if the // callback has now made the entity valid until the next updateEntity) idBounds bounds; // only needs to be set for deferred models and md5s deferredEntityCallback_t callback; void *callbackData; // used for whatever the callback wants // player bodies and possibly player shadows should be suppressed in views from // that player's eyes, but will show up in mirrors and other subviews // security cameras could suppress their model in their subviews if we add a way // of specifying a view number for a remoteRenderMap view int suppressSurfaceInViewID; int suppressShadowInViewID; // world models for the player and weapons will not cast shadows from view weapon // muzzle flashes int suppressShadowInLightID; // if non-zero, the surface and shadow (if it casts one) // will only show up in the specific view, ie: player weapons int allowSurfaceInViewID; // positioning // axis rotation vectors must be unit length for many // R_LocalToGlobal functions to work, so don't scale models! // axis vectors are [0] = forward, [1] = left, [2] = up idVec3 origin; idMat3 axis; // texturing const idMaterial *customShader; // if non-0, all surfaces will use this const idMaterial *referenceShader; // used so flares can reference the proper light shader const idDeclSkin *customSkin; // 0 for no remappings class idSoundEmitter *referenceSound; // for shader sound tables, allowing effects to vary with sounds float shaderParms[MAX_ENTITY_SHADER_PARMS]; // can be used in any way by shader or model generation // networking: see WriteGUIToSnapshot / ReadGUIFromSnapshot class idUserInterface *gui[MAX_RENDERENTITY_GUI]; struct renderView_s *remoteRenderView; // any remote camera surfaces will use this int numJoints; idJointMat *joints; // array of joints that will modify vertices. // NULL if non-deformable model. NOT freed by renderer float modelDepthHack; // squash depth range so particle effects don't clip into walls // options to override surface shader flags (replace with material parameters?) bool noSelfShadow; // cast shadows onto other objects,but not self bool noShadow; // no shadow at all bool noDynamicInteractions; // don't create any light / shadow interactions after // the level load is completed. This is a performance hack // for the gigantic outdoor meshes in the monorail map, so // all the lights in the moving monorail don't touch the meshes bool weaponDepthHack; // squash depth range so view weapons don't poke into walls // this automatically implies noShadow int forceUpdate; // force an update (NOTE: not a bool to keep this struct a multiple of 4 bytes) int timeGroup; int xrayIndex; } renderEntity_t; typedef struct renderLight_s { idMat3 axis; // rotation vectors, must be unit length idVec3 origin; // if non-zero, the light will not show up in the specific view, // which may be used if we want to have slightly different muzzle // flash lights for the player and other views int suppressLightInViewID; // if non-zero, the light will only show up in the specific view // which can allow player gun gui lights and such to not effect everyone int allowLightInViewID; // I am sticking the four bools together so there are no unused gaps in // the padded structure, which could confuse the memcmp that checks for redundant // updates bool noShadows; // (should we replace this with material parameters on the shader?) bool noSpecular; // (should we replace this with material parameters on the shader?) bool pointLight; // otherwise a projection light (should probably invert the sense of this, because points are way more common) bool parallel; // lightCenter gives the direction to the light at infinity idVec3 lightRadius; // xyz radius for point lights idVec3 lightCenter; // offset the lighting direction for shading and // shadows, relative to origin // frustum definition for projected lights, all reletive to origin // FIXME: we should probably have real plane equations here, and offer // a helper function for conversion from this format idVec3 target; idVec3 right; idVec3 up; idVec3 start; idVec3 end; // Dmap will generate an optimized shadow volume named _prelight_<lightName> // for the light against all the _area* models in the map. The renderer will // ignore this value if the light has been moved after initial creation idRenderModel *prelightModel; // muzzle flash lights will not cast shadows from player and weapon world models int lightId; const idMaterial *shader; // NULL = either lights/defaultPointLight or lights/defaultProjectedLight float shaderParms[MAX_ENTITY_SHADER_PARMS]; // can be used in any way by shader idSoundEmitter *referenceSound; // for shader sound tables, allowing effects to vary with sounds } renderLight_t; typedef struct renderView_s { // player views will set this to a non-zero integer for model suppress / allow // subviews (mirrors, cameras, etc) will always clear it to zero int viewID; // sized from 0 to SCREEN_WIDTH / SCREEN_HEIGHT (640/480), not actual resolution int x, y, width, height; float fov_x, fov_y; idVec3 vieworg; idMat3 viewaxis; // transformation matrix, view looks down the positive X axis bool cramZNear; // for cinematics, we want to set ZNear much lower bool forceUpdate; // for an update // time in milliseconds for shader effects and other time dependent rendering issues int time; float shaderParms[MAX_GLOBAL_SHADER_PARMS]; // can be used in any way by shader const idMaterial *globalMaterial; // used to override everything draw } renderView_t; // exitPortal_t is returned by idRenderWorld::GetPortal() typedef struct { int areas[2]; // areas connected by this portal const idWinding *w; // winding points have counter clockwise ordering seen from areas[0] int blockingBits; // PS_BLOCK_VIEW, PS_BLOCK_AIR, etc qhandle_t portalHandle; } exitPortal_t; // guiPoint_t is returned by idRenderWorld::GuiTrace() typedef struct { float x, y; // 0.0 to 1.0 range if trace hit a gui, otherwise -1 int guiId; // id of gui ( 0, 1, or 2 ) that the trace happened against } guiPoint_t; // modelTrace_t is for tracing vs. visual geometry typedef struct modelTrace_s { float fraction; // fraction of trace completed idVec3 point; // end point of trace in global space idVec3 normal; // hit triangle normal vector in global space const idMaterial *material; // material of hit surface const renderEntity_t *entity; // render entity that was hit int jointNumber; // md5 joint nearest to the hit triangle } modelTrace_t; static const int NUM_PORTAL_ATTRIBUTES = 3; typedef enum { PS_BLOCK_NONE = 0, PS_BLOCK_VIEW = 1, PS_BLOCK_LOCATION = 2, // game map location strings often stop in hallways PS_BLOCK_AIR = 4, // windows between pressurized and unpresurized areas PS_BLOCK_ALL = (1 << NUM_PORTAL_ATTRIBUTES) - 1 } portalConnection_t; class idRenderWorld { public: virtual ~idRenderWorld() {}; // The same render world can be reinitialized as often as desired // a NULL or empty mapName will create an empty, single area world virtual bool InitFromMap(const char *mapName) = 0; //-------------- Entity and Light Defs ----------------- // entityDefs and lightDefs are added to a given world to determine // what will be drawn for a rendered scene. Most update work is defered // until it is determined that it is actually needed for a given view. virtual qhandle_t AddEntityDef(const renderEntity_t *re) = 0; virtual void UpdateEntityDef(qhandle_t entityHandle, const renderEntity_t *re) = 0; virtual void FreeEntityDef(qhandle_t entityHandle) = 0; virtual const renderEntity_t *GetRenderEntity(qhandle_t entityHandle) const = 0; virtual qhandle_t AddLightDef(const renderLight_t *rlight) = 0; virtual void UpdateLightDef(qhandle_t lightHandle, const renderLight_t *rlight) = 0; virtual void FreeLightDef(qhandle_t lightHandle) = 0; virtual const renderLight_t *GetRenderLight(qhandle_t lightHandle) const = 0; // Force the generation of all light / surface interactions at the start of a level // If this isn't called, they will all be dynamically generated virtual void GenerateAllInteractions() = 0; // returns true if this area model needs portal sky to draw virtual bool CheckAreaForPortalSky(int areaNum) = 0; //-------------- Decals and Overlays ----------------- // Creates decals on all world surfaces that the winding projects onto. // The projection origin should be infront of the winding plane. // The decals are projected onto world geometry between the winding plane and the projection origin. // The decals are depth faded from the winding plane to a certain distance infront of the // winding plane and the same distance from the projection origin towards the winding. virtual void ProjectDecalOntoWorld(const idFixedWinding &winding, const idVec3 &projectionOrigin, const bool parallel, const float fadeDepth, const idMaterial *material, const int startTime) = 0; // Creates decals on static models. virtual void ProjectDecal(qhandle_t entityHandle, const idFixedWinding &winding, const idVec3 &projectionOrigin, const bool parallel, const float fadeDepth, const idMaterial *material, const int startTime) = 0; // Creates overlays on dynamic models. virtual void ProjectOverlay(qhandle_t entityHandle, const idPlane localTextureAxis[2], const idMaterial *material) = 0; // Removes all decals and overlays from the given entity def. virtual void RemoveDecals(qhandle_t entityHandle) = 0; //-------------- Scene Rendering ----------------- // some calls to material functions use the current renderview time when servicing cinematics. this function // ensures that any parms accessed (such as time) are properly set. virtual void SetRenderView(const renderView_t *renderView) = 0; // rendering a scene may actually render multiple subviews for mirrors and portals, and // may render composite textures for gui console screens and light projections // It would also be acceptable to render a scene multiple times, for "rear view mirrors", etc virtual void RenderScene(const renderView_t *renderView) = 0; //-------------- Portal Area Information ----------------- // returns the number of portals virtual int NumPortals(void) const = 0; // returns 0 if no portal contacts the bounds // This is used by the game to identify portals that are contained // inside doors, so the connection between areas can be topologically // terminated when the door shuts. virtual qhandle_t FindPortal(const idBounds &b) const = 0; // doors explicitly close off portals when shut // multiple bits can be set to block multiple things, ie: ( PS_VIEW | PS_LOCATION | PS_AIR ) virtual void SetPortalState(qhandle_t portal, int blockingBits) = 0; virtual int GetPortalState(qhandle_t portal) = 0; // returns true only if a chain of portals without the given connection bits set // exists between the two areas (a door doesn't separate them, etc) virtual bool AreasAreConnected(int areaNum1, int areaNum2, portalConnection_t connection) = 0; // returns the number of portal areas in a map, so game code can build information // tables for the different areas virtual int NumAreas(void) const = 0; // Will return -1 if the point is not in an area, otherwise // it will return 0 <= value < NumAreas() virtual int PointInArea(const idVec3 &point) const = 0; // fills the *areas array with the numbers of the areas the bounds cover // returns the total number of areas the bounds cover virtual int BoundsInAreas(const idBounds &bounds, int *areas, int maxAreas) const = 0; // Used by the sound system to do area flowing virtual int NumPortalsInArea(int areaNum) = 0; // returns one portal from an area virtual exitPortal_t GetPortal(int areaNum, int portalNum) = 0; //-------------- Tracing ----------------- // Checks a ray trace against any gui surfaces in an entity, returning the // fraction location of the trace on the gui surface, or -1,-1 if no hit. // This doesn't do any occlusion testing, simply ignoring non-gui surfaces. // start / end are in global world coordinates. virtual guiPoint_t GuiTrace(qhandle_t entityHandle, const idVec3 &start, const idVec3 &end) const = 0; // Traces vs the render model, possibly instantiating a dynamic version, and returns true if something was hit virtual bool ModelTrace(modelTrace_t &trace, qhandle_t entityHandle, const idVec3 &start, const idVec3 &end, const float radius) const = 0; // Traces vs the whole rendered world. FIXME: we need some kind of material flags. virtual bool Trace(modelTrace_t &trace, const idVec3 &start, const idVec3 &end, const float radius, bool skipDynamic = true, bool skipPlayer = false) const = 0; // Traces vs the world model bsp tree. virtual bool FastWorldTrace(modelTrace_t &trace, const idVec3 &start, const idVec3 &end) const = 0; //-------------- Demo Control ----------------- // Writes a loadmap command to the demo, and clears archive counters. virtual void StartWritingDemo(idDemoFile *demo) = 0; virtual void StopWritingDemo() = 0; // Returns true when demoRenderView has been filled in. // adds/updates/frees entityDefs and lightDefs based on the current demo file // and returns the renderView to be used to render this frame. // a demo file may need to be advanced multiple times if the framerate // is less than 30hz // demoTimeOffset will be set if a new map load command was processed before // the next renderScene virtual bool ProcessDemoCommand(idDemoFile *readDemo, renderView_t *demoRenderView, int *demoTimeOffset) = 0; // this is used to regenerate all interactions ( which is currently only done during influences ), there may be a less // expensive way to do it virtual void RegenerateWorld() = 0; //-------------- Debug Visualization ----------------- // Line drawing for debug visualization virtual void DebugClearLines(int time) = 0; // a time of 0 will clear all lines and text virtual void DebugLine(const idVec4 &color, const idVec3 &start, const idVec3 &end, const int lifetime = 0, const bool depthTest = false) = 0; virtual void DebugArrow(const idVec4 &color, const idVec3 &start, const idVec3 &end, int size, const int lifetime = 0) = 0; virtual void DebugWinding(const idVec4 &color, const idWinding &w, const idVec3 &origin, const idMat3 &axis, const int lifetime = 0, const bool depthTest = false) = 0; virtual void DebugCircle(const idVec4 &color, const idVec3 &origin, const idVec3 &dir, const float radius, const int numSteps, const int lifetime = 0, const bool depthTest = false) = 0; virtual void DebugSphere(const idVec4 &color, const idSphere &sphere, const int lifetime = 0, bool depthTest = false) = 0; virtual void DebugBounds(const idVec4 &color, const idBounds &bounds, const idVec3 &org = vec3_origin, const int lifetime = 0) = 0; virtual void DebugBox(const idVec4 &color, const idBox &box, const int lifetime = 0) = 0; virtual void DebugFrustum(const idVec4 &color, const idFrustum &frustum, const bool showFromOrigin = false, const int lifetime = 0) = 0; virtual void DebugCone(const idVec4 &color, const idVec3 &apex, const idVec3 &dir, float radius1, float radius2, const int lifetime = 0) = 0; virtual void DebugAxis(const idVec3 &origin, const idMat3 &axis) = 0; // Polygon drawing for debug visualization. virtual void DebugClearPolygons(int time) = 0; // a time of 0 will clear all polygons virtual void DebugPolygon(const idVec4 &color, const idWinding &winding, const int lifeTime = 0, const bool depthTest = false) = 0; // Text drawing for debug visualization. virtual void DrawText(const char *text, const idVec3 &origin, float scale, const idVec4 &color, const idMat3 &viewAxis, const int align = 1, const int lifetime = 0, bool depthTest = false) = 0; }; #endif /* !__RENDERWORLD_H__ */
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/ehstorguids/guids0000042C.c
475
// Created file "Lib\src\ehstorguids\guids" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(PKEY_DeviceInterface_PrinterDriverName, 0xafc47170, 0x14f5, 0x498c, 0x8f, 0x30, 0xb0, 0xd1, 0x9b, 0xe4, 0x49, 0xc6);
lgpl-3.0
RuedigerMoeller/kontraktor
modules/kontraktor-http/src/main/java/org/nustaq/kontraktor/remoting/http/servlet/ServletKHttpExchangeImpl.java
1761
package org.nustaq.kontraktor.remoting.http.servlet; import org.nustaq.kontraktor.remoting.http.KHttpExchange; import org.nustaq.kontraktor.util.Log; import javax.servlet.AsyncContext; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * Created by ruedi on 19.06.17. */ public class ServletKHttpExchangeImpl implements KHttpExchange { KontraktorServlet servlet; AsyncContext aCtx; public ServletKHttpExchangeImpl(KontraktorServlet servlet, AsyncContext aCtx) { this.servlet = servlet; this.aCtx = aCtx; } @Override public void endExchange() { aCtx.complete(); } @Override public void setResponseContentLength(int length) { aCtx.getResponse().setContentLength(length); } @Override public void setResponseCode(int i) { ((HttpServletResponse) aCtx.getResponse()).setStatus(i); } @Override public void send(String s) { try { aCtx.getResponse().setCharacterEncoding("UTF-8"); aCtx.getResponse().setContentType("text/html; charset=utf-8"); aCtx.getResponse().getWriter().write(s); } catch (IOException e) { Log.Warn(this,e); } } @Override public void send(byte[] b) { try { send(new String(b,"UTF-8")); } catch (UnsupportedEncodingException e) { Log.Error(this,e); } } @Override public void sendAuthResponse(byte[] response, String sessionId) { try { send(new String(response,"UTF-8")); aCtx.complete(); } catch (UnsupportedEncodingException e) { Log.Error(this,e); } } }
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/mobile/rori/kobola_pitboss.lua
1179
kobola_pitboss = Creature:new { objectName = "@mob/creature_names:kobola_pitboss", socialGroup = "kobola", pvpFaction = "kobola", faction = "kobola", level = 22, chanceHit = 0.33, damageMin = 190, damageMax = 200, baseXp = 2219, baseHAM = 5000, baseHAMmax = 6100, armor = 0, resists = {30,30,0,-1,0,0,-1,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + KILLER, optionsBitmask = 128, diet = HERBIVORE, templates = { "object/mobile/dressed_kobola_pitboss_trandoshan_male_01.iff", "object/mobile/dressed_kobola_pitboss_trandoshan_female_01.iff"}, lootGroups = { { groups = { {group = "junk", chance = 2400000}, {group = "tailor_components", chance = 2000000}, {group = "loot_kit_parts", chance = 2000000}, {group = "kobola_common", chance = 3600000} }, lootChance = 2600000 } }, weapons = {"pirate_weapons_light"}, conversationTemplate = "", attacks = merge(brawlermaster,pistoleermaster) } CreatureTemplates:addCreatureTemplate(kobola_pitboss, "kobola_pitboss")
lgpl-3.0
spark/firmware
hal/src/template/wlan_hal.cpp
3455
/** ****************************************************************************** * @file wlan_hal.c * @author Matthew McGowan * @version V1.0.0 * @date 27-Sept-2014 * @brief ****************************************************************************** Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 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 library; if not, see <http://www.gnu.org/licenses/>. ****************************************************************************** */ #include "wlan_hal.h" uint32_t HAL_NET_SetNetWatchDog(uint32_t timeOutInMS) { return 0; } int wlan_clear_credentials() { return 1; } int wlan_has_credentials() { return 1; } int wlan_connect_init() { return 0; } wlan_result_t wlan_activate() { return 0; } wlan_result_t wlan_deactivate() { return 0; } bool wlan_reset_credentials_store_required() { return false; } wlan_result_t wlan_reset_credentials_store() { return 0; } /** * Do what is needed to finalize the connection. * @return */ wlan_result_t wlan_connect_finalize() { // enable connection from stored profiles return 0; } void Set_NetApp_Timeout(void) { } wlan_result_t wlan_disconnect_now() { return 0; } wlan_result_t wlan_connected_rssi(char* ssid) { return 0; } int wlan_connected_info(void* reserved, wlan_connected_info_t* inf, void* reserved1) { return -1; } int wlan_set_credentials(WLanCredentials* c) { return -1; } void wlan_smart_config_init() { } bool wlan_smart_config_finalize() { return false; } void wlan_smart_config_cleanup() { } void wlan_setup() { } void wlan_set_error_count(uint32_t errorCount) { } int wlan_fetch_ipconfig(WLanConfig* config) { return -1; } void SPARK_WLAN_SmartConfigProcess() { } void wlan_connect_cancel(bool called_from_isr) { } /** * Sets the IP source - static or dynamic. */ void wlan_set_ipaddress_source(IPAddressSource source, bool persist, void* reserved) { } /** * Sets the IP Addresses to use when the device is in static IP mode. * @param device * @param netmask * @param gateway * @param dns1 * @param dns2 * @param reserved */ void wlan_set_ipaddress(const HAL_IPAddress* device, const HAL_IPAddress* netmask, const HAL_IPAddress* gateway, const HAL_IPAddress* dns1, const HAL_IPAddress* dns2, void* reserved) { } IPAddressSource wlan_get_ipaddress_source(void* reserved) { return DYNAMIC_IP; } int wlan_get_ipaddress(IPConfig* conf, void* reserved) { return -1; } int wlan_scan(wlan_scan_result_t callback, void* cookie) { return -1; } int wlan_restart(void* reserved) { return -1; } int wlan_get_hostname(char* buf, size_t len, void* reserved) { // Unsupported if (buf) { buf[0] = '\0'; } return -1; } int wlan_set_hostname(const char* hostname, void* reserved) { // Unsupported return -1; }
lgpl-3.0
pcolby/libqtaws
src/support/resolvecaserequest_p.h
1387
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_RESOLVECASEREQUEST_P_H #define QTAWS_RESOLVECASEREQUEST_P_H #include "supportrequest_p.h" #include "resolvecaserequest.h" namespace QtAws { namespace Support { class ResolveCaseRequest; class ResolveCaseRequestPrivate : public SupportRequestPrivate { public: ResolveCaseRequestPrivate(const SupportRequest::Action action, ResolveCaseRequest * const q); ResolveCaseRequestPrivate(const ResolveCaseRequestPrivate &other, ResolveCaseRequest * const q); private: Q_DECLARE_PUBLIC(ResolveCaseRequest) }; } // namespace Support } // namespace QtAws #endif
lgpl-3.0
pcolby/libqtaws
src/lexmodelbuildingservice/getbuiltinintentresponse_p.h
1381
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_GETBUILTININTENTRESPONSE_P_H #define QTAWS_GETBUILTININTENTRESPONSE_P_H #include "lexmodelbuildingserviceresponse_p.h" namespace QtAws { namespace LexModelBuildingService { class GetBuiltinIntentResponse; class GetBuiltinIntentResponsePrivate : public LexModelBuildingServiceResponsePrivate { public: explicit GetBuiltinIntentResponsePrivate(GetBuiltinIntentResponse * const q); void parseGetBuiltinIntentResponse(QXmlStreamReader &xml); private: Q_DECLARE_PUBLIC(GetBuiltinIntentResponse) Q_DISABLE_COPY(GetBuiltinIntentResponsePrivate) }; } // namespace LexModelBuildingService } // namespace QtAws #endif
lgpl-3.0
pcolby/libqtaws
src/mediaconnect/mediaconnectresponse.cpp
2716
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "mediaconnectresponse.h" #include "mediaconnectresponse_p.h" #include <QDebug> #include <QXmlStreamReader> namespace QtAws { namespace MediaConnect { /*! * \class QtAws::MediaConnect::MediaConnectResponse * \brief The MediaConnectResponse class provides an interface for MediaConnect responses. * * \inmodule QtAwsMediaConnect */ /*! * Constructs a MediaConnectResponse object with parent \a parent. */ MediaConnectResponse::MediaConnectResponse(QObject * const parent) : QtAws::Core::AwsAbstractResponse(new MediaConnectResponsePrivate(this), parent) { } /*! * \internal * Constructs a MediaConnectResponse object with private implementation \a d, * and parent \a parent. * * This overload allows derived classes to provide their own private class * implementation that inherits from MediaConnectResponsePrivate. */ MediaConnectResponse::MediaConnectResponse(MediaConnectResponsePrivate * const d, QObject * const parent) : QtAws::Core::AwsAbstractResponse(d, parent) { } /*! * \reimp */ void MediaConnectResponse::parseFailure(QIODevice &response) { //Q_D(MediaConnectResponse); Q_UNUSED(response); /*QXmlStreamReader xml(&response); if (xml.readNextStartElement()) { if (xml.name() == QLatin1String("ErrorResponse")) { d->parseErrorResponse(xml); } else { qWarning() << "ignoring" << xml.name(); xml.skipCurrentElement(); } } setXmlError(xml);*/ } /*! * \class QtAws::MediaConnect::MediaConnectResponsePrivate * \brief The MediaConnectResponsePrivate class provides private implementation for MediaConnectResponse. * \internal * * \inmodule QtAwsMediaConnect */ /*! * Constructs a MediaConnectResponsePrivate object with public implementation \a q. */ MediaConnectResponsePrivate::MediaConnectResponsePrivate( MediaConnectResponse * const q) : QtAws::Core::AwsAbstractResponsePrivate(q) { } } // namespace MediaConnect } // namespace QtAws
lgpl-3.0
dennisbappert/fileharbor
src/Services/Entities/CollectionEntity.cs
789
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Fileharbor.Common.Database; namespace Fileharbor.Services.Entities { [Table("collections")] public class CollectionEntity { [Key] [ColumnName("id")] public Guid Id { get; set; } [Required] [ColumnName("name")] public string Name { get; set; } [Required] [ColumnName("quota")] public long Quota { get; set; } [Required] [ColumnName("bytes_used")] public long BytesUsed { get; set; } [ColumnName("template_id")] public Guid? TemplateId { get; set; } [ColumnName("description")] public string Description { get; set; } } }
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/Uuid/X64/iid0000005A.c
452
// Created file "Lib\src\Uuid\X64\iid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_SecurityProperty, 0xe74a7215, 0x014d, 0x11d1, 0xa6, 0x3c, 0x00, 0xa0, 0xc9, 0x11, 0xb4, 0xe0);
lgpl-3.0
kbogert/falconunity
UnityDemoProject/Assets/SimpleDebug.cs
323
using UnityEngine; using System.Collections; public class SimpleDebug : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { float val = FalconUnity.getFPS(); GUI.Label(new Rect(5,5,200,30), val.ToString() ); } }
lgpl-3.0
tjbwyk/myrgbdemo
nestk/ntk/detection/table_object_detector.hpp
10289
/** * This file is part of the nestk library. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Nicolas Burrus <[email protected]>, (C) 2010 */ # include "table_object_detector.h" # include <ntk/utils/time.h> # include <boost/make_shared.hpp> using namespace pcl; using cv::Point3f; namespace ntk { template <class PointType> TableObjectDetector<PointType> :: TableObjectDetector() : m_max_dist_to_plane(0.03) { // ---[ Create all PCL objects and set their parameters setObjectVoxelSize(); setBackgroundVoxelSize(); setDepthLimits(); setObjectHeightLimits(); // Normal estimation parameters k_ = 10; // 50 k-neighbors by default // Table model fitting parameters sac_distance_threshold_ = 0.01; // 1cm // Don't know ? normal_distance_weight_ = 0.1; // Clustering parameters object_cluster_tolerance_ = 0.05; // 5cm between two objects object_cluster_min_size_ = 100; // 100 points per object cluster } template <class PointType> void TableObjectDetector<PointType> :: initialize() { grid_.setLeafSize (downsample_leaf_, downsample_leaf_, downsample_leaf_); grid_objects_.setLeafSize (downsample_leaf_objects_, downsample_leaf_objects_, downsample_leaf_objects_); grid_.setFilterFieldName ("z"); pass_.setFilterFieldName ("z"); grid_.setFilterLimits (min_z_bounds_, max_z_bounds_); pass_.setFilterLimits (min_z_bounds_, max_z_bounds_); grid_.setDownsampleAllData (false); grid_objects_.setDownsampleAllData (false); #ifdef HAVE_PCL_GREATER_THAN_1_2_0 normals_tree_ = boost::make_shared<pcl::search::KdTree<Point> > (); clusters_tree_ = boost::make_shared<pcl::search::KdTree<Point> > (); #else normals_tree_ = boost::make_shared<pcl::KdTreeFLANN<Point> > (); clusters_tree_ = boost::make_shared<pcl::KdTreeFLANN<Point> > (); #endif clusters_tree_->setEpsilon (1); //tree_.setSearchWindowAsK (10); //tree_.setMaxDistance (0.5); n3d_.setKSearch (k_); n3d_.setSearchMethod (normals_tree_); normal_distance_weight_ = 0.1; seg_.setNormalDistanceWeight (normal_distance_weight_); seg_.setOptimizeCoefficients (true); seg_.setModelType (pcl::SACMODEL_NORMAL_PLANE); seg_.setMethodType (pcl::SAC_RANSAC); seg_.setProbability (0.99); seg_.setDistanceThreshold (sac_distance_threshold_); seg_.setMaxIterations (10000); proj_.setModelType (pcl::SACMODEL_NORMAL_PLANE); prism_.setHeightLimits (object_min_height_, object_max_height_); cluster_.setClusterTolerance (object_cluster_tolerance_); cluster_.setMinClusterSize (object_cluster_min_size_); cluster_.setSearchMethod (clusters_tree_); } template <class PointType> bool TableObjectDetector<PointType> :: detect(PointCloudConstPtr cloud) { ntk::TimeCount tc("TableObjectDetector::detect", 1); m_object_clusters.clear(); initialize(); ntk_dbg(1) << cv::format("PointCloud with %d data points.\n", cloud->width * cloud->height); // ---[ Convert the dataset cloud_ = cloud; // FIXME: Find out whether the removal of the (deep-copying) cloud.makeShared() call sped things up. // ---[ Create the voxel grid pcl::PointCloud<Point> cloud_filtered; pass_.setInputCloud (cloud_); pass_.filter (cloud_filtered); cloud_filtered_.reset (new pcl::PointCloud<Point> (cloud_filtered)); ntk_dbg(1) << cv::format("Number of points left after filtering (%f -> %f): %d out of %d.\n", min_z_bounds_, max_z_bounds_, (int)cloud_filtered.points.size (), (int)cloud->points.size ()); pcl::PointCloud<Point> cloud_downsampled; grid_.setInputCloud (cloud_filtered_); grid_.filter (cloud_downsampled); cloud_downsampled_.reset (new pcl::PointCloud<Point> (cloud_downsampled)); if ((int)cloud_filtered_->points.size () < k_) { ntk_dbg(0) << cv::format("WARNING Filtering returned %d points! Continuing.\n", (int)cloud_filtered_->points.size ()); return false; } // ---[ Estimate the point normals pcl::PointCloud<pcl::Normal> cloud_normals; n3d_.setInputCloud (cloud_downsampled_); n3d_.compute (cloud_normals); cloud_normals_.reset (new pcl::PointCloud<pcl::Normal> (cloud_normals)); ntk_dbg(1) << cv::format("%d normals estimated.", (int)cloud_normals.points.size ()); //ROS_ASSERT (cloud_normals_->points.size () == cloud_filtered_->points.size ()); // ---[ Perform segmentation pcl::PointIndices table_inliers; pcl::ModelCoefficients table_coefficients; seg_.setInputCloud (cloud_downsampled_); seg_.setInputNormals (cloud_normals_); seg_.segment (table_inliers, table_coefficients); table_inliers_.reset (new pcl::PointIndices (table_inliers)); table_coefficients_.reset (new pcl::ModelCoefficients (table_coefficients)); if (table_coefficients.values.size () > 3) ntk_dbg(1) << cv::format("Model found with %d inliers: [%f %f %f %f].\n", (int)table_inliers.indices.size (), table_coefficients.values[0], table_coefficients.values[1], table_coefficients.values[2], table_coefficients.values[3]); if (table_inliers_->indices.size () == 0) return false; m_plane = ntk::Plane (table_coefficients.values[0], table_coefficients.values[1], table_coefficients.values[2], table_coefficients.values[3]); // ---[ Extract the table pcl::PointCloud<Point> table_projected; proj_.setInputCloud (cloud_downsampled_); proj_.setIndices (table_inliers_); proj_.setModelCoefficients (table_coefficients_); proj_.filter (table_projected); table_projected_.reset (new pcl::PointCloud<Point> (table_projected)); ntk_dbg(1) << cv::format("Number of projected inliers: %d.\n", (int)table_projected.points.size ()); // ---[ Estimate the convex hull pcl::PointCloud<Point> table_hull; hull_.setInputCloud (table_projected_); hull_.reconstruct (table_hull); table_hull_.reset (new pcl::PointCloud<Point> (table_hull)); // ---[ Get the objects on top of the table pcl::PointIndices cloud_object_indices; prism_.setInputCloud (cloud_filtered_); prism_.setInputPlanarHull (table_hull_); prism_.segment (cloud_object_indices); ntk_dbg(1) << cv::format("Number of object point indices: %d.\n", (int)cloud_object_indices.indices.size ()); pcl::PointCloud<Point> cloud_objects; pcl::ExtractIndices<Point> extract_object_indices; //extract_object_indices.setInputCloud (cloud_all_minus_table_ptr); extract_object_indices.setInputCloud (cloud_filtered_); // extract_object_indices.setInputCloud (cloud_downsampled_); extract_object_indices.setIndices (boost::make_shared<const pcl::PointIndices> (cloud_object_indices)); extract_object_indices.filter (cloud_objects); cloud_objects_.reset (new pcl::PointCloud<Point> (cloud_objects)); ntk_dbg(1) << cv::format("Number of object point candidates: %d.\n", (int)cloud_objects.points.size ()); if (cloud_objects.points.size () == 0) return false; // ---[ Downsample the points pcl::PointCloud<Point> cloud_objects_downsampled; grid_objects_.setInputCloud (cloud_objects_); grid_objects_.filter (cloud_objects_downsampled); cloud_objects_downsampled_.reset (new pcl::PointCloud<Point> (cloud_objects_downsampled)); ntk_dbg(1) << cv::format("Number of object point candidates left after downsampling: %d.\n", (int)cloud_objects_downsampled.points.size ()); // ---[ Split the objects into Euclidean clusters std::vector< PointIndices > object_clusters; cluster_.setInputCloud (cloud_objects_downsampled_); cluster_.extract (object_clusters); ntk_dbg(1) << cv::format("Number of clusters found matching the given constraints: %d.\n", (int)object_clusters.size ()); for (size_t i = 0; i < object_clusters.size (); ++i) { std::vector<Point3f> object_points; foreach_idx(k, object_clusters[i].indices) { int index = object_clusters[i].indices[k]; Point p = cloud_objects_downsampled_->points[index]; object_points.push_back(Point3f(p.x,p.y,p.z)); } float min_dist_to_plane = FLT_MAX; for (int j = 0; j < object_points.size(); ++j) { Point3f pobj = object_points[j]; min_dist_to_plane = std::min(plane().distanceToPlane(pobj), min_dist_to_plane); } ntk_dbg_print(min_dist_to_plane, 1); if (min_dist_to_plane > m_max_dist_to_plane) continue; m_object_clusters.push_back(object_points); } tc.stop(); return true; } template <class PointType> int TableObjectDetector<PointType> :: getMostCentralCluster() const { // Look for the most central cluster which is not flying. int selected_object = -1; float min_x = FLT_MAX; for (int i = 0; i < objectClusters().size(); ++i) { const std::vector<Point3f>& object_points = objectClusters()[i]; float min_dist_to_plane = FLT_MAX; for (int j = 0; j < object_points.size(); ++j) { Point3f pobj = object_points[j]; min_dist_to_plane = std::min(plane().distanceToPlane(pobj), min_dist_to_plane); } if (min_dist_to_plane > m_max_dist_to_plane) continue; ntk::Rect3f bbox = bounding_box(object_points); if (std::abs(bbox.centroid().x) < min_x) { min_x = std::abs(bbox.centroid().x); selected_object = i; } } return selected_object; } } // ntk
lgpl-3.0
biotextmining/processes
src/main/java/com/silicolife/textmining/processes/ir/patentpipeline/components/searchmodule/googlesearch/IRPatentIDRetrievalGoogleSearchConfigurationImpl.java
614
package com.silicolife.textmining.processes.ir.patentpipeline.components.searchmodule.googlesearch; public class IRPatentIDRetrievalGoogleSearchConfigurationImpl implements IIRPatentIDRecoverGoogleSearchConfiguration { private String accessToken; private String CustomSearchID; public IRPatentIDRetrievalGoogleSearchConfigurationImpl(String accessToken, String CustomSearchID) { this.accessToken=accessToken; this.CustomSearchID=CustomSearchID; } @Override public String getAccessToken() { return accessToken; } @Override public String getCustomSearchID() { return CustomSearchID; } }
lgpl-3.0
SergiyKolesnikov/fuji
examples/AHEAD/j2jast/PlstEscape.java
140
public class PlstEscape { public void harvestConstructors( int stage ) { super.harvestConstructors( stage-1 ); } }
lgpl-3.0
JackNoordhuis/PocketMine-MP
src/world/sound/IgniteSound.php
1028
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\world\sound; use pocketmine\math\Vector3; use pocketmine\network\mcpe\protocol\LevelEventPacket; class IgniteSound implements Sound{ public function encode(?Vector3 $pos) : array{ return [LevelEventPacket::create(LevelEventPacket::EVENT_SOUND_IGNITE, 0, $pos)]; } }
lgpl-3.0
DivineCooperation/bco.core-manager
openhab/src/main/java/org/openbase/bco/device/openhab/registry/synchronizer/ItemUnitSynchronization.java
6930
package org.openbase.bco.device.openhab.registry.synchronizer; /*- * #%L * BCO Openhab Device Manager * %% * Copyright (C) 2015 - 2021 openbase.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.eclipse.smarthome.core.thing.link.dto.ItemChannelLinkDTO; import org.eclipse.smarthome.io.rest.core.item.EnrichedItemDTO; import org.openbase.bco.device.openhab.communication.OpenHABRestCommunicator; import org.openbase.bco.device.openhab.registry.diff.IdentifiableEnrichedItemDTO; import org.openbase.bco.device.openhab.registry.synchronizer.OpenHABItemProcessor.OpenHABItemNameMetaData; import org.openbase.bco.registry.remote.Registries; import org.openbase.jul.exception.CouldNotPerformException; import org.openbase.jul.exception.InstantiationException; import org.openbase.jul.exception.NotAvailableException; import org.openbase.jul.schedule.SyncObject; import org.openbase.jul.storage.registry.AbstractSynchronizer; import org.openbase.type.domotic.service.ServiceTemplateType.ServiceTemplate.ServiceType; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState; import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:[email protected]">Tamino Huxohl</a> */ public class ItemUnitSynchronization extends AbstractSynchronizer<String, IdentifiableEnrichedItemDTO> { public ItemUnitSynchronization(final SyncObject synchronizationLock) throws InstantiationException { super(new ItemObservable(), synchronizationLock); } @Override public void activate() throws CouldNotPerformException, InterruptedException { OpenHABRestCommunicator.getInstance().waitForConnectionState(ConnectionState.State.CONNECTED); super.activate(); } @Override public void update(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) throws CouldNotPerformException { logger.trace("Synchronize update {} ...", identifiableEnrichedItemDTO.getDTO().name); validateAndUpdateItem(identifiableEnrichedItemDTO.getDTO()); } @Override public void register(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) throws CouldNotPerformException { logger.trace("Synchronize registration {} ...", identifiableEnrichedItemDTO.getDTO().name); // do nothing because items are registers by the thing synchronization validateAndUpdateItem(identifiableEnrichedItemDTO.getDTO()); } @Override public void remove(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) throws CouldNotPerformException { logger.trace("Synchronize removal {} ...", identifiableEnrichedItemDTO.getDTO().name); final OpenHABItemNameMetaData metaData = new OpenHABItemNameMetaData(identifiableEnrichedItemDTO.getId()); try { // unit exists for item so sync and register it again final UnitConfig unitConfig = Registries.getUnitRegistry().getUnitConfigByAlias(metaData.getAlias()); updateItem(unitConfig, metaData.getServiceType(), identifiableEnrichedItemDTO.getDTO()); OpenHABRestCommunicator.getInstance().registerItem(identifiableEnrichedItemDTO.getDTO()); } catch (NotAvailableException ex) { // unit does not exist so removal is okay } } @Override protected void afterInternalSync() { logger.debug("Internal sync finished!"); } @Override public List<IdentifiableEnrichedItemDTO> getEntries() throws CouldNotPerformException { final List<IdentifiableEnrichedItemDTO> itemList = new ArrayList<>(); for (final EnrichedItemDTO item : OpenHABRestCommunicator.getInstance().getItems()) { itemList.add(new IdentifiableEnrichedItemDTO(item)); } return itemList; } @Override public boolean isSupported(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) { return true; } private boolean updateItem(final UnitConfig unitConfig, final ServiceType serviceType, final EnrichedItemDTO item) throws CouldNotPerformException { boolean modification = false; final String label = SynchronizationProcessor.generateItemLabel(unitConfig, serviceType); if (item.label == null || !item.label.equals(label)) { if (item.label != null) { logger.info("Item name of {} change from {} to {}", item.name, label, item.label, label); } item.label = label; modification = true; } return modification; } private void validateAndUpdateItem(final EnrichedItemDTO item) throws CouldNotPerformException { OpenHABItemNameMetaData metaData; try { metaData = new OpenHABItemNameMetaData(item.name); } catch (CouldNotPerformException ex) { // ignore item because it was not configured by this app return; } try { // unit exists for item so sync label from dal unit back to item if necessary final UnitConfig unitConfig = Registries.getUnitRegistry().getUnitConfigByAlias(metaData.getAlias()); if (updateItem(unitConfig, metaData.getServiceType(), item)) { OpenHABRestCommunicator.getInstance().updateItem(item); } } catch (NotAvailableException ex) { // unit does not exist for item so remove it try { OpenHABRestCommunicator.getInstance().deleteItem(item); } catch (CouldNotPerformException exx) { // It seems like openHAB is sometimes not deleting item channel links but the links still // cause items to be returned when queried. // Thus if the item could not be deleted search a link still referencing it. for (final ItemChannelLinkDTO itemChannelLink : OpenHABRestCommunicator.getInstance().getItemChannelLinks()) { if (itemChannelLink.itemName.equals(item.name)) { OpenHABRestCommunicator.getInstance().deleteItemChannelLink(itemChannelLink); return; } } throw exx; } } } }
lgpl-3.0
blunted2night/MyGUI
MyGUIEngine/src/MyGUI_LayerItem.cpp
5791
/*! @file @author Albert Semenov @date 11/2007 */ /* This file is part of MyGUI. MyGUI 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. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_LayerItem.h" #include <algorithm> namespace MyGUI { LayerItem::LayerItem() : mLayer(nullptr), mLayerNode(nullptr), mSaveLayerNode(nullptr), mTexture(nullptr) { } LayerItem::~LayerItem() { } void LayerItem::addChildItem(LayerItem* _item) { mLayerItems.push_back(_item); if (mLayerNode != nullptr) { _item->attachToLayerItemNode(mLayerNode, false); } } void LayerItem::removeChildItem(LayerItem* _item) { VectorLayerItem::iterator item = std::remove(mLayerItems.begin(), mLayerItems.end(), _item); MYGUI_ASSERT(item != mLayerItems.end(), "item not found"); mLayerItems.erase(item); } void LayerItem::addChildNode(LayerItem* _item) { mLayerNodes.push_back(_item); if (mLayerNode != nullptr) { // создаем оверлаппеду новый айтем ILayerNode* child_node = mLayerNode->createChildItemNode(); _item->attachToLayerItemNode(child_node, true); } } void LayerItem::removeChildNode(LayerItem* _item) { VectorLayerItem::iterator item = std::remove(mLayerNodes.begin(), mLayerNodes.end(), _item); MYGUI_ASSERT(item != mLayerNodes.end(), "item not found"); mLayerNodes.erase(item); } void LayerItem::addRenderItem(ISubWidget* _item) { mDrawItems.push_back(_item); } void LayerItem::removeAllRenderItems() { detachFromLayerItemNode(false); mDrawItems.clear(); } void LayerItem::setRenderItemTexture(ITexture* _texture) { mTexture = _texture; if (mLayerNode) { ILayerNode* node = mLayerNode; // позже сделать детач без текста detachFromLayerItemNode(false); attachToLayerItemNode(node, false); } } void LayerItem::saveLayerItem() { mSaveLayerNode = mLayerNode; } void LayerItem::restoreLayerItem() { mLayerNode = mSaveLayerNode; if (mLayerNode) { attachToLayerItemNode(mLayerNode, false); } } void LayerItem::attachItemToNode(ILayer* _layer, ILayerNode* _node) { mLayer = _layer; mLayerNode = _node; attachToLayerItemNode(_node, true); } void LayerItem::detachFromLayer() { // мы уже отдетачены в доску if (nullptr == mLayer) return; // такого быть не должно MYGUI_ASSERT(mLayerNode, "mLayerNode == nullptr"); // отписываемся от пиккинга mLayerNode->detachLayerItem(this); // при детаче обнулиться ILayerNode* save = mLayerNode; // физически отсоединяем detachFromLayerItemNode(true); // отсоединяем леер и обнуляем у рутового виджета mLayer->destroyChildItemNode(save); mLayerNode = nullptr; mLayer = nullptr; } void LayerItem::upLayerItem() { if (mLayerNode) mLayerNode->getLayer()->upChildItemNode(mLayerNode); } void LayerItem::attachToLayerItemNode(ILayerNode* _item, bool _deep) { MYGUI_DEBUG_ASSERT(nullptr != _item, "attached item must be valid"); // сохраняем, чтобы последующие дети могли приаттачиться mLayerNode = _item; for (VectorSubWidget::iterator skin = mDrawItems.begin(); skin != mDrawItems.end(); ++skin) { (*skin)->createDrawItem(mTexture, _item); } for (VectorLayerItem::iterator item = mLayerItems.begin(); item != mLayerItems.end(); ++item) { (*item)->attachToLayerItemNode(_item, _deep); } for (VectorLayerItem::iterator item = mLayerNodes.begin(); item != mLayerNodes.end(); ++item) { // создаем оверлаппеду новый айтем if (_deep) { ILayerNode* child_node = _item->createChildItemNode(); (*item)->attachToLayerItemNode(child_node, _deep); } } } void LayerItem::detachFromLayerItemNode(bool _deep) { for (VectorLayerItem::iterator item = mLayerItems.begin(); item != mLayerItems.end(); ++item) { (*item)->detachFromLayerItemNode(_deep); } for (VectorLayerItem::iterator item = mLayerNodes.begin(); item != mLayerNodes.end(); ++item) { if (_deep) { ILayerNode* node = (*item)->mLayerNode; (*item)->detachFromLayerItemNode(_deep); if (node) { node->getLayer()->destroyChildItemNode(node); } } } // мы уже отаттачены ILayerNode* node = mLayerNode; if (node) { //for (VectorWidgetPtr::iterator widget = mWidgetChildSkin.begin(); widget != mWidgetChildSkin.end(); ++widget) (*widget)->_detachFromLayerItemKeeperByStyle(_deep); for (VectorSubWidget::iterator skin = mDrawItems.begin(); skin != mDrawItems.end(); ++skin) { (*skin)->destroyDrawItem(); } // при глубокой очистке, если мы оверлаппед, то для нас создавали айтем /*if (_deep && !this->isRootWidget() && mWidgetStyle == WidgetStyle::Overlapped) { node->destroyItemNode(); }*/ // очищаем mLayerNode = nullptr; } } ILayer* LayerItem::getLayer() const { return mLayer; } ILayerNode* LayerItem::getLayerNode() const { return mLayerNode; } } // namespace MyGUI
lgpl-3.0
anderflash/komputilisto_kvadratoj
pt-BR/blogo/2013-12-06-webgl-improving-code.md
409
------------------------------ author: Anderson Tavares title: Tutorial WebGL: Melhorando o código description: Melhorando o código tags: WebGL, OpenGL thumbnail: assets/images/webgl-improving-code-thumb.png biblio: library.bib csl: ieee-with-url.csl math: True en-GB: 2013-11-06-webgl-improving-code eo: 2013-12-06-webgl-improving-code pt-BR: 2013-12-06-webgl-improving-code ------------------------------
lgpl-3.0
pcolby/libqtaws
src/cognitosync/describeidentityusagerequest.cpp
4598
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "describeidentityusagerequest.h" #include "describeidentityusagerequest_p.h" #include "describeidentityusageresponse.h" #include "cognitosyncrequest_p.h" namespace QtAws { namespace CognitoSync { /*! * \class QtAws::CognitoSync::DescribeIdentityUsageRequest * \brief The DescribeIdentityUsageRequest class provides an interface for CognitoSync DescribeIdentityUsage requests. * * \inmodule QtAwsCognitoSync * * <fullname>Amazon Cognito Sync</fullname> * * Amazon Cognito Sync provides an AWS service and client library that enable cross-device syncing of application-related * user data. High-level client libraries are available for both iOS and Android. You can use these libraries to persist * data locally so that it's available even if the device is offline. Developer credentials don't need to be stored on the * mobile device to access the service. You can use Amazon Cognito to obtain a normalized user ID and credentials. User * data is persisted in a dataset that can store up to 1 MB of key-value pairs, and you can have up to 20 datasets per user * * identity> * * With Amazon Cognito Sync, the data stored for each identity is accessible only to credentials assigned to that identity. * In order to use the Cognito Sync service, you need to make API calls using credentials retrieved with <a * href="http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/Welcome.html">Amazon Cognito Identity * * service</a>> * * If you want to use Cognito Sync in an Android or iOS application, you will probably want to make API calls via the AWS * Mobile SDK. To learn more, see the <a * href="http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-sync.html">Developer Guide for Android</a> * and the <a href="http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-sync.html">Developer Guide for * * \sa CognitoSyncClient::describeIdentityUsage */ /*! * Constructs a copy of \a other. */ DescribeIdentityUsageRequest::DescribeIdentityUsageRequest(const DescribeIdentityUsageRequest &other) : CognitoSyncRequest(new DescribeIdentityUsageRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DescribeIdentityUsageRequest object. */ DescribeIdentityUsageRequest::DescribeIdentityUsageRequest() : CognitoSyncRequest(new DescribeIdentityUsageRequestPrivate(CognitoSyncRequest::DescribeIdentityUsageAction, this)) { } /*! * \reimp */ bool DescribeIdentityUsageRequest::isValid() const { return false; } /*! * Returns a DescribeIdentityUsageResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DescribeIdentityUsageRequest::response(QNetworkReply * const reply) const { return new DescribeIdentityUsageResponse(*this, reply); } /*! * \class QtAws::CognitoSync::DescribeIdentityUsageRequestPrivate * \brief The DescribeIdentityUsageRequestPrivate class provides private implementation for DescribeIdentityUsageRequest. * \internal * * \inmodule QtAwsCognitoSync */ /*! * Constructs a DescribeIdentityUsageRequestPrivate object for CognitoSync \a action, * with public implementation \a q. */ DescribeIdentityUsageRequestPrivate::DescribeIdentityUsageRequestPrivate( const CognitoSyncRequest::Action action, DescribeIdentityUsageRequest * const q) : CognitoSyncRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DescribeIdentityUsageRequest * class' copy constructor. */ DescribeIdentityUsageRequestPrivate::DescribeIdentityUsageRequestPrivate( const DescribeIdentityUsageRequestPrivate &other, DescribeIdentityUsageRequest * const q) : CognitoSyncRequestPrivate(other, q) { } } // namespace CognitoSync } // namespace QtAws
lgpl-3.0
fkie-cad/iva
database.py
3952
from pymongo import MongoClient import config class Database: def __init__(self, db_name=None): self.mongodb_client = create_mongodb_client() self.db = self.create_db(db_name) self.authenticate_user() def create_db(self, db_name): if db_name is None: return self.mongodb_client[config.get_database_name()] return self.mongodb_client[db_name] def authenticate_user(self): if config.is_database_authentication_enabled(): self.db.authenticate(config.get_database_user(), config.get_database_password()) def insert_document_in_collection(self, doc, collection_name): collection = self.db[collection_name] collection.insert_one(doc) def exist_doc_in_collection(self, search_condition, collection_name): collection = self.db[collection_name] query_result = collection.find(search_condition).limit(1) return doc_found(query_result) def search_text_with_regex_in_collection(self, regex, field, collection_name): collection = self.db[collection_name] return collection.find({field: get_regex_dict(regex)}) def search_text_with_regex_in_collection_mul(self, regex_a, regex_b, field_a, field_b, collection_name): collection = self.db[collection_name] return collection.find({'$and': [{field_a: get_regex_dict(regex_a)}, {field_b: get_regex_dict(regex_b)}]}) def search_document_in_collection(self, search_condition, collection_name): collection = self.db[collection_name] return collection.find_one(search_condition, {'_id': 0}) def search_documents_in_collection(self, search_condition, collection_name): collection = self.db[collection_name] return collection.find(search_condition, {'_id': 0}) def search_documents_and_aggregate(self, search_condition, aggregation, collection_name): collection = self.db[collection_name] return list(collection.aggregate([{'$match': search_condition}, {'$project': aggregation}])) def get_number_of_documents_in_collection(self, collection_name, filter_=None): collection = self.db[collection_name] return collection.count(filter_) def update_document_in_collection(self, filter_, update, collection_name, insert_if_not_exists=False): collection = self.db[collection_name] collection.update_one(filter_, {'$set': update}, upsert=insert_if_not_exists) def update_documents_in_collection(self, docs, find_filter, collection_name): if len(docs) > 0: bulk = self.db[collection_name].initialize_ordered_bulk_op() for doc in docs: bulk.find({find_filter: doc.get(find_filter)}).upsert().update({'$set': doc}) bulk.execute() def get_documents_from_collection(self, collection_name): collection = self.db[collection_name] return list(collection.find({}, {'_id': 0})) def get_documents_from_collection_in_range(self, collection_name, skip=0, limit=0): collection = self.db[collection_name] return list(collection.find({}, {'_id': 0}).skip(skip).limit(limit)) def delete_document_from_collection(self, query, collection_name): collection = self.db[collection_name] collection.delete_one(query) def close(self): self.mongodb_client.close() def drop_collection(self, collection_name): collection = self.db[collection_name] collection.drop() def insert_documents_in_collection(self, documents, collection_name): collection = self.db[collection_name] collection.insert_many(documents=documents) def create_mongodb_client(): return MongoClient(config.get_database_host(), config.get_database_port()) def doc_found(query_result): found = query_result.count() > 0 query_result.close() return found def get_regex_dict(regex): return {'$regex': regex}
lgpl-3.0
sprylab/webinloop
webinloop/src/test/java/com/sprylab/webinloop/util/mailer/tests/MailAccountParseResultTest.java
3415
/******************************************************************************* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2009-2011 by sprylab technologies GmbH * * WebInLoop - a program for testing web applications * * This file is part of WebInLoop. * * WebInLoop is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * WebInLoop 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with WebInLoop. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html> * for a copy of the LGPLv3 License. ******************************************************************************/ package com.sprylab.webinloop.util.mailer.tests; import javax.mail.MessagingException; import org.testng.Assert; import org.testng.annotations.Test; import com.sprylab.webinloop.util.mailer.MailAccountParseResult; @Test public class MailAccountParseResultTest { private String buildMailTargetString(String account, Integer lowerBound, Integer upperBound, String target) { String result = account; if (lowerBound != null && upperBound != null) { result += ":" + lowerBound + "-" + upperBound; } if (target != null) { result += ":" + target; } return result; } private void testParseMailTargetString(String account, Integer lowerBound, Integer upperBound, String target) throws MessagingException { String mailTarget = buildMailTargetString(account, lowerBound, upperBound, target); MailAccountParseResult result = MailAccountParseResult.parse(mailTarget); if (lowerBound == null) { lowerBound = 0; } if (upperBound == null) { upperBound = Integer.MAX_VALUE; } Assert.assertEquals(result.getMailAccount(), account); Assert.assertEquals(result.getLowerBound(), lowerBound); Assert.assertEquals(result.getUpperBound(), upperBound); Assert.assertEquals(result.getTarget(), target); } @Test public void parseAccount() throws MessagingException { String account = "mail1"; Integer lowerBound = null; Integer upperBound = null; String target = null; testParseMailTargetString(account, lowerBound, upperBound, target); } @Test public void parseAccountAndTarget() throws MessagingException { String account = "mail1"; Integer lowerBound = null; Integer upperBound = null; String target = "subject"; testParseMailTargetString(account, lowerBound, upperBound, target); } @Test public void parseAccountRangeAndTarget() throws MessagingException { String account = "mail1"; Integer lowerBound = 1; Integer upperBound = 10; String target = "subject"; testParseMailTargetString(account, lowerBound, upperBound, target); } }
lgpl-3.0
cristal-ise/restapi
src/main/java/org/cristalise/restapi/ScriptUtils.java
6223
/** * This file is part of the CRISTAL-iSE REST API. * Copyright (c) 2001-2016 The CRISTAL Consortium. All rights reserved. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 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; with out even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * http://www.fsf.org/licensing/licenses/lgpl.html */ package org.cristalise.restapi; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import java.net.URLDecoder; import java.util.Date; import java.util.Map; import java.util.concurrent.Semaphore; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import org.cristalise.kernel.common.InvalidDataException; import org.cristalise.kernel.entity.proxy.ItemProxy; import org.cristalise.kernel.persistency.outcome.Outcome; import org.cristalise.kernel.persistency.outcome.Schema; import org.cristalise.kernel.scripting.Script; import org.cristalise.kernel.scripting.ScriptingEngineException; import org.cristalise.kernel.utils.CastorHashMap; import org.cristalise.kernel.utils.LocalObjectLoader; import org.cristalise.kernel.utils.Logger; import org.json.JSONObject; import org.json.XML; public class ScriptUtils extends ItemUtils { static Semaphore mutex = new Semaphore(1); public ScriptUtils() { super(); } /** * * @param item * @param script * @return * @throws ScriptingEngineException * @throws InvalidDataException */ protected Object executeScript(ItemProxy item, final Script script, CastorHashMap inputs) throws ScriptingEngineException, InvalidDataException { Object scriptResult = null; try { scriptResult = script.evaluate(item == null ? script.getItemPath() : item.getPath(), inputs, null, null); } catch (ScriptingEngineException e) { throw e; } catch (Exception e) { throw new InvalidDataException(e.getMessage()); } return scriptResult; } public Response executeScript(HttpHeaders headers, ItemProxy item, String scriptName, Integer scriptVersion, String inputJson, Map<String, Object> additionalInputs) { // FIXME: version should be retrieved from the current item or the Module // String view = "last"; if (scriptVersion == null) scriptVersion = 0; Script script = null; if (scriptName != null) { try { script = LocalObjectLoader.getScript(scriptName, scriptVersion); JSONObject json = new JSONObject( inputJson == null ? "{}" : URLDecoder.decode(inputJson, "UTF-8")); CastorHashMap inputs = new CastorHashMap(); for (String key: json.keySet()) { inputs.put(key, json.get(key)); } inputs.putAll(additionalInputs); return returnScriptResult(scriptName, item, null, script, inputs, produceJSON(headers.getAcceptableMediaTypes())); } catch (Exception e) { Logger.error(e); throw ItemUtils.createWebAppException("Error executing script, please contact support", e, Response.Status.NOT_FOUND); } } else { throw ItemUtils.createWebAppException("Name or UUID of Script was missing", Response.Status.NOT_FOUND); } } public Response returnScriptResult(String scriptName, ItemProxy item, final Schema schema, final Script script, CastorHashMap inputs, boolean jsonFlag) throws ScriptingEngineException, InvalidDataException { try { mutex.acquire(); return runScript(scriptName, item, schema, script, inputs, jsonFlag); } catch (ScriptingEngineException e) { throw e; } catch (Exception e) { throw new InvalidDataException(e.getMessage()); } finally { mutex.release(); } } /** * * @param scriptName * @param item * @param schema * @param script * @param jsonFlag whether the response is a JSON or XML * @return * @throws ScriptingEngineException * @throws InvalidDataException */ protected Response runScript(String scriptName, ItemProxy item, final Schema schema, final Script script, CastorHashMap inputs, boolean jsonFlag) throws ScriptingEngineException, InvalidDataException { String xmlOutcome = null; Object scriptResult = executeScript(item, script, inputs); if (scriptResult instanceof String) { xmlOutcome = (String)scriptResult; } else if (scriptResult instanceof Map) { //the map shall have one Key only String key = ((Map<?,?>) scriptResult).keySet().toArray(new String[0])[0]; xmlOutcome = (String)((Map<?,?>) scriptResult).get(key); } else throw ItemUtils.createWebAppException("Cannot handle result of script:" + scriptName, NOT_FOUND); if (xmlOutcome == null) throw ItemUtils.createWebAppException("Cannot handle result of script:" + scriptName, NOT_FOUND); if (schema != null) return getOutcomeResponse(new Outcome(xmlOutcome, schema), new Date(), jsonFlag); else { if (jsonFlag) return Response.ok(XML.toJSONObject(xmlOutcome).toString()).build(); else return Response.ok((xmlOutcome)).build(); } } }
lgpl-3.0
sdruix/AutomaticParallelization
src/tl/tl-pragmasupport.hpp
18927
/*-------------------------------------------------------------------- (C) Copyright 2006-2011 Barcelona Supercomputing Center Centro Nacional de Supercomputacion This file is part of Mercurium C/C++ source-to-source compiler. See AUTHORS file in the top level directory for information regarding developers and contributors. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Mercurium C/C++ source-to-source compiler 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 Mercurium C/C++ source-to-source compiler; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. --------------------------------------------------------------------*/ #ifndef TL_PRAGMASUPPORT_HPP #define TL_PRAGMASUPPORT_HPP #include "tl-common.hpp" #include <string> #include <stack> #include <algorithm> #include "tl-clauses-info.hpp" #include "tl-compilerphase.hpp" #include "tl-langconstruct.hpp" #include "tl-handler.hpp" #include "tl-traverse.hpp" #include "tl-source.hpp" #include "cxx-attrnames.h" namespace TL { class LIBTL_CLASS ClauseTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const = 0; virtual ~ClauseTokenizer() { } }; class LIBTL_CLASS NullClauseTokenizer : public ClauseTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const { ObjectList<std::string> result; result.append(str); return result; } }; class LIBTL_CLASS ExpressionTokenizer : public ClauseTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const { int bracket_nesting = 0; ObjectList<std::string> result; std::string temporary(""); for (std::string::const_iterator it = str.begin(); it != str.end(); it++) { const char & c(*it); if (c == ',' && bracket_nesting == 0 && temporary != "") { result.append(temporary); temporary = ""; } else { if (c == '(' || c == '{' || c == '[') { bracket_nesting++; } else if (c == ')' || c == '}' || c == ']') { bracket_nesting--; } temporary += c; } } if (temporary != "") { result.append(temporary); } return result; } }; class LIBTL_CLASS ExpressionTokenizerTrim : public ExpressionTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const { ObjectList<std::string> result; result = ExpressionTokenizer::tokenize(str); std::transform(result.begin(), result.end(), result.begin(), trimExp); return result; } private: static std::string trimExp (const std::string &str) { ssize_t first = str.find_first_not_of(" \t"); ssize_t last = str.find_last_not_of(" \t"); return str.substr(first, last - first + 1); } }; //! This class wraps a clause in a PragmaCustomConstruct /*! This class allows a clause to be named several times, thus #pragma prefix name clause(a) clause(b) will be equivalent as if the user had written #pragma prefix name clause(a, b) There is no way to tell apart these two cases, except for using PragmaCustomClause::get_arguments_unflattened, see below. Pragma clauses are pretty flexible on what they allow as arguments. Free, well parenthesized, text is allowed in clauses. Thus forwarding the responsability of giving a syntactic validity and semantic meaning to PragmaCustomCompilerPhase classes. Since the raw string is most of the time of little use, the class can cook some usual cases: When the clause should contain a list of expressions, use PragmaCustomClause::get_expression_list When the clause should contain a list of variable-names (but not general expressions), use PragmaCustomClause::get_id_expressions You can always get raw versions of the clause content (in case you have very special syntax in it requiring special parsing) using PragmaCustomClause::get_arguments and PragmaCustomClause::get_arguments_unflattened. The second version returns a list of lists of strings, one list per occurrence of the clause while the first flats them in a single list. */ class LIBTL_CLASS PragmaCustomClause : public LangConstruct { private: ObjectList<std::string> _clause_names; ObjectList<AST_t> filter_pragma_clause(); public: PragmaCustomClause(const std::string& src, AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link) { _clause_names.push_back(src); } PragmaCustomClause(const ObjectList<std::string> & src, AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link), _clause_names(src) { } //! Returns the name of the current clause std::string get_clause_name() { return _clause_names[0]; } //! States whether the clause was actually in the pragma /*! Since PragmaCustomConstruct always returns a PragmaCustomClause use this function to know whether the clause was actually in the pragma line. No other function of PragmaCustomClause should be used if this function returns false */ bool is_defined(); //! Convenience function, it returns all the arguments of the clause parsed as expressions ObjectList<Expression> get_expression_list(); //! Convenience function, it returns all arguments of the clause parsed as id-expressions ObjectList<IdExpression> get_id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS); //! Do not use this one, its name is deprecated, use get_id_expressions instead ObjectList<IdExpression> id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS); //! Returns the string contents of the clause arguments /*! This function actually returns a list of a single element */ ObjectList<std::string> get_arguments(); //! Returns the string contents of the clause arguments but using a tokenizer /*! The tokenizer can further split the text in additional substrings */ ObjectList<std::string> get_arguments(const ClauseTokenizer&); //! Returns the string contents of the clause arguments but using a tokenizer /*! This function is similar to get_arguments but does not combine them in a single list. There is a list per each clause occurrence in the pragma */ ObjectList<ObjectList<std::string> > get_arguments_unflattened(); //! This is like get_arguments but at tree level. This function is of little use /*! It is highly unlikely that you need this function. Check the others */ ObjectList<AST_t> get_arguments_tree(); }; class LIBTL_CLASS PragmaCustomConstruct : public LangConstruct, public LinkData { private: DTO* _dto; public: PragmaCustomConstruct(AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link), _dto(NULL) { } //! Returns the name of the pragma prefix std::string get_pragma() const; //! Returns the name of the pragma directive std::string get_directive() const; //! States if this is a directive /*! When this function is true it means that the pragma itself is a sole entity */ bool is_directive() const; //! States if this is a construct /*! When this function is true it means that the pragma acts as a header of another language construct. Functions get_statement and get_declaration can then, be used to retrieve that language construct. For pragma constructs at block-scope only get_statement should be used, otherwise use get_declaration as the nested construct can be a declaration or a function definition (or even something else) */ bool is_construct() const; //! Returns the statement associated to this pragma construct /*! Using this function is only valid when the pragma is in block-scope and function is_construct returned true */ Statement get_statement() const; //! Returns the tree associated to this pragma construct /*! Using this function is only valid when the pragma is in a scope other than block and function is_construct returned true This tree can be a Declaration, FunctionDefinition or some other tree not wrapped yet in a LangConstruct (e.g. a Namespace definition) */ AST_t get_declaration() const; //! This function returns the tree related to the pragma itself /*! This function is rarely needed, only when a change of the pragma itself is required */ AST_t get_pragma_line() const; //! This is used internally to initialize clauses information /*! Use it only if you want automatic clause checks but you never call get_clause on it It is safe to call it more than once. */ void init_clause_info() const; //! States if the pragma encloses a function definition /*! This is useful when using get_declaration, to quickly know if we can use a FunctionDefinition or we should use a Declaration instead */ bool is_function_definition() const; //! States if the pragma is followed by a first clause-alike parenthesis pair /*! #pragma prefix directive(a,b) 'a,b' is sort of an unnamed clause which is called the parameter of the pragma This function states if this pragma has this syntax */ bool is_parameterized() const; //! Returns a list of IdExpression's found in the parameter of the pragma ObjectList<IdExpression> get_parameter_id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS) const; //! Returns a list of Expressions in the parameter of the pragma /*! Parameters allow well-parenthesized free text. This function interprets the content of the parameter as a list of comma-separated expressions, parses them at this moment (if not parsed already) and returns it as a list */ ObjectList<Expression> get_parameter_expressions() const; //! Returns the string of the parameter of the pragma /*! Parameters allow well-parenthesized free text. This function returns the whole text with no tokenization. This function will always return one element, but for parallelism with the equivalent function of PragmaCustomClause it returns a list (that will contain a single element) */ ObjectList<std::string> get_parameter_arguments() const; //! Returns the string of the parameter of the pragma using a tokenizer /*! This function is identical to get_parameter_arguments() but uses \a tokenizer to split the contents of the string. */ ObjectList<std::string> get_parameter_arguments(const ClauseTokenizer& tokenizer) const; //! This function returns all the clauses of this pragma ObjectList<std::string> get_clause_names() const; //! This function returns a PragmaCustomClause object for a named clause /*! Note that this function always returns a PragmaCustomClause object even if no clause with the given /a name exists. Use PragmaCustomClause::is_defined to check its existence. Adds to the DTO of PragmaCustomCompilerPhase the clause only if /a name exists. */ PragmaCustomClause get_clause(const std::string& name) const; PragmaCustomClause get_clause(const ObjectList<std::string>& names) const; //! This function set to the object _dto the dto get from de compiler phase void set_dto(DTO* dto); //! This function returns a boolean that show if some warnings must be printed out bool get_show_warnings(); }; LIBTL_EXTERN bool is_pragma_custom(const std::string& pragma_preffix, AST_t ast, ScopeLink scope_link); LIBTL_EXTERN bool is_pragma_custom_directive(const std::string& pragma_preffix, const std::string& pragma_directive, AST_t ast, ScopeLink scope_link); LIBTL_EXTERN bool is_pragma_custom_construct(const std::string& pragma_preffix, const std::string& pragma_directive, AST_t ast, ScopeLink scope_link); typedef std::map<std::string, Signal1<PragmaCustomConstruct> > CustomFunctorMap; class LIBTL_CLASS PragmaCustomDispatcher : public TraverseFunctor { private: std::string _pragma_handled; CustomFunctorMap& _pre_map; CustomFunctorMap& _post_map; DTO* _dto; bool _warning_clauses; std::stack<PragmaCustomConstruct*> _construct_stack; void dispatch_pragma_construct(CustomFunctorMap& search_map, PragmaCustomConstruct& pragma_custom_construct); public: PragmaCustomDispatcher(const std::string& pragma_handled, CustomFunctorMap& pre_map, CustomFunctorMap& post_map, bool warning_clauses); virtual void preorder(Context ctx, AST_t node); virtual void postorder(Context ctx, AST_t node); void set_dto(DTO* dto); void set_warning_clauses(bool warning); }; //! Base class for all compiler phases working on user defined pragma lines /*! * Configuration of mcxx will require a 'pragma_prefix' line in order * to properly parse these pragma lines. In addition, the phases * will have to call register_directive and register_construct * accordingly to register specific constructs and directives. */ class LIBTL_CLASS PragmaCustomCompilerPhase : public CompilerPhase { private: std::string _pragma_handled; PragmaCustomDispatcher _pragma_dispatcher; public: //! Constructor /*! * \param pragma_handled The pragma prefix actually handled in this phase. */ PragmaCustomCompilerPhase(const std::string& pragma_handled); virtual void pre_run(DTO& data_flow); //! Entry point of the phase /*! * This function registers traverse functors to perform * a traversal on all the constructs and directives. */ virtual void run(DTO& data_flow); //! Custom functor map for directives found in preorder CustomFunctorMap on_directive_pre; //! Custom functor map for directives found in postorder CustomFunctorMap on_directive_post; //! Function to register a directive /*! * This is required for successful parsing of directives */ void register_directive(const std::string& name); //! Function to register a construct /*! * This is required for successful parsing of construct * * \param bound_to_statement This parameter is only meaningful in * Fortran and will have no effect in C/C++. If true, the * construct is bounded to the next single statement. By default in * Fortran a construct 'name' is bound to a block of statements, * thus requiring a 'end name' directive to know where such block * ends. By binding the construct to the next statement, such 'end * name' it is not strictly needed anymore thus becoming optional. * This parameter does not have any effect in C/C++ since in those * languages pragma constructs are always bound to the next * statement since blocks are expressed by compound-statements * which are statements (recursively) containing other statements */ void register_construct(const std::string& name, bool bound_to_statement = false); //! Function to activate a flag in order to warning about all the unused clauses of a pragma /*! * Each fase must activate this flag if wants to show the warnings */ void warning_pragma_unused_clauses(bool warning); }; } #endif // TL_PRAGMASUPPORT_HPP
lgpl-3.0
Udacity2048/CloudSimDisk
docs/org/cloudbus/cloudsim/examples/power/planetlab/LrrMc.html
11116
<!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 (1.8.0_31) on Mon Apr 06 15:30:26 CEST 2015 --> <title>LrrMc</title> <meta name="date" content="2015-04-06"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="LrrMc"; } } catch(err) { } //--> var methods = {"i0":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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/LrrMc.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="../../../../../../org/cloudbus/cloudsim/examples/power/planetlab/LrMu.html" title="class in org.cloudbus.cloudsim.examples.power.planetlab"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../../org/cloudbus/cloudsim/examples/power/planetlab/LrrMmt.html" title="class in org.cloudbus.cloudsim.examples.power.planetlab"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/cloudbus/cloudsim/examples/power/planetlab/LrrMc.html" target="_top">Frames</a></li> <li><a href="LrrMc.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</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">org.cloudbus.cloudsim.examples.power.planetlab</div> <h2 title="Class LrrMc" class="title">Class LrrMc</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.cloudbus.cloudsim.examples.power.planetlab.LrrMc</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">LrrMc</span> extends java.lang.Object</pre> <div class="block">A simulation of a heterogeneous power aware data center that applies the Local Regression Robust (LRR) VM allocation policy and Maximum Correlation (MC) VM selection policy. This example uses a real PlanetLab workload: 20110303. The remaining configuration parameters are in the Constants and PlanetLabConstants classes. If you are using any algorithms, policies or workload included in the power package please cite the following paper: Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24, Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012</div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>Jan 5, 2012</dd> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>Anton Beloglazov</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/cloudbus/cloudsim/examples/power/planetlab/LrrMc.html#LrrMc--">LrrMc</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/cloudbus/cloudsim/examples/power/planetlab/LrrMc.html#main-java.lang.String:A-">main</a></span>(java.lang.String[]&nbsp;args)</code> <div class="block">The main method.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, 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"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="LrrMc--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>LrrMc</h4> <pre>public&nbsp;LrrMc()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="main-java.lang.String:A-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>main</h4> <pre>public static&nbsp;void&nbsp;main(java.lang.String[]&nbsp;args) throws java.io.IOException</pre> <div class="block">The main method.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>args</code> - the arguments</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>java.io.IOException</code> - Signals that an I/O exception has occurred.</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> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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/LrrMc.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="../../../../../../org/cloudbus/cloudsim/examples/power/planetlab/LrMu.html" title="class in org.cloudbus.cloudsim.examples.power.planetlab"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../../org/cloudbus/cloudsim/examples/power/planetlab/LrrMmt.html" title="class in org.cloudbus.cloudsim.examples.power.planetlab"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/cloudbus/cloudsim/examples/power/planetlab/LrrMc.html" target="_top">Frames</a></li> <li><a href="LrrMc.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
lgpl-3.0
goulu/Goulib
Goulib/decorators.py
5279
""" useful decorators """ __author__ = "Philippe Guglielmetti" __copyright__ = "Copyright 2015, Philippe Guglielmetti" __credits__ = ["http://include.aorcsik.com/2014/05/28/timeout-decorator/"] __license__ = "LGPL + MIT" import multiprocessing from multiprocessing import TimeoutError from threading import Timer import weakref import threading import _thread as thread from multiprocessing.pool import ThreadPool import logging import functools import sys import logging _gettrace = getattr(sys, 'gettrace', None) debugger = _gettrace and _gettrace() logging.info('debugger ' + ('ACTIVE' if debugger else 'INACTIVE')) # http://wiki.python.org/moin/PythonDecoratorLibrary def memoize(obj): """speed up repeated calls to a function by caching its results in a dict index by params :see: https://en.wikipedia.org/wiki/Memoization """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer def debug(func): # Customize these messages ENTRY_MESSAGE = 'Entering {}' EXIT_MESSAGE = 'Exiting {}' @functools.wraps(func) def wrapper(*args, **kwds): logger = logging.getLogger() logger.info(ENTRY_MESSAGE.format(func.__name__)) level = logger.getEffectiveLevel() logger.setLevel(logging.DEBUG) f_result = func(*args, **kwds) logger.setLevel(level) logger.info(EXIT_MESSAGE.format(func.__name__)) return f_result return wrapper def nodebug(func): @functools.wraps(func) def wrapper(*args, **kwds): logger = logging.getLogger() level = logger.getEffectiveLevel() logger.setLevel(logging.INFO) f_result = func(*args, **kwds) logger.setLevel(level) return f_result return wrapper # https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d def timeit(method): import time def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() logging.info('%r %2.2f ms' % (method.__name__, (te - ts) * 1000)) return result return timed # http://include.aorcsik.com/2014/05/28/timeout-decorator/ # BUT read http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python thread_pool = None def get_thread_pool(): global thread_pool if thread_pool is None: # fix for python <2.7.2 if not hasattr(threading.current_thread(), "_children"): threading.current_thread()._children = weakref.WeakKeyDictionary() thread_pool = ThreadPool(processes=1) return thread_pool def timeout(timeout): def wrap_function(func): if not timeout: return func @functools.wraps(func) def __wrapper(*args, **kwargs): try: async_result = get_thread_pool().apply_async(func, args=args, kwds=kwargs) return async_result.get(timeout) except thread.error: return func(*args, **kwargs) return __wrapper return wrap_function # https://gist.github.com/goulu/45329ef041a368a663e5 def itimeout(iterable, timeout): """timeout for loops :param iterable: any iterable :param timeout: float max running time in seconds :yield: items in iterator until timeout occurs :raise: multiprocessing.TimeoutError if timeout occured """ if False: # handle debugger better one day ... n = 100 * timeout for i, x in enumerate(iterable): yield x if i > n: break else: timer = Timer(timeout, lambda: None) timer.start() for x in iterable: yield x if timer.finished.is_set(): raise TimeoutError # don't forget it, otherwise the thread never finishes... timer.cancel() # https://www.artima.com/weblogs/viewpost.jsp?thread=101605 registry = {} class MultiMethod(object): def __init__(self, name): self.name = name self.typemap = {} def __call__(self, *args): types = tuple(arg.__class__ for arg in args) # a generator expression! function = self.typemap.get(types) if function is None: raise TypeError("no match") return function(*args) def register(self, types, function): if types in self.typemap: raise TypeError("duplicate registration") self.typemap[types] = function def multimethod(*types): """ allows to overload functions for various parameter types @multimethod(int, int) def foo(a, b): ...code for two ints... @multimethod(float, float): def foo(a, b): ...code for two floats... @multimethod(str, str): def foo(a, b): ...code for two strings... """ def register(function): name = function.__name__ mm = registry.get(name) if mm is None: mm = registry[name] = MultiMethod(name) mm.register(types, function) return mm return register
lgpl-3.0
pcolby/libqtaws
src/swf/describeworkflowexecutionrequest_p.h
1521
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_DESCRIBEWORKFLOWEXECUTIONREQUEST_P_H #define QTAWS_DESCRIBEWORKFLOWEXECUTIONREQUEST_P_H #include "swfrequest_p.h" #include "describeworkflowexecutionrequest.h" namespace QtAws { namespace SWF { class DescribeWorkflowExecutionRequest; class DescribeWorkflowExecutionRequestPrivate : public SwfRequestPrivate { public: DescribeWorkflowExecutionRequestPrivate(const SwfRequest::Action action, DescribeWorkflowExecutionRequest * const q); DescribeWorkflowExecutionRequestPrivate(const DescribeWorkflowExecutionRequestPrivate &other, DescribeWorkflowExecutionRequest * const q); private: Q_DECLARE_PUBLIC(DescribeWorkflowExecutionRequest) }; } // namespace SWF } // namespace QtAws #endif
lgpl-3.0
markovmodel/PyEMMA
pyemma/coordinates/clustering/interface.py
12270
# This file is part of PyEMMA. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU 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/>. ''' Created on 18.02.2015 @author: marscher ''' import os import numpy as np from deeptime.clustering import ClusterModel, metrics from pyemma._base.serialization.serialization import SerializableMixIn from pyemma._base.model import Model from pyemma._base.parallel import NJobsMixIn from pyemma._ext.sklearn.base import ClusterMixin from pyemma.coordinates.data._base.transformer import StreamingEstimationTransformer from pyemma.util.annotators import fix_docs, aliased, alias from pyemma.util.discrete_trajectories import index_states, sample_indexes_by_state from pyemma.util.files import mkdir_p @fix_docs @aliased class AbstractClustering(StreamingEstimationTransformer, Model, ClusterMixin, NJobsMixIn, SerializableMixIn): """ provides a common interface for cluster algorithms. Parameters ---------- metric: str, default='euclidean' metric to pass to c extension n_jobs: int or None, default=None How much threads to use during assignment If None, all available CPUs will be used. """ def __init__(self, metric='euclidean', n_jobs=None): super(AbstractClustering, self).__init__() from ._ext import rmsd metrics.register("minRMSD", rmsd) self.metric = metric self.clustercenters = None self._previous_stride = -1 self._dtrajs = [] self._overwrite_dtrajs = False self._index_states = [] self.n_jobs = n_jobs __serialize_fields = ('_dtrajs', '_previous_stride', '_index_states', '_overwrite_dtrajs', '_precentered') __serialize_version = 0 def set_model_params(self, clustercenters): self.clustercenters = clustercenters @property @alias('cluster_centers_') # sk-learn compat. def clustercenters(self): """ Array containing the coordinates of the calculated cluster centers. """ return self._clustercenters @clustercenters.setter def clustercenters(self, val): self._clustercenters = np.asarray(val, dtype='float32', order='C')[:] if val is not None else None self._precentered = False @property def overwrite_dtrajs(self): """ Should existing dtraj files be overwritten. Set this property to True to overwrite. """ return self._overwrite_dtrajs @overwrite_dtrajs.setter def overwrite_dtrajs(self, value): self._overwrite_dtrajs = value @property #@alias('labels_') # TODO: for fully sklearn-compat this would have to be a flat array! def dtrajs(self): """Discrete trajectories (assigned data to cluster centers).""" if len(self._dtrajs) == 0: # nothing assigned yet, doing that now self._dtrajs = self.assign(stride=1) return self._dtrajs # returning what we have saved @property def index_clusters(self): """Returns trajectory/time indexes for all the clusters Returns ------- indexes : list of ndarray( (N_i, 2) ) For each state, all trajectory and time indexes where this cluster occurs. Each matrix has a number of rows equal to the number of occurrences of the corresponding state, with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. """ if len(self._dtrajs) == 0: # nothing assigned yet, doing that now self._dtrajs = self.assign() if len(self._index_states) == 0: # has never been run self._index_states = index_states(self._dtrajs) return self._index_states def sample_indexes_by_cluster(self, clusters, nsample, replace=True): """Samples trajectory/time indexes according to the given sequence of states. Parameters ---------- clusters : iterable of integers It contains the cluster indexes to be sampled nsample : int Number of samples per cluster. If replace = False, the number of returned samples per cluster could be smaller if less than nsample indexes are available for a cluster. replace : boolean, optional Whether the sample is with or without replacement Returns ------- indexes : list of ndarray( (N, 2) ) List of the sampled indices by cluster. Each element is an index array with a number of rows equal to N=len(sequence), with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. """ # Check if the catalogue (index_states) if len(self._index_states) == 0: # has never been run self._index_states = index_states(self.dtrajs) return sample_indexes_by_state(self._index_states[clusters], nsample, replace=replace) def _transform_array(self, X): """get closest index of point in :attr:`clustercenters` to x.""" X = np.require(X, dtype=np.float32, requirements='C') # for performance reasons we pre-center the cluster centers for minRMSD. if self.metric == 'minRMSD' and not self._precentered: self._precentered = True model = ClusterModel(cluster_centers=self.clustercenters, metric=self.metric) dtraj = model.transform(X) res = dtraj[:, None] # always return a column vector in this function return res def dimension(self): """output dimension of clustering algorithm (always 1).""" return 1 def output_type(self): return np.int32() def assign(self, X=None, stride=1): """ Assigns the given trajectory or list of trajectories to cluster centers by using the discretization defined by this clustering method (usually a Voronoi tesselation). You can assign multiple times with different strides. The last result of assign will be saved and is available as the attribute :func:`dtrajs`. Parameters ---------- X : ndarray(T, n) or list of ndarray(T_i, n), optional, default = None Optional input data to map, where T is the number of time steps and n is the number of dimensions. When a list is provided they can have differently many time steps, but the number of dimensions need to be consistent. When X is not provided, the result of assign is identical to get_output(), i.e. the data used for clustering will be assigned. If X is given, the stride argument is not accepted. stride : int, optional, default = 1 If set to 1, all frames of the input data will be assigned. Note that this could cause this calculation to be very slow for large data sets. Since molecular dynamics data is usually correlated at short timescales, it is often sufficient to obtain the discretization at a longer stride. Note that the stride option used to conduct the clustering is independent of the assign stride. This argument is only accepted if X is not given. Returns ------- Y : ndarray(T, dtype=int) or list of ndarray(T_i, dtype=int) The discretized trajectory: int-array with the indexes of the assigned clusters, or list of such int-arrays. If called with a list of trajectories, Y will also be a corresponding list of discrete trajectories """ if X is None: # if the stride did not change and the discrete trajectory is already present, # just return it if self._previous_stride is stride and len(self._dtrajs) > 0: return self._dtrajs self._previous_stride = stride skip = self.skip if hasattr(self, 'skip') else 0 # map to column vectors mapped = self.get_output(stride=stride, chunk=self.chunksize, skip=skip) # flatten and save self._dtrajs = [np.transpose(m)[0] for m in mapped] # return return self._dtrajs else: if stride != 1: raise ValueError('assign accepts either X or stride parameters, but not both. If you want to map '+ 'only a subset of your data, extract the subset yourself and pass it as X.') # map to column vector(s) mapped = self.transform(X) # flatten if isinstance(mapped, np.ndarray): mapped = np.transpose(mapped)[0] else: mapped = [np.transpose(m)[0] for m in mapped] # return return mapped def save_dtrajs(self, trajfiles=None, prefix='', output_dir='.', output_format='ascii', extension='.dtraj'): """saves calculated discrete trajectories. Filenames are taken from given reader. If data comes from memory dtrajs are written to a default filename. Parameters ---------- trajfiles : list of str (optional) names of input trajectory files, will be used generate output files. prefix : str prepend prefix to filenames. output_dir : str save files to this directory. output_format : str if format is 'ascii' dtrajs will be written as csv files, otherwise they will be written as NumPy .npy files. extension : str file extension to append (eg. '.itraj') """ if extension[0] != '.': extension = '.' + extension # obtain filenames from input (if possible, reader is a featurereader) if output_format == 'ascii': from msmtools.dtraj import write_discrete_trajectory as write_dtraj else: from msmtools.dtraj import save_discrete_trajectory as write_dtraj import os.path as path output_files = [] if trajfiles is not None: # have filenames available? for f in trajfiles: p, n = path.split(f) # path and file basename, _ = path.splitext(n) if prefix != '': name = "%s_%s%s" % (prefix, basename, extension) else: name = "%s%s" % (basename, extension) # name = path.join(p, name) output_files.append(name) else: for i in range(len(self.dtrajs)): if prefix != '': name = "%s_%i%s" % (prefix, i, extension) else: name = str(i) + extension output_files.append(name) assert len(self.dtrajs) == len(output_files) if not os.path.exists(output_dir): mkdir_p(output_dir) for filename, dtraj in zip(output_files, self.dtrajs): dest = path.join(output_dir, filename) self.logger.debug('writing dtraj to "%s"' % dest) try: if path.exists(dest) and not self.overwrite_dtrajs: raise EnvironmentError('Attempted to write dtraj "%s" which already existed. To automatically' ' overwrite existing files, set source.overwrite_dtrajs=True.' % dest) write_dtraj(dest, dtraj) except IOError: self.logger.exception('Exception during writing dtraj to "%s"' % dest)
lgpl-3.0
loftuxab/community-edition-old
projects/slingshot/config/alfresco/site-webscripts/org/alfresco/components/node-details/node-path.get.js
650
<import resource="classpath:/alfresco/templates/org/alfresco/import/alfresco-util.js"> /** * Cloud Sync Status Information * */ function main() { AlfrescoUtil.param("nodeRef"); AlfrescoUtil.param("site", "defaultSite"); AlfrescoUtil.param("rootPage", "documentlibrary"); AlfrescoUtil.param("rootLabelId", "path.documents"); var nodeDetails = AlfrescoUtil.getNodeDetails(model.nodeRef, model.site); if (nodeDetails) { model.item = nodeDetails.item; model.node = nodeDetails.item.node; model.paths = AlfrescoUtil.getPaths(nodeDetails, model.rootPage, model.rootLabelId); } } main();
lgpl-3.0
pcolby/libqtaws
src/iotwireless/getwirelessgatewaycertificaterequest.h
1513
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_GETWIRELESSGATEWAYCERTIFICATEREQUEST_H #define QTAWS_GETWIRELESSGATEWAYCERTIFICATEREQUEST_H #include "iotwirelessrequest.h" namespace QtAws { namespace IoTWireless { class GetWirelessGatewayCertificateRequestPrivate; class QTAWSIOTWIRELESS_EXPORT GetWirelessGatewayCertificateRequest : public IoTWirelessRequest { public: GetWirelessGatewayCertificateRequest(const GetWirelessGatewayCertificateRequest &other); GetWirelessGatewayCertificateRequest(); virtual bool isValid() const Q_DECL_OVERRIDE; protected: virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(GetWirelessGatewayCertificateRequest) }; } // namespace IoTWireless } // namespace QtAws #endif
lgpl-3.0
fergunet/osgiliath
OsgiliathEvolutionaryAlgorithm/src/es/ugr/osgiliath/evolutionary/individual/Gene.java
1022
/* * Gene.java * * Copyright (c) 2013, Pablo Garcia-Sanchez. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * Contributors: */ package es.ugr.osgiliath.evolutionary.individual; import java.io.Serializable; public interface Gene extends Serializable, Cloneable{ public Object clone(); }
lgpl-3.0
haisamido/SFDaaS
src/org/orekit/propagation/sampling/OrekitStepNormalizer.java
5548
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.propagation.sampling; import org.orekit.errors.OrekitException; import org.orekit.errors.PropagationException; import org.orekit.propagation.SpacecraftState; import org.orekit.time.AbsoluteDate; /** * This class wraps an object implementing {@link OrekitFixedStepHandler} * into a {@link OrekitStepHandler}. * <p>It mirrors the <code>StepNormalizer</code> interface from <a * href="http://commons.apache.org/math/">commons-math</a> but * provides a space-dynamics interface to the methods.</p> * @author Luc Maisonobe * @version $Revision$ $Date$ */ public class OrekitStepNormalizer implements OrekitStepHandler { /** Serializable UID. */ private static final long serialVersionUID = 6335110162884693078L; /** Fixed time step. */ private double h; /** Underlying step handler. */ private OrekitFixedStepHandler handler; /** Last step date. */ private AbsoluteDate lastDate; /** Last State vector. */ private SpacecraftState lastState; /** Integration direction indicator. */ private boolean forward; /** Simple constructor. * @param h fixed time step (sign is not used) * @param handler fixed time step handler to wrap */ public OrekitStepNormalizer(final double h, final OrekitFixedStepHandler handler) { this.h = Math.abs(h); this.handler = handler; reset(); } /** Determines whether this handler needs dense output. * This handler needs dense output in order to provide data at * regularly spaced steps regardless of the steps the propagator * uses, so this method always returns true. * @return always true */ public boolean requiresDenseOutput() { return true; } /** Reset the step handler. * Initialize the internal data as required before the first step is * handled. */ public void reset() { lastDate = null; lastState = null; forward = true; } /** * Handle the last accepted step. * @param interpolator interpolator for the last accepted step. For * efficiency purposes, the various propagators reuse the same * object on each call, so if the instance wants to keep it across * all calls (for example to provide at the end of the propagation a * continuous model valid throughout the propagation range), it * should build a local copy using the clone method and store this * copy. * @param isLast true if the step is the last one * @throws PropagationException this exception is propagated to the * caller if the underlying user function triggers one */ public void handleStep(final OrekitStepInterpolator interpolator, final boolean isLast) throws PropagationException { try { if (lastState == null) { // initialize lastState in the first step case lastDate = interpolator.getPreviousDate(); interpolator.setInterpolatedDate(lastDate); lastState = interpolator.getInterpolatedState(); // take the propagation direction into account forward = interpolator.getCurrentDate().compareTo(lastDate) >= 0; if (!forward) { h = -h; } } // use the interpolator to push fixed steps events to the underlying handler AbsoluteDate nextTime = lastDate.shiftedBy(h); boolean nextInStep = forward ^ (nextTime.compareTo(interpolator.getCurrentDate()) > 0); while (nextInStep) { // output the stored previous step handler.handleStep(lastState, false); // store the next step lastDate = nextTime; interpolator.setInterpolatedDate(lastDate); lastState = interpolator.getInterpolatedState(); // prepare next iteration nextTime = nextTime.shiftedBy(h); nextInStep = forward ^ (nextTime.compareTo(interpolator.getCurrentDate()) > 0); } if (isLast) { // there will be no more steps, // the stored one should be flagged as being the last handler.handleStep(lastState, true); } } catch (OrekitException oe) { // recover a possible embedded PropagationException for (Throwable t = oe; t != null; t = t.getCause()) { if (t instanceof PropagationException) { throw (PropagationException) t; } } throw new PropagationException(oe.getMessage(), oe); } } }
lgpl-3.0
Bananasft/MBINCompiler
MBINCompiler/Models/Structs/TkCameraWanderData.cs
287
namespace MBINCompiler.Models.Structs { public class TkCameraWanderData : NMSTemplate { public bool CamWander; public float CamWanderPhase; public float CamWanderAmplitude; [NMS(Size = 4, Ignore = true)] public byte[] PaddingC; } }
lgpl-3.0
bobxiv/IAAspiradora
Ejercicio Aspiradora Logica/Aspiradora2.pl
1616
%Aspiradora %Hechos :- dynamic sucia/1. sucia(1).%habitacion 1 sucia(2).%habitacion 2 sucia(3).%habitacion 3 sucia(4).%habitacion 4 :- dynamic estoy/1. estoy(1). %Regla principal %aspirar(Path):- not(pruebaMeta), (limpiar(Path,NextPath); irH1(Path,NextPath); irH2(Path,NextPath); irH3(Path,NextPath); irH4(Path,NextPath)), aspirar(NextPath). aspirar(Path):- aspirarAux([],Path). aspirarAux(Path,Path2):- pruebaMeta(Path,Path2) -> ! ; ( (limpiar(Path,NextPath); girar(Path,NextPath)), aspirarAux(NextPath,Path2) ). %Iguala dos listas o variables equal(L,L). %Operadores %sucia(X) -> Limpiar(X) -> ~sucia(X) limpiar(Path,NextPath):- estoy(Pos), sucia(Pos), retract(sucia(Pos)), append([Path,[limpia]],NextPath), write('limpia'), nl. %(estoy(2) ; estoy(3)) -> irH1(X) -> estoy(1) ^ ~estoy(2) ^ ~estoy(3) girar(Path,NextPath):- estoy(X), ( X=1 -> irH2(Path,NextPath) ; X=2 -> irH4(Path,NextPath) ; X=3 -> irH1(Path,NextPath) ; X=4 -> irH3(Path,NextPath)). irH1(Path,NextPath):- (estoy(2) ; estoy(3)), retract(estoy(X)), assert(estoy(1)), append([Path,[irH1]],Path), write('irH1'), nl. irH2(Path,NextPath):- (estoy(1) ; estoy(4)), retract(estoy(X)), assert(estoy(2)), append([Path,[irH2]],NextPath), write('irH2'), nl. irH3(Path,NextPath):- (estoy(1) ; estoy(4)), retract(estoy(X)), assert(estoy(3)), append([Path,[irH3]],NextPath), write('irH3'), nl. irH4(Path,NextPath):- (estoy(2) ; estoy(3)), retract(estoy(X)), assert(estoy(4)), append([Path,[irH4]],NextPath), write('irH4'), nl. %Prueba de Meta pruebaMeta(Path,Path2):- not(sucia(1)), not(sucia(2)), not(sucia(3)), not(sucia(4)), !, true, equal(Path2,Path).
lgpl-3.0
liqiang1980/VTFS
src/TaskModule/visservotask.cpp
670
#include "visservotask.h" void VisuoServoTask::switchtotask(VISTaskNameT tn){ curtaskname.vist = tn; } void VisuoServoTask::switchtoglobalframe(){ mft = GLOBAL; } void VisuoServoTask::switchtolocalframe(){ mft = LOCAL; } VisuoServoTask::VisuoServoTask(VISTaskNameT tn) { curtaskname.vist = tn; desired_pose_range.setZero(); desired_dis = 0; } Eigen::Vector3d VisuoServoTask::get_desired_rotation_range(){ Eigen::Vector3d des; des.setZero(); des = desired_pose_range; return des; } double VisuoServoTask::get_desired_mv_dis(){ return desired_dis; } void VisuoServoTask::set_desired_mv_dis(double s){ desired_dis =s; }
lgpl-3.0
huyenntt/newSMC
doc/doxygen/a00086_afbba369697dcc1576af69ea6fd5e01fd.html
32827
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Petri Net API: pnapi::PetriNet::createOutputLabel</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Petri Net API &#160;<span id="projectnumber">Version 4.02</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="a00178.html">pnapi</a></li><li class="navelem"><a class="el" href="a00086.html">PetriNet</a></li> </ul> </div> </div><!-- top --> <div class="contents"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td valign="top"> <div class="navtab"> <table> <tr><td class="navtab"><a class="qindex" href="a00086_a553df2cef6e79bbfc9944018b7aa389e.html#a553df2cef6e79bbfc9944018b7aa389e">addRole</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a72e7359162c1979588aee9264e2f74ee.html#a72e7359162c1979588aee9264e2f74ee">addRoles</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a0f6e6479ef237f024c20575b7c98668e.html#a0f6e6479ef237f024c20575b7c98668e">arcs_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a301f46116b4e5365d90183c072f098ae.html#a301f46116b4e5365d90183c072f098ae">AutomatonConverter</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac6fe2abd93b3801e33cf4e887aa9ca79.html#ac6fe2abd93b3801e33cf4e887aa9ca79">automatonConverter_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9aed3c68f0cce97cf68b4367ae42f148d0">BOUNDEDNESS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a3c5858892d2e2a8da761343aa53e8916.html#a3c5858892d2e2a8da761343aa53e8916">canonicalNames</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_af76dc238276e6a34864cee93cedcf245.html#af76dc238276e6a34864cee93cedcf245">clear</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a4da9284bde011c610596f92d6435c970.html#a4da9284bde011c610596f92d6435c970">compose</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a28a41263253e27f9e4c39a015745c2ce.html#a28a41263253e27f9e4c39a015745c2ce">constraints_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5e4ddb085f1f2120e375c32a8bd25621.html#a5e4ddb085f1f2120e375c32a8bd25621">containsNode</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a9745ab562e6d35dc860380d4a8210035.html#a9745ab562e6d35dc860380d4a8210035">containsNode</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5fe4bb5bc56e2c0475f95ee8a0c2fe98.html#a5fe4bb5bc56e2c0475f95ee8a0c2fe98">copyPlaces</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a29216872f8014b80516292d0c5dacd6a.html#a29216872f8014b80516292d0c5dacd6a">copyStructure</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aa4da8ee1a2c769e804dc418fae899c28.html#aa4da8ee1a2c769e804dc418fae899c28">createArc</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ab03606dfdc1c68bef1de6de3ae7acb01.html#ab03606dfdc1c68bef1de6de3ae7acb01">createArcs</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a32babfa14efb8ab1b349ad6c3a420064.html#a32babfa14efb8ab1b349ad6c3a420064">createFromSTG</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a4de763868860771c11830781f47633fe.html#a4de763868860771c11830781f47633fe">createInputLabel</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a30a64527f32d61206e3df34b02576c82.html#a30a64527f32d61206e3df34b02576c82">createInputLabel</a></td></tr> <tr><td class="navtab"><a class="qindexHL" href="a00086_afbba369697dcc1576af69ea6fd5e01fd.html#afbba369697dcc1576af69ea6fd5e01fd">createOutputLabel</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_afd77c5f174970f07f9121f6533e6b472.html#afd77c5f174970f07f9121f6533e6b472">createOutputLabel</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a0b57ec2e2b2d808084cae78a062d9c10.html#a0b57ec2e2b2d808084cae78a062d9c10">createPlace</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac3d34197ab4b18db0ff89a3c8744ca90.html#ac3d34197ab4b18db0ff89a3c8744ca90">createPort</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_af49df8dc4ea8f8c4dfd59ba62f5b0ed4.html#af49df8dc4ea8f8c4dfd59ba62f5b0ed4">createSynchronizeLabel</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_abce8395761c63358a13a553df917533c.html#abce8395761c63358a13a553df917533c">createSynchronizeLabel</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aaf8158b180aba000f3ece160365fe8ee.html#aaf8158b180aba000f3ece160365fe8ee">createTransition</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_affcf11b7f6d7b997e9076a206a7375d5.html#affcf11b7f6d7b997e9076a206a7375d5">createTransition</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a075c505160095c8aeec549cda61ea0e8">DEAD_NODES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aa64f2ceb24f56cb2574bf8c414ba053d.html#aa64f2ceb24f56cb2574bf8c414ba053d">deleteArc</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a23953325e625c39a2a9ab003d275ac35.html#a23953325e625c39a2a9ab003d275ac35">deleteNode</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a19c6cfa0999ac0f4ec02a67a72e0598f.html#a19c6cfa0999ac0f4ec02a67a72e0598f">deletePlace</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a6e5464dea706f8c174c8aeb553d2f6a1.html#a6e5464dea706f8c174c8aeb553d2f6a1">deleteTransition</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9aa6c32537ffc1c40e4cf7ec5bfa664685">EQUAL_PLACES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aa9869a2a4fa30050f0b51220087d4ba2.html#aa9869a2a4fa30050f0b51220087d4ba2">finalCondition_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac70f41f2e73eab362d836dc0900cdae3.html#ac70f41f2e73eab362d836dc0900cdae3">findArc</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a8b8093681a01caa4e57743570dfe242b.html#a8b8093681a01caa4e57743570dfe242b">findNode</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ad5c2148de0cc433ad5ec13c833f96394.html#ad5c2148de0cc433ad5ec13c833f96394">findPlace</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a90c37d5baac5da014b1d223d3951d3e2.html#a90c37d5baac5da014b1d223d3951d3e2">findTransition</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a301f46116b4e5365d90183c072f098ae.html#a301f46116b4e5365d90183c072f098aead9866c79976f238f205cf7d4a194a4f0">GENET</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a680545281288907ba1b8529265cfcae1.html#a680545281288907ba1b8529265cfcae1">genetCapacity_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a188927cd7f4ce13c4128ce9245f2313f.html#a188927cd7f4ce13c4128ce9245f2313f">getArcs</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a091205ca198f30d3cd9b75f60b0846c2.html#a091205ca198f30d3cd9b75f60b0846c2">getConflictCluster</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_af4060504fa6bb5b672ba59c3f6b0a46a.html#af4060504fa6bb5b672ba59c3f6b0a46a">getConflictClusters</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a396370185497ee843e089dd5565c43ae.html#a396370185497ee843e089dd5565c43ae">getFinalCondition</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aeb00a9c78dddd7acc0e9ae177b122232.html#aeb00a9c78dddd7acc0e9ae177b122232">getFinalCondition</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a98865553a90b545d72dc5dc1b679bfdb.html#a98865553a90b545d72dc5dc1b679bfdb">getInterface</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a8d3352351982323b1ee71e6a147c0fbb.html#a8d3352351982323b1ee71e6a147c0fbb">getInterface</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a0d3e0f5e44ebdbb8371fc4afe7ac4d3f.html#a0d3e0f5e44ebdbb8371fc4afe7ac4d3f">getMetaInformation</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_af182817d6cf4c8adf58d8fe5b761201a.html#af182817d6cf4c8adf58d8fe5b761201a">getNodes</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a6f17da4ae3a1a65f419438b3e7895282.html#a6f17da4ae3a1a65f419438b3e7895282">getPlaces</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a373d7ac6ca2bcc26059d763938f3552f.html#a373d7ac6ca2bcc26059d763938f3552f">getRoles</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a3a7971397eca3307d45c238938994de7.html#a3a7971397eca3307d45c238938994de7">getSynchronizedTransitions</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a3352e50376291412460de0638a5a47a5.html#a3352e50376291412460de0638a5a47a5">getTransitions</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a925551ff5688c945dfecb5741ca4be36.html#a925551ff5688c945dfecb5741ca4be36">getUniqueNodeName</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a11bbe91acb6ffd90112382c2d1ffda58.html#a11bbe91acb6ffd90112382c2d1ffda58">getWarnings</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a06df5ec8b999fdaad5ecb26d572d297d.html#a06df5ec8b999fdaad5ecb26d572d297d">guessPlaceRelation</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a8892a9b08ce9bba5e51e795bfc075b1a">IDENTICAL_PLACES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a994dd7727cdbacaede8cdc3c4440664e">IDENTICAL_TRANSITIONS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9afb6634c5a2a6827ea9ce4450b2ff89a2">INITIALLY_MARKED_PLACES_IN_CHOREOGRAPHIES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5c5baafde1b0374f038d12d8244db15f.html#a5c5baafde1b0374f038d12d8244db15f">interface_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a946387052808ddafaa0a439b713f7409.html#a946387052808ddafaa0a439b713f7409">io::__dot::output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a31215e9dd0de0142ccb30b0f92eb2c8c.html#a31215e9dd0de0142ccb30b0f92eb2c8c">io::__lola::output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aa9d5f4f44c36ab6c8cc3e21cd7a815aa.html#aa9d5f4f44c36ab6c8cc3e21cd7a815aa">io::__owfn::output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac83c8898adb3854410fc7806d716d0b5.html#ac83c8898adb3854410fc7806d716d0b5">io::__pnml::output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a6e7b331ea2eea039ac5ac6a6455aec3f.html#a6e7b331ea2eea039ac5ac6a6455aec3f">io::__stat::output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aad44264399fe9e12237841127df8ec2b.html#aad44264399fe9e12237841127df8ec2b">io::__woflan::output</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_af6405e42f70fcfcdbd91e9990d123606.html#af6405e42f70fcfcdbd91e9990d123606">io::operator&gt;&gt;</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a17695c7f9ed8617fbd6a857f2d416068.html#a17695c7f9ed8617fbd6a857f2d416068">isFreeChoice</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a10da66d7f2d35de044be32c6bb4fc81e.html#a10da66d7f2d35de044be32c6bb4fc81e">isNormal</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aa6c2bde41c08bb12a521b24f034efa9c.html#aa6c2bde41c08bb12a521b24f034efa9c">isRoleSpecified</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a1c3c42392b7201006021fda25a82445b.html#a1c3c42392b7201006021fda25a82445b">isWorkflow</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9aa7021584e40977571cf7f3768bf9fcc7">K_BOUNDEDNESS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a07d7e28146672f023acdc0418258178e">LEVEL_1</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a967b452dbb09e69ba1326571a7274022">LEVEL_2</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a1f930296152166eb65f01b22f892138f">LEVEL_3</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a00aac3efaade8f28b76e37295577c0cc">LEVEL_4</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a1d3487c24c1394d9b7e6de5db3ec7692">LEVEL_5</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a50f395bfd962770bd4dfcc684eaa1b51">LEVEL_6</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9adac1c9ae00938728db664aabf4bb1d93">LIVENESS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac5979533e6b802fd0f33fd64446b92b8.html#ac5979533e6b802fd0f33fd64446b92b8">meta_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a7279a10a12a021aeca5bd50395eb2bbc.html#a7279a10a12a021aeca5bd50395eb2bbc">mirror</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ab252793c2f6db9e74e4b84fc9709b83f.html#ab252793c2f6db9e74e4b84fc9709b83f">nodes_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ad9fbbc3f6f3eb9e7310f2e863066e3e1.html#ad9fbbc3f6f3eb9e7310f2e863066e3e1">nodesByName_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a47e374892bc13936a413178e7293bb88">NONE</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a832a48353ba43617c32b9163515935ae.html#a832a48353ba43617c32b9163515935ae">normalize</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a503afb77da7be07c4777da5faf3e0f4e.html#a503afb77da7be07c4777da5faf3e0f4e">normalize_classical</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a1eec9931ba1f409f0d906255a2c71d41.html#a1eec9931ba1f409f0d906255a2c71d41">normalize_rules</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a29d731af41bb312442d564ab85f6316a.html#a29d731af41bb312442d564ab85f6316a">observer_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a57f3e3da28c1aa607a437baa111e7c05">ONCE</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a3d48fa719fa7b32ebcd6accf65109c91.html#a3d48fa719fa7b32ebcd6accf65109c91">operator=</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a4a3c857f1af06ae35bd61e8e4f00f66c.html#a4a3c857f1af06ae35bd61e8e4f00f66c">pathToGenet_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac9ace88cb232c44e941e4199e55147b0.html#ac9ace88cb232c44e941e4199e55147b0">pathToPetrify_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a301f46116b4e5365d90183c072f098ae.html#a301f46116b4e5365d90183c072f098aea2b34e4c68ddb0cf7b295b12e147cbb93">PETRIFY</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a68b1a4706e057c77d676e3337d13c790.html#a68b1a4706e057c77d676e3337d13c790">PetriNet</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ae9d047649d3cf300adc279d5fa623f98.html#ae9d047649d3cf300adc279d5fa623f98">PetriNet</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5490e8bd6c15886e4e9ca73eab6ce703.html#a5490e8bd6c15886e4e9ca73eab6ce703">PetriNet</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_aed1a655e8762981a631091506c95abed.html#aed1a655e8762981a631091506c95abed">PetriNet</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a9422af524509329465837a481c5521a4.html#a9422af524509329465837a481c5521a4">places_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_afd6eef613f421cd32c180b21371c45c4.html#afd6eef613f421cd32c180b21371c45c4">prefixLabelNames</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a42cf5f450fa4cc387445261aaff21c6b.html#a42cf5f450fa4cc387445261aaff21c6b">prefixNames</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a163f5b2140c058363c371a470d64151f.html#a163f5b2140c058363c371a470d64151f">prefixNodeNames</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ace1a1ec82ae68c7fcfb19c0bef95b8fb.html#ace1a1ec82ae68c7fcfb19c0bef95b8fb">produce</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a34d46cfd32f09242aa2b20c119ee902c.html#a34d46cfd32f09242aa2b20c119ee902c">reduce</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a57a3a474006cc5ac62eb18446314fd1b.html#a57a3a474006cc5ac62eb18446314fd1b">reduce_dead_nodes</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_afa6696cd7622f6d823312c3a064dc813.html#afa6696cd7622f6d823312c3a064dc813">reduce_emptyPostset</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a048ac2b88ae56ca194d3cd24628c6b4b.html#a048ac2b88ae56ca194d3cd24628c6b4b">reduce_equal_places</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a1f574589a29da2cbef3e730741ebb263.html#a1f574589a29da2cbef3e730741ebb263">reduce_identical_places</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a9c284e055a0f703a698f3d7c52463922.html#a9c284e055a0f703a698f3d7c52463922">reduce_identical_transitions</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ac23afcb0fd2f9f84b2a506f172c95874.html#ac23afcb0fd2f9f84b2a506f172c95874">reduce_isEqual</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2a4917b0582ffa655f8ca08362cda025.html#a2a4917b0582ffa655f8ca08362cda025">reduce_remove_initially_marked_places_in_choreographies</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a44dfee7b8aae746c52eece297edf784c.html#a44dfee7b8aae746c52eece297edf784c">reduce_rule_3p</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a8275854f8b26439619919dbcc114a963.html#a8275854f8b26439619919dbcc114a963">reduce_rule_3t</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5c4a85c10f8ebf2a3ef2752cc725581c.html#a5c4a85c10f8ebf2a3ef2752cc725581c">reduce_rule_4</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a0d640e500c0f0c52a5a25d3de806126e.html#a0d640e500c0f0c52a5a25d3de806126e">reduce_rule_5</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_acc1733c7272b2e9015ec7848f7c8a1e8.html#acc1733c7272b2e9015ec7848f7c8a1e8">reduce_rule_6</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2a7e6976e86d531db43c6d1106ade6fd.html#a2a7e6976e86d531db43c6d1106ade6fd">reduce_rule_7</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a736706f12ab9243164a53cd4b67bad5a.html#a736706f12ab9243164a53cd4b67bad5a">reduce_rule_8</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ab9f744dc9551578ecc30cd42182dfb48.html#ab9f744dc9551578ecc30cd42182dfb48">reduce_rule_9</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ada8a6e1ccf8105556b691d9e4a64bfc9.html#ada8a6e1ccf8105556b691d9e4a64bfc9">reduce_self_loop_places</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_ae2a6e75597454ec573eaa3c073848b0f.html#ae2a6e75597454ec573eaa3c073848b0f">reduce_self_loop_transitions</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a876ae814840f6d462c2646f47ca87a8d.html#a876ae814840f6d462c2646f47ca87a8d">reduce_series_places</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2d0d25e13da2b8674e2c87dacd4215c6.html#a2d0d25e13da2b8674e2c87dacd4215c6">reduce_series_transitions</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a065e65a3863d292be4336736274a09f2.html#a065e65a3863d292be4336736274a09f2">reduce_singletonPreset</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2247cde3ad8239ad68fcab1d5523b957.html#a2247cde3ad8239ad68fcab1d5523b957">reduce_suspicious_transitions</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a316b5cb29df85359fffd8b1c8aaefc76.html#a316b5cb29df85359fffd8b1c8aaefc76">reduce_unused_status_places</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a17196c18f03339a0f8bbe5b429fda3e8.html#a17196c18f03339a0f8bbe5b429fda3e8">reductionCache_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9">ReductionLevel</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_abba33101b23a042388f07bc72062b5a9.html#abba33101b23a042388f07bc72062b5a9">remap</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a0598d7897b33a0f1fac16273f15bc20a.html#a0598d7897b33a0f1fac16273f15bc20a">roles_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a75b9a3926f900421fb1e89d82b54a1b1">SELF_LOOP_PLACES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a5bcd62b0c379d054fd4e2247e261db31">SELF_LOOP_TRANSITIONS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a4acaeee5e0f0086bd875a0ccbf458af7">SERIES_PLACES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9acc340a701bc9f399f9526e9bfdddddbd">SERIES_TRANSITIONS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a947df75e7239f530e8ef93913dc86acf">SET_PILLAT</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a878e727f64fd9c95e1a478261fde35f8">SET_STARKE</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9abfadd6c59b1d7764cdf3cba50ff0c0ce">SET_UNNECCESSARY</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a95fbb48f633b5d93676f7b3633910055.html#a95fbb48f633b5d93676f7b3633910055">setConstraintLabels</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5e567fe790a9ec5ed14611554d8674e3.html#a5e567fe790a9ec5ed14611554d8674e3">setGenet</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_acb853b4cb01eb7824f757a15ba78f665.html#acb853b4cb01eb7824f757a15ba78f665">setPetrify</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a5cf0f95da3657721154f3f01ce764697.html#a5cf0f95da3657721154f3f01ce764697">setWarnings</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a6dc8e43f1e91e0f60892664153b7bc76">STARKE_RULE_3_PLACES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a73d8b99360daca703ed26f6195a06085">STARKE_RULE_3_TRANSITIONS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9aa7ce20124b480603e3247a1b051fbce0">STARKE_RULE_4</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9ae427bf643ba0cfe27946ee510434307b">STARKE_RULE_5</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9ae7e2f441ebe775a2cd8720825279f7ea">STARKE_RULE_6</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a426bf14c58a58b5356af85220b4f5102">STARKE_RULE_7</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a3d749f87d51285c2cf80940ac40f547a">STARKE_RULE_8</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a0f18c4be317a444e2871286f47e3f0f4">STARKE_RULE_9</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a301f46116b4e5365d90183c072f098ae.html#a301f46116b4e5365d90183c072f098aea73daf4434d3219cb83e111508eb7640c">STATEMACHINE</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a0b7ee7f8301973c414855100df053b03">SUSPICIOUS_TRANSITIONS</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a8c380c809203dc31b2a8931eb47b8161.html#a8c380c809203dc31b2a8931eb47b8161">synchronizedTransitions_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a8fba1becedefcfd6d21f13beeeb5ced9.html#a8fba1becedefcfd6d21f13beeeb5ced9">transitions_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a04e595627726ee54ad4350fdbc4c061a.html#a04e595627726ee54ad4350fdbc4c061a">translateConstraintLabels</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_adff6783d94206d5b1925bae14d4e54e9.html#adff6783d94206d5b1925bae14d4e54e9a6eccb24a4cc37e01ee124e185a3902ef">UNUSED_STATUS_PLACES</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a0ef435bf245d72ea04dd0b666bf511be.html#a0ef435bf245d72ea04dd0b666bf511be">util::ComponentObserver</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2a21a49cde4e8a11a68cf595b33d7383.html#a2a21a49cde4e8a11a68cf595b33d7383aefb3e51639244fcbf146fc6d8dcfd3d4">W_INTERFACE_PLACE_IN_FINAL_CONDITION</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2a21a49cde4e8a11a68cf595b33d7383.html#a2a21a49cde4e8a11a68cf595b33d7383a9626e6663613e6c7d4c5e68739834ea7">W_NONE</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a2a21a49cde4e8a11a68cf595b33d7383.html#a2a21a49cde4e8a11a68cf595b33d7383">Warning</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a51bc9e55297793ff65640e5b23d1a0a6.html#a51bc9e55297793ff65640e5b23d1a0a6">warnings_</a></td></tr> <tr><td class="navtab"><a class="qindex" href="a00086_a9a36c8728693dc3ed8761b57ef62c224.html#a9a36c8728693dc3ed8761b57ef62c224">~PetriNet</a></td></tr> </table> </div> </td> <td valign="top" class="mempage"> <a class="anchor" id="afbba369697dcc1576af69ea6fd5e01fd"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00038.html">Label</a> &amp; pnapi::PetriNet::createOutputLabel </td> <td>(</td> <td class="paramtype">const std::string &amp;&#160;</td> <td class="paramname"><em>name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const std::string &amp;&#160;</td> <td class="paramname"><em>port</em> = <code>&quot;&quot;</code>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>creates an output <a class="el" href="a00038.html" title="interface labels">Label</a> </p> <p>Creates an output label. </p> <p>Definition at line <a class="el" href="a00166_source.html#l00960">960</a> of file <a class="el" href="a00166_source.html">petrinet.cc</a>.</p> <p>References <a class="el" href="a00112_source.html#l00334">pnapi::Interface::addOutputLabel()</a>, and <a class="el" href="a00167_source.html#l00308">interface_</a>.</p> <div class="fragment"><div class="line">{</div> <div class="line"> <span class="keywordflow">return</span> <a class="code" href="a00086_a5c5baafde1b0374f038d12d8244db15f.html#a5c5baafde1b0374f038d12d8244db15f" title="interface">interface_</a>.<a class="code" href="a00030_a4a824b9405ca6763f61e58b811422d34.html#a4a824b9405ca6763f61e58b811422d34" title="adding an output label">addOutputLabel</a>(name, port);</div> <div class="line">}</div> </div><!-- fragment --> <p><div class="dynheader"> Here is the call graph for this function:</div> <div class="dyncontent"> <div class="center"><img src="a00086_afbba369697dcc1576af69ea6fd5e01fd_afbba369697dcc1576af69ea6fd5e01fd_cgraph.png" border="0" usemap="#a00086_afbba369697dcc1576af69ea6fd5e01fd_afbba369697dcc1576af69ea6fd5e01fd_cgraph" alt=""/></div> <map name="a00086_afbba369697dcc1576af69ea6fd5e01fd_afbba369697dcc1576af69ea6fd5e01fd_cgraph" id="a00086_afbba369697dcc1576af69ea6fd5e01fd_afbba369697dcc1576af69ea6fd5e01fd_cgraph"> <area shape="rect" id="node3" href="a00030_a4a824b9405ca6763f61e58b811422d34.html#a4a824b9405ca6763f61e58b811422d34" title="adding an output label" alt="" coords="243,5,419,49"/><area shape="rect" id="node5" href="a00089_a6971b10c99ddc20ad5dfbaa9bb343f9c.html#a6971b10c99ddc20ad5dfbaa9bb343f9c" title="adding an output label" alt="" coords="467,13,648,41"/></map> </div> </p> </div> </div> </td> </tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Thu Sep 17 2015 15:58:05 for Petri Net API by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.2 </small></address> </body> </html>
lgpl-3.0
subes/invesdwin-nowicket
invesdwin-nowicket-examples/invesdwin-nowicket-examples-guide/src/main/java/de/invesdwin/nowicket/examples/guide/page/documentation/tagtransformations/tablesandchoices/TablesAndChoicesPanel.java
1236
package de.invesdwin.nowicket.examples.guide.page.documentation.tagtransformations.tablesandchoices; import javax.annotation.concurrent.NotThreadSafe; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import de.invesdwin.nowicket.generated.binding.GeneratedBinding; import de.invesdwin.nowicket.generated.binding.processor.element.SelectHtmlElement; import de.invesdwin.nowicket.generated.binding.processor.visitor.builder.BindingInterceptor; import de.invesdwin.nowicket.generated.binding.processor.visitor.builder.component.palette.ModelPalette; @NotThreadSafe public class TablesAndChoicesPanel extends Panel { public TablesAndChoicesPanel(final String id, final IModel<TablesAndChoices> model) { super(id, model); new GeneratedBinding(this).withBindingInterceptor(new BindingInterceptor() { @Override public Component createSelect(final SelectHtmlElement e) { if (TablesAndChoicesConstants.asMultiselectPalette.equals(e.getWicketId())) { return new ModelPalette(e); } return super.createSelect(e); } }).bind(); } }
lgpl-3.0
Ideetron/RFM95W_Nexus
LoRaWAN_V30/RFM95_V20.h
2613
/****************************************************************************************** * Copyright 2015, 2016 Ideetron B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************************/ /****************************************************************************************** * * File: RFM95_V20.h * Author: Gerben den Hartog * Compagny: Ideetron B.V. * Website: http://www.ideetron.nl/LoRa * E-mail: [email protected] ******************************************************************************************/ /**************************************************************************************** * * Created on: 23-10-2015 * Supported Hardware: ID150119-02 Nexus board with RFM95 * * History: * * Firmware version: 1.0 * First version for LoRaWAN * * Firmware version: 2.0 * Created function to read received package * Switching to rigth receive channel * Moved waiting on RxDone or Timeout to RFM file * Moved CRC check to RFM file ****************************************************************************************/ #ifndef RFM95_V20_H #define RFM95_V20_H /* ***************************************************************************************** * TYPE DEFENITIONS ***************************************************************************************** */ typedef enum {NO_MESSAGE,CRC_OK,MIC_OK,MESSAGE_DONE,TIMEOUT,WRONG_MESSAGE} message_t; /* ***************************************************************************************** * FUNCTION PROTOTYPES ***************************************************************************************** */ void RFM_Init(); void RFM_Send_Package(unsigned char *RFM_Tx_Package, unsigned char Package_Length); unsigned char RFM_Get_Package(unsigned char *RFM_Rx_Package); unsigned char RFM_Read(unsigned char RFM_Address); void RFM_Write(unsigned char RFM_Address, unsigned char RFM_Data); message_t RFM_Receive(); #endif
lgpl-3.0
kamou/radare2
binr/rax2/rax2.c
15220
/* radare - LGPL - Copyright 2007-2018 - pancake */ #include "../blob/version.c" #include <r_util.h> #include <r_util/r_print.h> #define STDIN_BUFFER_SIZE 354096 #define R_STATIC_ASSERT(x)\ switch (0) {\ case 0:\ case (x):;\ } static RNum *num; static int help(); static ut64 flags = 0; static int use_stdin(); static int force_mode = 0; static int rax(char *str, int len, int last); static const char *nl = ""; static int format_output(char mode, const char *s) { ut64 n = r_num_math (num, s); char strbits[65]; if (force_mode) { mode = force_mode; } if (flags & 2) { ut64 n2 = n; r_mem_swapendian ((ut8 *) &n, (ut8 *) &n2, (n >> 32)? 8: 4); } switch (mode) { case 'I': printf ("%" PFMT64d "\n", n); break; case '0': printf ("0x%" PFMT64x "\n", n); break; case 'F': { float *f = (float *) &n; printf ("%ff\n", *f); } break; case 'f': printf ("%.01lf\n", num->fvalue); break; case 'l': R_STATIC_ASSERT (sizeof (float) == 4); float f = (float) num->fvalue; ut8 *p = (ut8 *) &f; printf ("Fx%02x%02x%02x%02x\n", p[3], p[2], p[1], p[0]); break; case 'O': printf ("0%" PFMT64o "\n", n); break; case 'B': if (n) { r_num_to_bits (strbits, n); printf ("%sb\n", strbits); } else { printf ("0b\n"); } break; case 'T': if (n) { r_num_to_trits (strbits, n); printf ("%st\n", strbits); } else { printf ("0t\n"); } break; default: eprintf ("Unknown output mode %d\n", mode); break; } return true; } static void print_ascii_table() { printf("%s", ret_ascii_table()); } static int help() { printf ( " =[base] ; rax2 =10 0x46 -> output in base 10\n" " int -> hex ; rax2 10\n" " hex -> int ; rax2 0xa\n" " -int -> hex ; rax2 -77\n" " -hex -> int ; rax2 0xffffffb3\n" " int -> bin ; rax2 b30\n" " int -> ternary ; rax2 t42\n" " bin -> int ; rax2 1010d\n" " ternary -> int ; rax2 1010dt\n" " float -> hex ; rax2 3.33f\n" " hex -> float ; rax2 Fx40551ed8\n" " oct -> hex ; rax2 35o\n" " hex -> oct ; rax2 Ox12 (O is a letter)\n" " bin -> hex ; rax2 1100011b\n" " hex -> bin ; rax2 Bx63\n" " ternary -> hex ; rax2 212t\n" " hex -> ternary ; rax2 Tx23\n" " raw -> hex ; rax2 -S < /binfile\n" " hex -> raw ; rax2 -s 414141\n" " -l ; append newline to output (for -E/-D/-r/..\n" " -a show ascii table ; rax2 -a\n" " -b bin -> str ; rax2 -b 01000101 01110110\n" " -B str -> bin ; rax2 -B hello\n" " -d force integer ; rax2 -d 3 -> 3 instead of 0x3\n" " -e swap endianness ; rax2 -e 0x33\n" " -D base64 decode ;\n" " -E base64 encode ;\n" " -f floating point ; rax2 -f 6.3+2.1\n" " -F stdin slurp code hex ; rax2 -F < shellcode.[c/py/js]\n" " -h help ; rax2 -h\n" " -i dump as C byte array ; rax2 -i < bytes\n" " -k keep base ; rax2 -k 33+3 -> 36\n" " -K randomart ; rax2 -K 0x34 1020304050\n" " -L bin -> hex(bignum) ; rax2 -L 111111111 # 0x1ff\n" " -n binary number ; rax2 -n 0x1234 # 34120000\n" " -N binary number ; rax2 -N 0x1234 # \\x34\\x12\\x00\\x00\n" " -r r2 style output ; rax2 -r 0x1234\n" " -s hexstr -> raw ; rax2 -s 43 4a 50\n" " -S raw -> hexstr ; rax2 -S < /bin/ls > ls.hex\n" " -t tstamp -> str ; rax2 -t 1234567890\n" " -x hash string ; rax2 -x linux osx\n" " -u units ; rax2 -u 389289238 # 317.0M\n" " -w signed word ; rax2 -w 16 0xffff\n" " -v version ; rax2 -v\n"); return true; } static int rax(char *str, int len, int last) { ut8 *buf; char *p, out_mode = (flags & 128)? 'I': '0'; int i; if (!(flags & 4) || !len) { len = strlen (str); } if ((flags & 4)) { goto dotherax; } if (*str == '=') { switch (atoi (str + 1)) { case 2: force_mode = 'B'; break; case 3: force_mode = 'T'; break; case 8: force_mode = 'O'; break; case 10: force_mode = 'I'; break; case 16: force_mode = '0'; break; case 0: force_mode = str[1]; break; } return true; } if (*str == '-') { while (str[1] && str[1] != ' ') { switch (str[1]) { case 'l': nl = "\n"; break; case 'a': print_ascii_table (); return 0; case 's': flags ^= 1; break; case 'e': flags ^= 1 << 1; break; case 'S': flags ^= 1 << 2; break; case 'b': flags ^= 1 << 3; break; case 'B': flags ^= 1 << 17; break; case 'x': flags ^= 1 << 4; break; case 'k': flags ^= 1 << 5; break; case 'f': flags ^= 1 << 6; break; case 'd': flags ^= 1 << 7; break; case 'K': flags ^= 1 << 8; break; case 'n': flags ^= 1 << 9; break; case 'u': flags ^= 1 << 10; break; case 't': flags ^= 1 << 11; break; case 'E': flags ^= 1 << 12; break; case 'D': flags ^= 1 << 13; break; case 'F': flags ^= 1 << 14; break; case 'N': flags ^= 1 << 15; break; case 'w': flags ^= 1 << 16; break; case 'r': flags ^= 1 << 18; break; case 'L': flags ^= 1 << 19; break; case 'i': flags ^= 1 << 21; break; case 'v': blob_version ("rax2"); return 0; case '\0': return !use_stdin (); default: /* not as complete as for positive numbers */ out_mode = (flags ^ 32)? '0': 'I'; if (str[1] >= '0' && str[1] <= '9') { if (str[2] == 'x') { out_mode = 'I'; } else if (r_str_endswith (str, "f")) { out_mode = 'l'; } return format_output (out_mode, str); } printf ("Usage: rax2 [options] [expr ...]\n"); return help (); } str++; } if (last) { return !use_stdin (); } return true; } if (!flags && r_str_nlen (str, 2) == 1) { if (*str == 'q') { return false; } if (*str == 'h' || *str == '?') { help (); return false; } } dotherax: if (flags & 1) { // -s int n = ((strlen (str)) >> 1) + 1; buf = malloc (n); if (buf) { memset (buf, '\0', n); n = r_hex_str2bin (str, (ut8 *) buf); if (n > 0) { fwrite (buf, n, 1, stdout); } #if __EMSCRIPTEN__ puts (""); #else if (nl && *nl) { puts (""); } #endif fflush (stdout); free (buf); } return true; } if (flags & (1 << 2)) { // -S for (i = 0; i < len; i++) { printf ("%02x", (ut8) str[i]); } printf ("\n"); return true; } else if (flags & (1 << 3)) { // -b int i, len; ut8 buf[4096]; len = r_str_binstr2bin (str, buf, sizeof (buf)); for (i = 0; i < len; i++) { printf ("%c", buf[i]); } return true; } else if (flags & (1 << 4)) { // -x int h = r_str_hash (str); printf ("0x%x\n", h); return true; } else if (flags & (1 << 5)) { // -k out_mode = 'I'; } else if (flags & (1 << 6)) { // -f out_mode = 'f'; } else if (flags & (1 << 8)) { // -K int n = ((strlen (str)) >> 1) + 1; char *s = NULL; ut32 *m; buf = (ut8 *) malloc (n); if (!buf) { return false; } m = (ut32 *) buf; memset (buf, '\0', n); n = r_hex_str2bin (str, (ut8 *) buf); if (n < 1 || !memcmp (str, "0x", 2)) { ut64 q = r_num_math (num, str); s = r_print_randomart ((ut8 *) &q, sizeof (q), q); printf ("%s\n", s); free (s); } else { s = r_print_randomart ((ut8 *) buf, n, *m); printf ("%s\n", s); free (s); } free (m); return true; } else if (flags & (1 << 9)) { // -n ut64 n = r_num_math (num, str); if (n >> 32) { /* is 64 bit value */ ut8 *np = (ut8 *) &n; if (flags & 1) { fwrite (&n, sizeof (n), 1, stdout); } else { printf ("%02x%02x%02x%02x" "%02x%02x%02x%02x\n", np[0], np[1], np[2], np[3], np[4], np[5], np[6], np[7]); } } else { /* is 32 bit value */ ut32 n32 = (ut32) (n & UT32_MAX); ut8 *np = (ut8 *) &n32; if (flags & 1) { fwrite (&n32, sizeof (n32), 1, stdout); } else { printf ("%02x%02x%02x%02x\n", np[0], np[1], np[2], np[3]); } } fflush (stdout); return true; } else if (flags & (1 << 17)) { // -B (bin -> str) int i = 0; // TODO: move to r_util for (i = 0; i < strlen (str); i++) { ut8 ch = str[i]; printf ("%d%d%d%d" "%d%d%d%d", ch & 128? 1: 0, ch & 64? 1: 0, ch & 32? 1: 0, ch & 16? 1: 0, ch & 8? 1: 0, ch & 4? 1: 0, ch & 2? 1: 0, ch & 1? 1: 0); } return true; } else if (flags & (1 << 16)) { // -w ut64 n = r_num_math (num, str); if (n >> 31) { // is >32bit n = (st64) (st32) n; } else if (n >> 14) { n = (st64) (st16) n; } else if (n >> 7) { n = (st64) (st8) n; } printf ("%" PFMT64d "\n", n); fflush (stdout); return true; } else if (flags & (1 << 15)) { // -N ut64 n = r_num_math (num, str); if (n >> 32) { /* is 64 bit value */ ut8 *np = (ut8 *) &n; if (flags & 1) { fwrite (&n, sizeof (n), 1, stdout); } else { printf ("\\x%02x\\x%02x\\x%02x\\x%02x" "\\x%02x\\x%02x\\x%02x\\x%02x\n", np[0], np[1], np[2], np[3], np[4], np[5], np[6], np[7]); } } else { /* is 32 bit value */ ut32 n32 = (ut32) (n & UT32_MAX); ut8 *np = (ut8 *) &n32; if (flags & 1) { fwrite (&n32, sizeof (n32), 1, stdout); } else { printf ("\\x%02x\\x%02x\\x%02x\\x%02x\n", np[0], np[1], np[2], np[3]); } } fflush (stdout); return true; } else if (flags & (1 << 10)) { // -u char buf[8]; r_num_units (buf, sizeof (buf), r_num_math (NULL, str)); printf ("%s\n", buf); return true; } else if (flags & (1 << 11)) { // -t ut32 n = r_num_math (num, str); RPrint *p = r_print_new (); r_print_date_unix (p, (const ut8 *) &n, sizeof (ut32)); r_print_free (p); return true; } else if (flags & (1 << 12)) { // -E const int len = strlen (str); /* http://stackoverflow.com/questions/4715415/base64-what-is-the-worst-possible-increase-in-space-usage */ char *out = calloc (sizeof (char), (len + 2) / 3 * 4 + 1); // ceil(len/3)*4 plus 1 for NUL if (out) { r_base64_encode (out, (const ut8 *) str, len); printf ("%s%s", out, nl); fflush (stdout); free (out); } return true; } else if (flags & (1 << 13)) { // -D const int len = strlen (str); ut8 *out = calloc (sizeof (ut8), len / 4 * 3 + 1); if (out) { r_base64_decode (out, str, len); printf ("%s%s", out, nl); fflush (stdout); free (out); } return true; } else if (flags & 1 << 14) { // -F char *str = r_stdin_slurp (NULL); if (str) { char *res = r_hex_from_code (str); if (res) { printf ("%s\n", res); fflush (stdout); free (res); } else { eprintf ("Invalid input.\n"); } free (str); } return false; } else if (flags & (1 << 18)) { // -r char *asnum, unit[8]; char out[128]; ut32 n32, s, a; double d; float f; ut64 n = r_num_math (num, str); if (num->dbz) { eprintf ("RNum ERROR: Division by Zero\n"); return false; } n32 = (ut32) (n & UT32_MAX); asnum = r_num_as_string (NULL, n, false); memcpy (&f, &n32, sizeof (f)); memcpy (&d, &n, sizeof (d)); /* decimal, hexa, octal */ s = n >> 16 << 12; a = n & 0x0fff; r_num_units (unit, sizeof (unit), n); #if 0 eprintf ("%" PFMT64d " 0x%" PFMT64x " 0%" PFMT64o " %s %04x:%04x ", n, n, n, unit, s, a); if (n >> 32) { eprintf ("%" PFMT64d " ", (st64) n); } else { eprintf ("%d ", (st32) n); } if (asnum) { eprintf ("\"%s\" ", asnum); free (asnum); } /* binary and floating point */ r_str_bits (out, (const ut8 *) &n, sizeof (n), NULL); eprintf ("%s %.01lf %ff %lf\n", out, num->fvalue, f, d); #endif printf ("hex 0x%"PFMT64x"\n", n); printf ("octal 0%"PFMT64o"\n", n); printf ("unit %s\n", unit); printf ("segment %04x:%04x\n", s, a); if (n >> 32) { printf ("int64 %"PFMT64d"\n", (st64)n); } else { printf ("int32 %d\n", (st32)n); } if (asnum) { printf ("string \"%s\"\n", asnum); free (asnum); } /* binary and floating point */ r_str_bits64 (out, n); memcpy (&f, &n, sizeof (f)); memcpy (&d, &n, sizeof (d)); printf ("binary 0b%s\n", out); printf ("float: %ff\n", f); printf ("double: %lf\n", d); /* ternary */ r_num_to_trits (out, n); printf ("trits 0t%s\n", out); return true; } else if (flags & (1 << 19)) { // -L r_print_hex_from_bin (NULL, str); return true; } else if (flags & (1 << 21)) { // -i static const char start[] = "unsigned char buf[] = {"; printf (start); /* resonable amount of bytes per line */ const int byte_per_col = 12; for (i = 0; i < len-1; i++) { /* wrapping every N bytes */ if (i % byte_per_col == 0) { printf ("\n "); } printf ("0x%02x, ", (ut8) str[i]); } /* some care for the last element */ if (i % byte_per_col == 0) { printf("\n "); } printf ("0x%02x\n", (ut8) str[len-1]); printf ("};\n"); printf ("unsigned int buf_len = %d;\n", len); return true; } if (r_str_startswith (str, "0x")) { out_mode = (flags & 32)? '0': 'I'; } else if (r_str_startswith (str, "b")) { out_mode = 'B'; str++; } else if (r_str_startswith (str, "t")) { out_mode = 'T'; str++; } else if (r_str_startswith (str, "Fx")) { out_mode = 'F'; *str = '0'; } else if (r_str_startswith (str, "Bx")) { out_mode = 'B'; *str = '0'; } else if (r_str_startswith (str, "Tx")) { out_mode = 'T'; *str = '0'; } else if (r_str_startswith (str, "Ox")) { out_mode = 'O'; *str = '0'; } else if (r_str_endswith (str, "d")) { out_mode = 'I'; str[strlen (str) - 1] = 'b'; // TODO: Move print into format_output } else if (r_str_endswith (str, "f")) { out_mode = 'l'; } else if (r_str_endswith (str, "dt")) { out_mode = 'I'; str[strlen (str) - 2] = 't'; str[strlen (str) - 1] = '\0'; } while ((p = strchr (str, ' '))) { *p = 0; format_output (out_mode, str); str = p + 1; } if (*str) { format_output (out_mode, str); } return true; } static int use_stdin() { char *buf = calloc (1, STDIN_BUFFER_SIZE + 1); int l; // , sflag = (flags & 5); if (!buf) { return 0; } if (!(flags & (1<<14))) { for (l = 0; l >= 0 && l < STDIN_BUFFER_SIZE; l++) { // make sure we don't read beyond boundaries int n = read (0, buf + l, STDIN_BUFFER_SIZE - l); if (n < 1) { break; } l += n; if (buf[l - 1] == 0) { l--; continue; } buf[n] = 0; // if (sflag && strlen (buf) < STDIN_BUFFER_SIZE) // -S buf[STDIN_BUFFER_SIZE] = '\0'; if (!rax (buf, l, 0)) { break; } l = -1; } } else { l = 1; } if (l > 0) { rax (buf, l, 0); } free (buf); return 0; } R_API int r_core_main_rax2(int argc, char **argv) { int i; num = r_num_new (NULL, NULL, NULL); if (argc == 1) { use_stdin (); } else { for (i = 1; i < argc; i++) { rax (argv[i], 0, i == argc - 1); } } r_num_free (num); num = NULL; return 0; } int main(int argc, char **argv) { return r_core_main_rax2 (argc, argv); }
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/locationapi/X64/locationapi00000057.c
484
// Created file "Lib\src\locationapi\X64\locationapi" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(GUID_PROCESSOR_CORE_PARKING_MIN_CORES, 0x0cc5b647, 0xc1df, 0x4637, 0x89, 0x1a, 0xde, 0xc3, 0x5c, 0x31, 0x85, 0x83);
lgpl-3.0
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/LongCreativeTemplateVariable.php
1178
<?php namespace Google\AdsApi\Dfp\v201711; /** * This file was generated from WSDL. DO NOT EDIT. */ class LongCreativeTemplateVariable extends \Google\AdsApi\Dfp\v201711\CreativeTemplateVariable { /** * @var int $defaultValue */ protected $defaultValue = null; /** * @param string $label * @param string $uniqueName * @param string $description * @param boolean $isRequired * @param int $defaultValue */ public function __construct($label = null, $uniqueName = null, $description = null, $isRequired = null, $defaultValue = null) { parent::__construct($label, $uniqueName, $description, $isRequired); $this->defaultValue = $defaultValue; } /** * @return int */ public function getDefaultValue() { return $this->defaultValue; } /** * @param int $defaultValue * @return \Google\AdsApi\Dfp\v201711\LongCreativeTemplateVariable */ public function setDefaultValue($defaultValue) { $this->defaultValue = (!is_null($defaultValue) && PHP_INT_SIZE === 4) ? floatval($defaultValue) : $defaultValue; return $this; } }
lgpl-3.0
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/include/objects/biotree/BioTreeContainer.hpp
2831
/* $Id: BioTreeContainer.hpp 103491 2007-05-04 17:18:18Z kazimird $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ /// @file BioTreeContainer.hpp /// User-defined methods of the data storage class. /// /// This file was originally generated by application DATATOOL /// using the following specifications: /// 'biotree.asn'. /// /// New methods or data members can be added to it if needed. /// See also: BioTreeContainer_.hpp #ifndef OBJECTS_BIOTREE_BIOTREECONTAINER_HPP #define OBJECTS_BIOTREE_BIOTREECONTAINER_HPP // generated includes #include <objects/biotree/BioTreeContainer_.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: ///////////////////////////////////////////////////////////////////////////// class NCBI_BIOTREE_EXPORT CBioTreeContainer : public CBioTreeContainer_Base { typedef CBioTreeContainer_Base Tparent; public: // constructor CBioTreeContainer(void); // destructor ~CBioTreeContainer(void); size_t GetNodeCount() const; size_t GetLeafCount() const; private: // Prohibit copy constructor and assignment operator CBioTreeContainer(const CBioTreeContainer& value); CBioTreeContainer& operator=(const CBioTreeContainer& value); }; /////////////////// CBioTreeContainer inline methods // constructor inline CBioTreeContainer::CBioTreeContainer(void) { } /////////////////// end of CBioTreeContainer inline methods END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE #endif // OBJECTS_BIOTREE_BIOTREECONTAINER_HPP /* Original file checksum: lines: 94, chars: 2716, CRC32: ccfc4edf */
lgpl-3.0
huangye177/magate
src/main/java/ch/hefr/gridgroup/magate/em/SSLService.java
4030
package ch.hefr.gridgroup.magate.em; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.hefr.gridgroup.magate.MaGateEntity; import ch.hefr.gridgroup.magate.em.ssl.BlatAntNestController; import ch.hefr.gridgroup.magate.em.ssl.IBlatAntNestController; import ch.hefr.gridgroup.magate.em.ssl.IBlatAntNestObserver; import ch.hefr.gridgroup.magate.env.MaGateMessage; import ch.hefr.gridgroup.magate.env.MaGateParam; import ch.hefr.gridgroup.magate.storage.*; public class SSLService implements IResDiscovery { private static Log log = LogFactory.getLog(SSLService.class); private MaGateEntity maGate; private String maGateIdentity; // private int timeout = 500; private int counter = 0; private Map<String, String> results = new HashMap<String, String>(); private HashMap<String,Object> maGateProfile = new HashMap<String,Object>(); public SSLService(MaGateEntity maGate) { this.maGate = maGate; this.maGateIdentity = maGate.getMaGateIdentity(); // Create and preserve the profile of MaGate Node this.maGateProfile = new HashMap<String,Object>(); maGateProfile.put(MaGateMessage.MatchProfile_OS, this.maGate.getLRM().getOsType()); maGateProfile.put(MaGateMessage.MatchProfile_CPUCount, new Integer(this.maGate.getLRM().getNumOfPEPerResource())); maGateProfile.put(MaGateMessage.MatchProfile_VO, this.maGate.getLRM().getVO()); // maGateProfile.put(MaGateMessage.MatchProfile_ExePrice, new Double(-1.0)); this.maGate.setMaGateProfile(maGateProfile); // IMPORTANT: register a Nest for resource discovery try { this.maGate.getMaGateInfra().updateProfile(maGateIdentity, maGateProfile); } catch (Exception e) { e.printStackTrace(); } } /** * Send synchronous query for searching remote MaGates */ public String[] syncSearchRemoteNode(ConcurrentHashMap<String,Object> extQuery) { String queryId = this.maGateIdentity + "_" + java.util.UUID.randomUUID().toString(); String[] resultArray = null; this.results.put(queryId, ""); HashMap<String,Object> query = new HashMap<String,Object>(); query.put(MaGateMessage.MatchProfile_OS, extQuery.get(MaGateMessage.MatchProfile_OS)); query.put(MaGateMessage.MatchProfile_CPUCount, extQuery.get(MaGateMessage.MatchProfile_CPUCount)); try { // send the query this.maGate.getMaGateInfra().startQuery(this.maGateIdentity, queryId, query); // record the search issue int currentCommunitySearch = this.maGate.getStorage().getCommunitySearch().get(); this.maGate.getStorage().setCommunitySearch(new AtomicInteger(currentCommunitySearch + 1)); /*************************************************************************** * Sleep a while and collect the returned results while the time is reached ***************************************************************************/ Thread.sleep(MaGateParam.timeSearchCommunity); String result = this.results.get(queryId); resultArray = result.split("_"); // Remove Redundancy this.results.remove(queryId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // In case new nodes discovered, put them into the cached netowrkNeighbor Map NetworkNeighborsManager.cacheNetworkNeighbors(this.maGate, resultArray); return resultArray; } /** * Result found from the infrastructure */ public void onResultFound(String queryId, String matchedResult) { if(this.results.containsKey(queryId)) { String existResult = this.results.get(queryId); this.results.put(queryId, existResult + matchedResult + "_"); } else { this.results.put(queryId, matchedResult + "_"); } } public HashMap<String, Object> getMaGateProfile() { return maGateProfile; } }
lgpl-3.0
NeoFragCMS/neofrag-cms
modules/monitoring/monitoring.php
1215
<?php /** * https://neofr.ag * @author: Michaël BILCOT <[email protected]> */ namespace NF\Modules\Monitoring; use NF\NeoFrag\Addons\Module; class Monitoring extends Module { protected function __info() { return [ 'title' => 'Monitoring', 'description' => '', 'icon' => 'fas fa-heartbeat', 'link' => 'https://neofr.ag', 'author' => 'Michaël BILCOT & Jérémy VALENTIN <[email protected]>', 'license' => 'LGPLv3 <https://neofr.ag/license>', 'admin' => FALSE ]; } public function need_checking() { return ($this->config->nf_monitoring_last_check < ($time = strtotime('01:00')) && time() > $time) || !file_exists('cache/monitoring/monitoring.json'); } public function display() { if (file_exists('cache/monitoring/monitoring.json')) { foreach (array_merge(array_fill_keys(['danger', 'warning', 'info'], 0), array_count_values(array_map(function($a){ return $a[1]; }, json_decode(file_get_contents('cache/monitoring/monitoring.json'))->notifications))) as $class => $count) { if ($count) { return '<span class="float-right badge badge-'.$class.'">'.$count.'</span>'; } } } return ''; } }
lgpl-3.0
pcolby/libqtaws
src/kinesis/addtagstostreamrequest.h
1381
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_ADDTAGSTOSTREAMREQUEST_H #define QTAWS_ADDTAGSTOSTREAMREQUEST_H #include "kinesisrequest.h" namespace QtAws { namespace Kinesis { class AddTagsToStreamRequestPrivate; class QTAWSKINESIS_EXPORT AddTagsToStreamRequest : public KinesisRequest { public: AddTagsToStreamRequest(const AddTagsToStreamRequest &other); AddTagsToStreamRequest(); virtual bool isValid() const Q_DECL_OVERRIDE; protected: virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(AddTagsToStreamRequest) }; } // namespace Kinesis } // namespace QtAws #endif
lgpl-3.0
precice/precice
src/precice/impl/DataContext.cpp
2508
#include "precice/impl/DataContext.hpp" #include <memory> namespace precice { namespace impl { logging::Logger DataContext::_log{"impl::DataContext"}; DataContext::DataContext(mesh::PtrData data, mesh::PtrMesh mesh) { PRECICE_ASSERT(data); _providedData = data; PRECICE_ASSERT(mesh); _mesh = mesh; } mesh::PtrData DataContext::providedData() { PRECICE_ASSERT(_providedData); return _providedData; } mesh::PtrData DataContext::toData() { PRECICE_ASSERT(_toData); return _toData; } std::string DataContext::getDataName() const { PRECICE_ASSERT(_providedData); return _providedData->getName(); } int DataContext::getProvidedDataID() const { PRECICE_ASSERT(_providedData); return _providedData->getID(); } int DataContext::getFromDataID() const { PRECICE_TRACE(); PRECICE_ASSERT(hasMapping()); PRECICE_ASSERT(_fromData); return _fromData->getID(); } void DataContext::resetProvidedData() { PRECICE_TRACE(); _providedData->toZero(); } void DataContext::resetToData() { PRECICE_TRACE(); _toData->toZero(); } int DataContext::getToDataID() const { PRECICE_TRACE(); PRECICE_ASSERT(hasMapping()); PRECICE_ASSERT(_toData); return _toData->getID(); } int DataContext::getDataDimensions() const { PRECICE_TRACE(); PRECICE_ASSERT(_providedData); return _providedData->getDimensions(); } std::string DataContext::getMeshName() const { PRECICE_ASSERT(_mesh); return _mesh->getName(); } int DataContext::getMeshID() const { PRECICE_ASSERT(_mesh); return _mesh->getID(); } void DataContext::setMapping(MappingContext mappingContext, mesh::PtrData fromData, mesh::PtrData toData) { PRECICE_ASSERT(!hasMapping()); PRECICE_ASSERT(fromData); PRECICE_ASSERT(toData); _mappingContext = mappingContext; PRECICE_ASSERT(fromData == _providedData || toData == _providedData, "Either fromData or toData has to equal _providedData."); PRECICE_ASSERT(fromData->getName() == getDataName()); _fromData = fromData; PRECICE_ASSERT(toData->getName() == getDataName()); _toData = toData; PRECICE_ASSERT(_toData != _fromData); } bool DataContext::hasMapping() const { return hasReadMapping() || hasWriteMapping(); } bool DataContext::hasReadMapping() const { return _toData == _providedData; } bool DataContext::hasWriteMapping() const { return _fromData == _providedData; } const MappingContext DataContext::mappingContext() const { PRECICE_ASSERT(hasMapping()); return _mappingContext; } } // namespace impl } // namespace precice
lgpl-3.0
nerd4j/nerd4j-csv
src/main/java/org/nerd4j/csv/reader/binding/CSVToModelBinderFactory.java
1901
/* * #%L * Nerd4j CSV * %% * Copyright (C) 2013 Nerd4j * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package org.nerd4j.csv.reader.binding; import org.nerd4j.csv.exception.CSVToModelBindingException; import org.nerd4j.csv.reader.CSVReaderMetadata; import org.nerd4j.csv.registry.CSVRegistryEntry; /** * Represents a {@code Factory} able to build and configure * {@link CSVToModelBinder}s which populates data models of the given type. * * @param <Model> type of the model returned by the builder. * * @author Nerd4j Team */ public interface CSVToModelBinderFactory<Model> extends CSVRegistryEntry { /** * Returns a new CSV model binder which builds * and fills the data model objects of the * specified type. * * @param configuration used to configure the binding. * @param columnMapping used to map columns with model. * @return a new CSV model binder. * @throws CSVToModelBindingException if binding configuration is inconsistent. */ public CSVToModelBinder<Model> getCSVToModelBinder( final CSVReaderMetadata<Model> configuration, final Integer[] columnMapping ) throws CSVToModelBindingException; }
lgpl-3.0
mentallxm/iwshop
static/script/Wdmin/products/alter_categroy.js
2214
/* global shoproot */ /** * 编辑分类 * @description Hope You Do Good But Not Evil * @copyright Copyright 2014-2015 <[email protected]> * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @author Chenyong Cai <[email protected]> * @package Wshop * @link http://www.iwshop.cn */ requirejs(['jquery', 'util', 'fancyBox', 'jUploader'], function ($, Util, fancyBox, jUploader) { $(function () { $("#pd-cat-select").find("option[value='" + $('#cat_parent').val() + "']").get(0).selected = true; $('#del-cate').click(function () { if (confirm('你确定要删除这个分类吗')) { $.post('?/wProduct/ajaxDelCategroy/', { id: $('#cat_id').val() }, function (r) { r = parseInt(r); if (r > 0) { alert('删除成功'); window.parent.fnDelSelectCat(); window.parent.location.reload(); } }); } }); // alter $('#save-cate').click(function () { var data = $('#catForm').serializeArray(); $.post('?/wProduct/ajaxAlterCategroy/', { id: $('#cat_id').val(), data: data }, function (r) { r = parseInt(r); if (r > 0) { Util.Alert('保存成功'); window.parent.fnReloadTree(); } else { Util.Alert('保存失败'); } }); }); $.jUploader({ button: 'alter_categroy_image', action: '?/wImages/ImageUpload/', onComplete: function (fileName, response) { if (response.ret_code == 0) { $('#cat_image_src').val(response.ret_msg); $('#catimage').attr('src', response.ret_msg).show(); $('#cat_none_pic').hide(); Util.Alert('上传图片成功'); } else { Util.Alert('上传图片失败'); } } }); }); });
lgpl-3.0
joebandenburg/textsecure-server-node
lib/IncomingPushMessageSignalProtos.js
7889
module.exports = require("protobufjs").newBuilder({})["import"]({ "package": "textsecure", "messages": [ { "name": "IncomingPushMessageSignal", "fields": [ { "rule": "optional", "options": {}, "type": "Type", "name": "type", "id": 1 }, { "rule": "optional", "options": {}, "type": "string", "name": "source", "id": 2 }, { "rule": "optional", "options": {}, "type": "uint32", "name": "sourceDevice", "id": 7 }, { "rule": "optional", "options": {}, "type": "string", "name": "relay", "id": 3 }, { "rule": "optional", "options": {}, "type": "uint64", "name": "timestamp", "id": 5 }, { "rule": "optional", "options": {}, "type": "bytes", "name": "message", "id": 6 } ], "enums": [ { "name": "Type", "values": [ { "name": "UNKNOWN", "id": 0 }, { "name": "CIPHERTEXT", "id": 1 }, { "name": "KEY_EXCHANGE", "id": 2 }, { "name": "PREKEY_BUNDLE", "id": 3 }, { "name": "PLAINTEXT", "id": 4 }, { "name": "RECEIPT", "id": 5 } ], "options": {} } ], "messages": [], "options": {}, "oneofs": {} }, { "name": "PushMessageContent", "fields": [ { "rule": "optional", "options": {}, "type": "string", "name": "body", "id": 1 }, { "rule": "repeated", "options": {}, "type": "AttachmentPointer", "name": "attachments", "id": 2 }, { "rule": "optional", "options": {}, "type": "GroupContext", "name": "group", "id": 3 }, { "rule": "optional", "options": {}, "type": "uint32", "name": "flags", "id": 4 } ], "enums": [ { "name": "Flags", "values": [ { "name": "END_SESSION", "id": 1 } ], "options": {} } ], "messages": [ { "name": "AttachmentPointer", "fields": [ { "rule": "optional", "options": {}, "type": "fixed64", "name": "id", "id": 1 }, { "rule": "optional", "options": {}, "type": "string", "name": "contentType", "id": 2 }, { "rule": "optional", "options": {}, "type": "bytes", "name": "key", "id": 3 } ], "enums": [], "messages": [], "options": {}, "oneofs": {} }, { "name": "GroupContext", "fields": [ { "rule": "optional", "options": {}, "type": "bytes", "name": "id", "id": 1 }, { "rule": "optional", "options": {}, "type": "Type", "name": "type", "id": 2 }, { "rule": "optional", "options": {}, "type": "string", "name": "name", "id": 3 }, { "rule": "repeated", "options": {}, "type": "string", "name": "members", "id": 4 }, { "rule": "optional", "options": {}, "type": "AttachmentPointer", "name": "avatar", "id": 5 } ], "enums": [ { "name": "Type", "values": [ { "name": "UNKNOWN", "id": 0 }, { "name": "UPDATE", "id": 1 }, { "name": "DELIVER", "id": 2 }, { "name": "QUIT", "id": 3 } ], "options": {} } ], "messages": [], "options": {}, "oneofs": {} } ], "options": {}, "oneofs": {} } ], "enums": [], "imports": [], "options": { "java_package": "org.whispersystems.textsecure.push", "java_outer_classname": "PushMessageProtos" }, "services": [] }).build("textsecure");
lgpl-3.0
ziyoucaishi/marketplace
db/migrate/20151204083028_drop_community_plans.rb
452
class DropCommunityPlans < ActiveRecord::Migration def up drop_table :community_plans end def down create_table "community_plans" do |t| t.integer "community_id", :null => false t.integer "plan_level", :default => 0, :null => false t.datetime "expires_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end end end
lgpl-3.0
Christux/Arduino
NodeMCU_LedStrip/LedStrip.h
1097
/* * Copyright (c) 2017 Christophe Rubeck. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LedStrip_h #define LedStrip_h #include "Arduino.h" class LedStrip { protected: const uint8_t _nLeds; uint8_t *_leds; uint8_t *_ledPins; public: LedStrip(uint8_t pin1, uint8_t pin2, uint8_t pin3, uint8_t pin4); ~LedStrip(); void setup() const; void show() const; void all(); void set(uint8_t i, uint8_t val); uint8_t get(uint8_t i) const; void reset(); }; #endif
lgpl-3.0
TheAnswer/FirstTest
bin/scripts/slashcommands/generic/launchFirework.lua
2777
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 LaunchFireworkSlashCommand = { name = "launchfirework", alternativeNames = "", animation = "", invalidStateMask = 3963615227, --cover, combat, aiming, alert, berzerk, feigndeath, combatAttitudeEvasive, combatAttitudeNormal, combatAttitudeAggressive, tumbling, stunned, blinded, dizzy, intimidated, immobilized, frozen, swimming, sittingOnChair, crafting, glowingJedi, onFire, ridingMount, pilotingShip, shipOperations, shipGunner, invalidPostures = "3,2,5,6,7,8,9,10,11,12,13,14,4,", target = 2, targeType = 1, disabled = 0, maxRangeToTarget = 0, --adminLevel = 0, addToCombatQueue = 1, } AddLaunchFireworkSlashCommand(LaunchFireworkSlashCommand)
lgpl-3.0
BugBuster1701/backend_user_online
dca/tl_member.php
560
<?php /** * Contao Open Source CMS, Copyright (C) 2005-2013 Leo Feyer * * Module Backend User Online - DCA * * @copyright Glen Langer 2012..2013 <http://www.contao.glen-langer.de> * @author Glen Langer (BugBuster) * @package BackendUserOnline * @license LGPL * @filesource * @see https://github.com/BugBuster1701/backend_user_online */ /** * DCA Config, overwrite label_callback */ $GLOBALS['TL_DCA']['tl_member']['list']['label']['label_callback'] = array('BugBuster\BackendUserOnline\DCA_member_onlineicon','addIcon');
lgpl-3.0
ubccr/supremm
src/supremm/datadumper.py
6457
""" X """ import cPickle as pickle import os import numpy import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class PlotInterface(object): def plot_timeseries(self, times, values): pass def plot_sinwave(self, times, sinewave): pass def plot_area_ratio(self, on_period_area, off_period_area): pass def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold): pass def plot_acf(self, times, acf): pass def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx): pass def show(self): pass class ImageOutput(PlotInterface): """ Output the timeseries data and the period estimate as plot in png format """ def __init__(self, jobid, metricname): ijobid = int(jobid) top = (ijobid / 1000000) middle = (ijobid / 1000) % 1000 try: os.makedirs("{}/{}".format(top, middle)) except OSError: pass self.outfilename = "{}/{}/{}_{}.png".format(top, middle, jobid, metricname) self.fig = plt.figure() self.data_ax = plt.subplot(211, xlabel='Elapsed time (s)', ylabel='Data rate (MB/s)') self.sine_ax = None self.verbose = False def plot_timeseries(self, times, values): self.data_ax.plot(times, values / 1024.0 / 1024.0, label='Timeseries') def plot_sinwave(self, times, sinewave): self.sine_ax = plt.subplot(212, xlabel='Elapsed time (s)', ylabel='Data rate (MB/s)') self.sine_ax.plot(times, sinewave / 1024.0 / 1024.0, label='Estimate') def show(self): self.fig.tight_layout() self.fig.savefig(self.outfilename, format='png', transparent=True) class Dumper(object): def __init__(self, filename='data.dat'): self.filename = filename self.data = {} self.verbose = True def plot_timeseries(self, times, values): self.data['timeseries'] = (times, values) def plot_sinwave(self, times, sinewave): self.data['sinewave'] = (times, sinewave) def plot_area_ratio(self, on_period_area, off_period_area): self.data['area_ratio'] = (on_period_area, off_period_area) def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold): self.data['periodogram'] = (periods, powers, hints, power_threshold, time_threshold) def plot_acf(self, times, acf): self.data['acf'] = (times, acf) def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx): self.data['acf_validation'] = (times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx) def show(self): with open(self.filename, 'wb') as fp: pickle.dump(self.data, fp) def load(self): with open(self.filename, 'rb') as fp: self.data = pickle.load(fp) class Plotter(object): def __init__(self, title="Autoperiod", filename='output.pdf', figsize=(4, 3), verbose=False): self.title = title self.filename = filename self.fig = plt.figure() self.figsize = figsize self.verbose = verbose self.timeseries_ax = plt.subplot2grid((3, 10), (0, 0), colspan=9, xlabel='Times', ylabel='Values') self.area_ratio_ax = plt.subplot2grid((3, 10), (0, 9), colspan=1, xticks=(1, 2), xticklabels=("on", "off")) self.area_ratio_ax.get_yaxis().set_visible(False) self.periodogram_ax = plt.subplot2grid((3, 10), (1, 0), colspan=10, xlabel='Period', ylabel='Power') self.acf_ax = plt.subplot2grid((3, 10), (2, 0), colspan=10, xlabel='Lag', ylabel='Correlation') self.time_threshold = None def plot_timeseries(self, times, values): self.timeseries_ax.plot(times, values, label='Timeseries') self.timeseries_ax.legend() def plot_sinwave(self, times, sinwave): self.timeseries_ax.plot(times, sinwave, label='Estimated Period') self.timeseries_ax.legend() def plot_area_ratio(self, on_period_area, off_period_area): self.area_ratio_ax.bar(1, on_period_area) self.area_ratio_ax.bar(2, off_period_area) self.area_ratio_ax.legend() def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold): self.time_threshold = time_threshold self.periodogram_ax.plot(periods, powers, label='Periodogram') self.periodogram_ax.scatter([p for i, p in hints], [powers[i] for i, p in hints], c='red', marker='x', label='Period Hints') self.periodogram_ax.axhline(power_threshold, color='green', linewidth=1, linestyle='dashed', label='Min Power') #self.periodogram_ax.axvline(time_threshold, c='purple', linewidth=1, linestyle='dashed', label='Max Period') self.periodogram_ax.legend() self.periodogram_ax.set_xlim([0, self.time_threshold]) def plot_acf(self, times, acf): self.acf_ax.plot(times, acf, '-o', lw=0.5, ms=2, label='Autocorrelation') if self.time_threshold is not None: self.acf_ax.set_xlim([0, self.time_threshold]) self.acf_ax.legend() def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx): self.acf_ax.plot(times1, c1 + m1 * times1, c='r', label='Slope: {}, Error: {}'.format(m1, err1)) self.acf_ax.plot(times2, c2 + m2 * times2, c='r', label='Slope: {}, Error: {}'.format(m2, err2)) self.acf_ax.scatter(times[split_idx], acf[split_idx], c='y', label='Split point: {}'.format(times[split_idx])) self.acf_ax.scatter(times[peak_idx], acf[peak_idx], c='g', label='Peak point: {}'.format(times[peak_idx])) self.acf_ax.legend() def show(self): self.fig.tight_layout() if self.filename: self.fig.set_size_inches(*self.figsize) self.fig.savefig(self.filename, format='pdf', facecolor=self.fig.get_facecolor()) def main(): """ X """ d = Dumper('gpfs-fsios-write_bytes_data.dat') d.load() p = Plotter() p.plot_timeseries(*d.data['timeseries']) p.plot_sinwave(*d.data['sinewave']) p.plot_area_ratio(*d.data['area_ratio']) p.plot_periodogram(*d.data['periodogram']) p.plot_acf(*d.data['acf']) p.plot_acf_validation(*d.data['acf_validation']) p.show() if __name__ == "__main__": main()
lgpl-3.0
andreas-steffens/btree-framework-demonstration
src/btreetest/testbench/tests/regression/btreemaptestbench.h
29716
/************************************************************ ** ** file: btreemaptestbench.h ** author: Andreas Steffens ** license: LGPL v3 ** ** description: ** ** This file contains code for the b-tree framework's test bench ** exercising functional, code coverage and regression tests ** for the map application class. ** ************************************************************/ #ifndef BTREEMAPTESTBENCH_H #define BTREEMAPTESTBENCH_H #include <stdint.h> #include <map> #include <list> #include <vector> #include <type_traits> #include "testbench/application_classes/regression/btreetestmap.h" #include "testbench/primitives/btreecommonprimitives.h" #include "testbench/common/btreetestcommon.h" #include "testbench/wrapper_classes/btreemaptestwrapper.h" #include "testbench/tests/regression/btreemultimaptestbench.h" #include "specific_data_classes/btreemap.h" template<class _t_key, class _t_map> class CBTreeTestBenchMultiMap; typedef enum { BTREETEST_MAP_ASSIGNMENT_OPERATOR, BTREETEST_MAP_MOVE_CONSTRUCTOR_AND_ASSIGNMENT, BTREETEST_MAP_STL_IF_INSERT = 1000, BTREETEST_MAP_STL_IF_INSERT_VIA_ITERATOR, BTREETEST_MAP_STL_IF_ERASE_VIA_ITERATOR, BTREETEST_MAP_STL_IF_ERASE_VIA_KEY, BTREETEST_MAP_STL_IF_ERASE_VIA_ITERATOR_MULTIPLE, BTREETEST_MAP_STL_IF_KEY_COMP, BTREETEST_MAP_STL_IF_VALUE_COMP, BTREETEST_MAP_STL_IF_SWAP, BTREETEST_MAP_STL_IF_FIND, BTREETEST_MAP_STL_IF_LOWER_BOUND_UPPER_BOUND, BTREETEST_MAP_STL_IF_EMPLACE, BTREETEST_MAP_STL_IF_EMPLACE_HINT, BTREETEST_MAP_STL_IF_EMPLACE_HINT_MINOR, BTREETEST_MAP_STL_IF_EMPLACE_HINT_SIGNIFICANT, BTREETEST_MAP_STL_IF_EMPLACE_HINT_LARGE, BTREETEST_MAP_STL_IF_INSERT_HINT, BTREETEST_MAP_STL_IF_INSERT_HINT_MINOR, BTREETEST_MAP_STL_IF_INSERT_HINT_SIGNIFICANT, BTREETEST_MAP_STL_IF_INSERT_HINT_LARGE, BTREETEST_MAP_STL_IF_EMPLACE_VIA_CTOR, BTREETEST_MAP_STL_IF_EMPLACE_HINT_VIA_CTOR, BTREETEST_MAP_STL_IF_EQUAL_RANGE, } btreetest_map_t; typedef enum { BTREETEST_MAP_STL_IF_INSERT_VIA_ITERATOR_PART, BTREETEST_MAP_STL_IF_INSERT_VIA_ITERATOR_SAME_OR_EQUIVALENT, BTREETEST_MAP_STL_IF_INSERT_VIA_ITERATOR_SELF_REFERENCE, BTREETEST_MAP_STL_IF_INSERT_VIA_ITERATOR_PART_EXTERN, BTREETEST_MAP_STL_IF_INSERT_VIA_ITERATOR_SAME_OR_EQUIVALENT_EXTERN, } btreetest_map_stl_if_insert_via_iterator_e; template<class _t_key, class _t_map> class CBTreeTestBenchMap : public ::std::map<_t_key, _t_map> { public: CBTreeTestBenchMap<_t_key, _t_map> () : ::std::map<_t_key, _t_map> () {}; CBTreeTestBenchMap<_t_key, _t_map> (const CBTreeTestBenchMap &rMap) : ::std::map<_t_key, _t_map> (rMap) {}; explicit CBTreeTestBenchMap<_t_key, _t_map> (const ::std::map<_t_key, _t_map> &rMap) : ::std::map<_t_key, _t_map> (rMap) {}; ~CBTreeTestBenchMap<_t_key, _t_map> () {}; template<class _t_iterator> void insert (const typename ::std::map<_t_key, _t_map>::iterator &rDummyIter, _t_iterator &rIterFirst, _t_iterator &rIterLast) { rDummyIter; ::std::map<_t_key, _t_map>::insert (rIterFirst, rIterLast); }; template<class _t_iterator> void insert (const typename ::std::map<_t_key, _t_map>::const_iterator &rDummyIter, _t_iterator &rIterFirst, _t_iterator &rIterLast) { rDummyIter; ::std::map<_t_key, _t_map>::insert (rIterFirst, rIterLast); }; template<class _t_iterator> void insert (_t_iterator &rIterFirst, _t_iterator &rIterLast) { ::std::map<_t_key, _t_map>::insert (rIterFirst, rIterLast); }; // this version of insert only returns an iterator, instead of pair<iterator, bool>, although // this class is derived from ::std::map // - the masking of the bool component of this method has been done to make it interface compatible // with any other associative container class, when set as a template parameter typename ::std::map<_t_key, _t_map>::iterator insert (const typename ::std::map<_t_key, _t_map>::value_type &rVal) { ::std::pair<typename ::std::map<_t_key, _t_map>::iterator, bool> sRetval; if (::std::map<_t_key, _t_map>::count (rVal.first) == 0) { sRetval = ::std::map<_t_key, _t_map>::insert (rVal); return (sRetval.first); } else { return (::std::map<_t_key, _t_map>::end ()); } }; }; typedef CBTreeTestBenchMap<uint32_t, mapMap_t> map_reference_t; template<class _t_container, class _t_iterator> void TestBTreeMapSTLifInsertViaIteratorPart (const char *pszTitle, int nArg, uint32_t nNumInstances, uint32_t nNumEntries, _t_container *pContainer, _t_iterator &rIter) { uint32_t nLastKey; uint32_t i; _t_iterator sIterBegin; _t_iterator sIterEnd; ::std::cout << pszTitle << ::std::endl << ::std::flush; for (i = 0; i < nNumInstances; i++) { nLastKey = 0; associative_container_add_primitive (pContainer, nNumEntries, 0, nLastKey, BTREETEST_KEY_GENERATION_RANDOM); } get_begin (pContainer, sIterBegin); get_end (pContainer, sIterEnd); ::std::advance (sIterBegin, nArg); ::std::advance (sIterEnd, 0 - nArg); if (!is_const_iterator (pContainer, sIterBegin)) { if (!is_reverse_iterator (pContainer, sIterBegin)) { typename _t_container::test_iterator sIter; pContainer->insert_self_reference (sIterBegin, sIterEnd, sIter); } else { typename _t_container::test_reverse_iterator sRIter; pContainer->insert_self_reference (sIterBegin, sIterEnd, sRIter); } } else { if (!is_reverse_iterator (pContainer, sIterBegin)) { typename _t_container::test_const_iterator sCIter; pContainer->insert_self_reference (sIterBegin, sIterEnd, sCIter); } else { typename _t_container::test_const_reverse_iterator sCRIter; pContainer->insert_self_reference (sIterBegin, sIterEnd, sCRIter); } } pContainer->clear (); } template<class _t_dest_container, class _t_src_container, class _t_dest_iterator, class _t_src_iterator> void TestBTreeMapSTLifInsertViaIteratorPart (const char *pszTitle, int nArg, uint32_t nNumInstances, uint32_t nNumEntries, _t_dest_container *pDestContainer, _t_src_container *pSrcContainer, _t_dest_iterator &rDestIter, _t_src_iterator &rSrcIter) { uint32_t nLastKey; uint32_t i; _t_src_iterator sSrcIterBegin; _t_src_iterator sSrcIterEnd; ::std::cout << pszTitle << ::std::endl << ::std::flush; for (i = 0; i < nNumInstances; i++) { nLastKey = 0; associative_container_add_primitive (pSrcContainer, nNumEntries, 0, nLastKey, BTREETEST_KEY_GENERATION_RANDOM); } get_begin (pSrcContainer, sSrcIterBegin); get_end (pSrcContainer, sSrcIterEnd); ::std::advance (sSrcIterBegin, nArg); ::std::advance (sSrcIterEnd, 0 - nArg); pDestContainer->insert (sSrcIterBegin, sSrcIterEnd); pDestContainer->clear (); pSrcContainer->clear (); } template<class _t_dest_container, class _t_src_container, class _t_dest_iterator, class _t_src_iterator> void TestBTreeMapSTLifInsertViaIteratorSame (const char *pszTitle, int nArg, uint32_t nNumInstances, uint32_t nNumEntries, _t_dest_container *pDestContainer, _t_src_container *pSrcContainer, _t_dest_iterator &rDestIter, _t_src_iterator &rSrcIter) { uint32_t nLastKey; uint32_t i; _t_src_iterator sSrcIterBegin; _t_src_iterator sSrcIterEnd; _t_src_iterator sSrcIterA; _t_src_iterator sSrcIterB; _t_dest_iterator sDestIterA; ::std::cout << pszTitle << ::std::endl << ::std::flush; for (i = 0; i < nNumInstances; i++) { nLastKey = 0; associative_container_add_primitive (pSrcContainer, nNumEntries, 0, nLastKey, BTREETEST_KEY_GENERATION_RANDOM); } get_end (pSrcContainer, sSrcIterEnd); get_begin (pSrcContainer, sSrcIterA); get_begin (pSrcContainer, sSrcIterB); while (sSrcIterA != sSrcIterEnd) { pDestContainer->insert (sSrcIterA, sSrcIterB); ::std::advance (sSrcIterA, 1); ::std::advance (sSrcIterB, 1); } if (pDestContainer != pSrcContainer) { if (pDestContainer->size () != 0) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSame: destination container ought to be empty!" << ::std::endl; exit (-1); } } else { if (pDestContainer->size () != pSrcContainer->size ()) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSame: destination container and source container mismatch in size!" << ::std::endl; exit (-1); } } get_begin (pSrcContainer, sSrcIterA); while (sSrcIterA != sSrcIterEnd) { pDestContainer->insert (sSrcIterA, sSrcIterA); ::std::advance (sSrcIterA, 1); } if (pDestContainer != pSrcContainer) { if (pDestContainer->size () != 0) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSame: destination container ought to be empty! (2)" << ::std::endl; exit (-1); } } else { if (pDestContainer->size () != pSrcContainer->size ()) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSame: destination container and source container mismatch in size! (2)" << ::std::endl; exit (-1); } } pDestContainer->clear (); pSrcContainer->clear (); } template<class _t_dest_container, class _t_src_container, class _t_ext_container, class _t_dest_iterator, class _t_src_iterator, class _t_ext_iterator> void TestBTreeMapSTLifInsertViaIteratorPartExtern (const char *pszTitle, int nArg, uint32_t nNumInstances, uint32_t nNumEntries, _t_dest_container *pDestContainer, _t_src_container *pSrcContainer, _t_ext_container *pExtContainer, _t_dest_iterator &rDestIter, _t_src_iterator &rSrcIter, _t_ext_iterator &rExtIter) { uint32_t nLastKey; uint32_t i; _t_src_iterator sSrcIterBegin; _t_src_iterator sSrcIterA; _t_src_iterator sSrcIterB; _t_dest_iterator sDestIterA; ::std::cout << pszTitle << ::std::endl << ::std::flush; for (i = 0; i < nNumInstances; i++) { nLastKey = 0; associative_container_add_primitive (pSrcContainer, nNumEntries, 0, nLastKey, BTREETEST_KEY_GENERATION_RANDOM); } _t_ext_iterator sExtIterBegin; _t_ext_iterator sExtIterEnd; get_begin (pExtContainer, sExtIterBegin); get_begin (pSrcContainer, sSrcIterA); sSrcIterBegin = sSrcIterA; get_end (pSrcContainer, sSrcIterB); ::std::advance (sSrcIterA, nArg); ::std::advance (sSrcIterB, 0 - nArg); pSrcContainer->test_all_containers_insert (pExtContainer, sExtIterBegin, sSrcIterBegin, sSrcIterA, sSrcIterB); get_begin (pExtContainer, sExtIterBegin); get_end (pExtContainer, sExtIterEnd); pDestContainer->insert (sExtIterBegin, sExtIterEnd); pDestContainer->clear (); pSrcContainer->clear (); pExtContainer->clear (); } template<class _t_container, class _t_iterator, class _t_ext_iterator> void generic_insert (_t_container *pContainer, const _t_iterator &rIterPos, _t_ext_iterator &rExtFirst, _t_ext_iterator &rExtLast, ::std::true_type) { rIterPos; pContainer->insert (rExtFirst, rExtLast); } template<class _t_container, class _t_iterator, class _t_ext_iterator> void generic_insert (_t_container *pContainer, const _t_iterator &rIterPos, _t_ext_iterator &rExtFirst, _t_ext_iterator &rExtLast, ::std::false_type) { // pContainer->insert (rIterPos, rExtFirst, rExtLast); container_insert (pContainer, rIterPos, rExtFirst, rExtLast); } template<class _t_dest_container, class _t_src_container, class _t_ext_container, class _t_dest_iterator, class _t_src_iterator, class _t_ext_iterator> void TestBTreeMapSTLifInsertViaIteratorSameExtern (const char *pszTitle, int nArg, uint32_t nNumInstances, uint32_t nNumEntries, _t_dest_container *pDestContainer, _t_src_container *pSrcContainer, _t_ext_container *pExtContainer, _t_dest_iterator &rDestIter, _t_src_iterator &rSrcIter, _t_ext_iterator &rExtIter) { typedef typename ::std::map<typename _t_ext_iterator::value_type::first_type, typename _t_ext_iterator::value_type::second_type> map_t; typedef typename ::std::multimap<typename _t_ext_iterator::value_type::first_type, typename _t_ext_iterator::value_type::second_type> mmap_t; typename ::std::conditional< ::std::is_same<_t_ext_container, map_t> ::value || ::std::is_same<_t_ext_container, mmap_t> ::value, ::std::true_type, ::std::false_type> ::type sSelectInsertMethod; uint32_t nLastKey; uint32_t i; _t_src_iterator sSrcIterBegin; _t_src_iterator sSrcIterEnd; _t_src_iterator sSrcIterA; _t_src_iterator sSrcIterB; _t_dest_iterator sDestIterA; ::std::cout << pszTitle << ::std::endl << ::std::flush; for (i = 0; i < nNumInstances; i++) { nLastKey = 0; associative_container_add_primitive (pSrcContainer, nNumEntries, 0, nLastKey, BTREETEST_KEY_GENERATION_RANDOM); } get_begin (pSrcContainer, sSrcIterBegin); get_end (pSrcContainer, sSrcIterEnd); generic_insert (pExtContainer, pExtContainer->cbegin (), sSrcIterBegin, sSrcIterEnd, sSelectInsertMethod); _t_ext_iterator sExtIter; get_begin (pExtContainer, sExtIter); get_begin (pSrcContainer, sSrcIterA); get_begin (pSrcContainer, sSrcIterB); while (sSrcIterA != sSrcIterEnd) { pDestContainer->test_all_containers_insert (pExtContainer, sExtIter, sSrcIterBegin, sSrcIterA, sSrcIterB); ::std::advance (sSrcIterA, 1); ::std::advance (sSrcIterB, 1); ::std::advance (sExtIter, 1); } if (pDestContainer != pSrcContainer) { if (pDestContainer->size () != 0) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSameExtern: destination container ought to be empty!" << ::std::endl; exit (-1); } } else { if (pDestContainer->size () != pSrcContainer->size ()) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSameExtern: destination container and source container mismatch in size!" << ::std::endl; exit (-1); } } get_begin (pSrcContainer, sSrcIterA); sSrcIterBegin = sSrcIterA; while (sSrcIterA != sSrcIterEnd) { pDestContainer->test_all_containers_insert (pSrcContainer, sSrcIterA, sSrcIterBegin, sSrcIterA, sSrcIterA); ::std::advance (sSrcIterA, 1); ::std::cout << "*" << ::std::flush; } ::std::cout << ::std::endl; if (pDestContainer != pSrcContainer) { if (pDestContainer->size () != 0) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSameExtern: destination container ought to be empty! (2)" << ::std::endl; exit (-1); } } else { if (pDestContainer->size () != pSrcContainer->size ()) { ::std::cerr << "TestBTreeMapSTLifInsertViaIteratorSameExtern: destination container and source container mismatch in size! (2)" << ::std::endl; exit (-1); } } pDestContainer->clear (); pSrcContainer->clear (); } template<class _t_map> void TestBTreeMapSTLifInsertViaIterator (_t_map *pClM, uint32_t nNumEntries) { typedef typename _t_map::value_type value_t; typedef typename value_t::second_type second_type; typedef typename _t_map::iterator iter_t; typedef typename _t_map::const_iterator citer_t; typedef typename _t_map::reverse_iterator riter_t; typedef typename _t_map::const_reverse_iterator criter_t; typedef typename ::std::list<value_t>::iterator itlist_t; typedef typename ::std::list<value_t>::const_iterator citlist_t; typedef typename ::std::list<value_t>::reverse_iterator ritlist_t; typedef typename ::std::list<value_t>::const_reverse_iterator critlist_t; typedef typename ::std::vector<value_t>::iterator itvec_t; typedef typename ::std::vector<value_t>::const_iterator citvec_t; typedef typename ::std::vector<value_t>::reverse_iterator ritvec_t; typedef typename ::std::vector<value_t>::const_reverse_iterator critvec_t; typedef typename ::std::map<uint32_t, second_type>::iterator itmap_t; typedef typename ::std::map<uint32_t, second_type>::const_iterator citmap_t; typedef typename ::std::map<uint32_t, second_type>::reverse_iterator ritmap_t; typedef typename ::std::map<uint32_t, second_type>::const_reverse_iterator critmap_t; typedef typename ::std::multimap<uint32_t, second_type>::iterator itmmap_t; typedef typename ::std::multimap<uint32_t, second_type>::const_iterator citmmap_t; typedef typename ::std::multimap<uint32_t, second_type>::reverse_iterator ritmmap_t; typedef typename ::std::multimap<uint32_t, second_type>::const_reverse_iterator critmmap_t; _t_map sClMMTarget (*pClM); uint32_t nLastKey = 0; iter_t sIterA, sIterB; citer_t sCIterA, sCIterB; riter_t sRIterA, sRIterB; criter_t sCRIterA, sCRIterB; ::std::list<value_t> sList; ::std::vector<value_t> sVector; itlist_t sItList; citlist_t sCItList; ritlist_t sRItList; critlist_t sCRItList; itvec_t sItVec; citvec_t sCItVec; ritvec_t sRItVec; critvec_t sCRItVec; value_t sMapPairData; CBTreeTestBenchMap<uint32_t, second_type> sMap; itmap_t sItMap; citmap_t sCItMap; ritmap_t sRItMap; critmap_t sCRItMap; CBTreeTestBenchMultiMap<uint32_t, second_type> sMMap; itmmap_t sItMMap; citmmap_t sCItMMap; ritmmap_t sRItMMap; critmmap_t sCRItMMap; ::std::cout << "exercises method compatible to STL interface CBTreeMap[Multi]<>:: insert<_t_iterator> (_t_iterator, _t_iterator)" << ::std::endl; TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::iter_t> (iter_t, iter_t)", 0, 2, nNumEntries, &sClMMTarget, pClM, sIterA, sIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::citer_t> (citer_t, citer_t)", 0, 2, nNumEntries, &sClMMTarget, pClM, sCIterA, sCIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::riter_t> (riter_t, riter_t)", 0, 2, nNumEntries, &sClMMTarget, pClM, sRIterA, sRIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::criter_t> (criter_t, criter_t)", 0, 2, nNumEntries, &sClMMTarget, pClM, sCRIterA, sCRIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::iter_t> (iter_t == iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, sIterA, sIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::citer_t> (citer_t == citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, sCIterA, sCIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::riter_t> (riter_t == riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, sRIterA, sRIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::criter_t> (criter_t == criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, sCRIterA, sCRIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::iter_t> (>iter_t, iter_t<)", (int) (nNumEntries / 4), 1, nNumEntries, &sClMMTarget, pClM, sIterA, sIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::citer_t> (>citer_t, citer_t<)", (int) (nNumEntries / 4), 1, nNumEntries, &sClMMTarget, pClM, sCIterA, sCIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::riter_t> (>riter_t, riter_t<)", (int) (nNumEntries / 4), 1, nNumEntries, &sClMMTarget, pClM, sRIterA, sRIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::criter_t> (>criter_t, criter_t<)", (int) (nNumEntries / 4), 1, nNumEntries, &sClMMTarget, pClM, sCRIterA, sCRIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::iter_t> (target::iter_t, target::iter_t)", 0, 1, nNumEntries, pClM, sIterA); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::citer_t> (target::citer_t, target::citer_t)", 0, 1, nNumEntries, pClM, sCIterA); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::riter_t> (target::riter_t, target::riter_t)", 0, 1, nNumEntries, pClM, sRIterA); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::criter_t> (target::criter_t, target::criter_t)", 0, 1, nNumEntries, pClM, sCRIterA); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::iter_t> (target::iter_t == target::iter_t)", 0, 1, nNumEntries, pClM, pClM, sIterA, sIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::citer_t> (target::citer_t == target::citer_t)", 0, 1, nNumEntries, pClM, pClM, sCIterA, sCIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::riter_t> (target::riter_t == target::riter_t)", 0, 1, nNumEntries, pClM, pClM, sRIterA, sRIterB); TestBTreeMapSTLifInsertViaIteratorSame ("target::insert<_t_obj::criter_t> (target::criter_t == target::criter_t)", 0, 1, nNumEntries, pClM, pClM, sCRIterA, sCRIterB); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::iter_t> (>iter_t, iter_t<) x2", (int) (nNumEntries / 4), 2, nNumEntries, pClM, sIterA); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::citer_t> (>citer_t, citer_t<) x2", (int) (nNumEntries / 4), 2, nNumEntries, pClM, sCIterA); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::riter_t> (>riter_t, riter_t<) x2", (int) (nNumEntries / 4), 2, nNumEntries, pClM, sRIterA); TestBTreeMapSTLifInsertViaIteratorPart ("target::insert<_t_obj::criter_t> (>criter_t, criter_t<) x2", (int) (nNumEntries / 4), 2, nNumEntries, pClM, sCRIterA); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::iter_t> (iter_t, iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sIterA, sCIterB, sItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::citer_t> (citer_t, citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sCIterA, sCIterB, sCItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::riter_t> (riter_t, riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sRIterA, sCIterB, sItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::criter_t> (criter_t, criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sCRIterA, sCIterB, sCItList); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<list::iter_t> (iter_t == iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sIterA, sIterB, sItList); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<list::citer_t> (citer_t == citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sCIterA, sCIterB, sCItList); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<list::riter_t> (riter_t == riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sRIterA, sRIterB, sItList); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<list::criter_t> (criter_t == criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sList, sCRIterA, sCRIterB, sCItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::iter_t> (>iter_t, iter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sList, sIterA, sCIterB, sItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::citer_t> (>citer_t, citer_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sList, sCIterA, sCIterB, sCItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::riter_t> (>riter_t, riter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sList, sRIterA, sCIterB, sItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<list::criter_t> (>criter_t, criter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sList, sCRIterA, sCIterB, sCItList); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::iter_t> (iter_t, iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sIterA, sCIterB, sItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::citer_t> (citer_t, citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sCIterA, sCIterB, sCItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::riter_t> (riter_t, riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sRIterA, sCIterB, sItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::criter_t> (criter_t, criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sCRIterA, sCIterB, sCItVec); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<vector::iter_t> (iter_t == iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sIterA, sIterB, sItVec); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<vector::citer_t> (citer_t == citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sCIterA, sCIterB, sCItVec); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<vector::riter_t> (riter_t == riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sRIterA, sRIterB, sItVec); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<vector::criter_t> (criter_t == criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sVector, sCRIterA, sCRIterB, sCItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::iter_t> (>iter_t, iter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sVector, sIterA, sCIterB, sItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::citer_t> (>citer_t, citer_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sVector, sCIterA, sCIterB, sCItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::riter_t> (>riter_t, riter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sVector, sRIterA, sCIterB, sItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<vector::criter_t> (>criter_t, criter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sVector, sCRIterA, sCIterB, sCItVec); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::iter_t> (iter_t, iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sIterA, sIterB, sItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::citer_t> (citer_t, citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sCIterA, sCIterB, sCItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::riter_t> (riter_t, riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sRIterA, sRIterB, sItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::criter_t> (criter_t, criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sCRIterA, sCRIterB, sCItMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<map::iter_t> (iter_t == iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sIterA, sIterB, sItMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<map::citer_t> (citer_t == citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sCIterA, sCIterB, sCItMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<map::riter_t> (riter_t == riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sRIterA, sRIterB, sItMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<map::criter_t> (criter_t == criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMap, sCRIterA, sCRIterB, sCItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::iter_t> (>iter_t, iter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMap, sIterA, sIterB, sItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::citer_t> (>citer_t, citer_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMap, sCIterA, sCIterB, sCItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::riter_t> (>riter_t, riter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMap, sRIterA, sRIterB, sItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<map::criter_t> (>criter_t, criter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMap, sCRIterA, sCRIterB, sCItMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::iter_t> (iter_t, iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sIterA, sIterB, sItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::citer_t> (citer_t, citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sCIterA, sCIterB, sCItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::riter_t> (riter_t, riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sRIterA, sRIterB, sItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::criter_t> (criter_t, criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sCRIterA, sCRIterB, sCItMMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<mmap::iter_t> (iter_t == iter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sIterA, sIterB, sItMMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<mmap::citer_t> (citer_t == citer_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sCIterA, sCIterB, sCItMMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<mmap::riter_t> (riter_t == riter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sRIterA, sRIterB, sItMMap); TestBTreeMapSTLifInsertViaIteratorSameExtern ("target::insert<mmap::criter_t> (criter_t == criter_t)", 0, 1, nNumEntries, &sClMMTarget, pClM, &sMMap, sCRIterA, sCRIterB, sCItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::iter_t> (>iter_t, iter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMMap, sIterA, sIterB, sItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::citer_t> (>citer_t, citer_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMMap, sCIterA, sCIterB, sCItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::riter_t> (>riter_t, riter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMMap, sRIterA, sRIterB, sItMMap); TestBTreeMapSTLifInsertViaIteratorPartExtern ("target::insert<mmap::criter_t> (>criter_t, criter_t<)", 0, 1, (int) (nNumEntries / 4), &sClMMTarget, pClM, &sMMap, sCRIterA, sCRIterB, sCItMMap); } template<class _t_container> void TestBTreeSTLmap (uint32_t nTestNum, uint32_t nNodeSize, uint32_t nPageSize, _t_container *pMapWrapper); #endif // !BTREEMAPTESTBENCH_H
lgpl-3.0
daniel-yu-papa/Maggie-OpenMax
framework/platform/hal/inc/Mag_hal.h
2575
/* * Copyright (c) 2015 Daniel Yu <[email protected]> * * This file is part of Maggie-OpenMax project. * * Maggie-OpenMax 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. * * Maggie-OpenMax 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 Maggie-OpenMax; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _MAG_HAL_H__ #define _MAG_HAL_H__ #include "Mag_pub_def.h" #include "Mag_pub_type.h" #include <pthread.h> #include <time.h> #define HAVE_POSIX_CLOCKS #ifdef __cplusplus extern "C" { #endif enum { MAG_SYSTEM_TIME_REALTIME = 0, /*// system-wide realtime clock*/ MAG_SYSTEM_TIME_MONOTONIC = 1, /*// monotonic time since unspecified starting point*/ MAG_SYSTEM_TIME_PROCESS = 2, /*// high-resolution per-process clock*/ MAG_SYSTEM_TIME_THREAD = 3, /*// high-resolution per-thread clock*/ MAG_SYSTEM_TIME_BOOTTIME = 4 /*// same as SYSTEM_TIME_MONOTONIC, but including CPU suspend time*/ }; struct MAG_MutexObj{ pthread_mutex_t mutex; }; typedef struct MAG_MutexObj *MagMutexHandle; #define MAG_ASSERT(expr) (expr) ? (void) 0 : Mag_AssertFailed(#expr, __FILE__, __LINE__) void Mag_AssertFailed(const char *expr, const char *file, unsigned int line); MagErr_t Mag_CreateMutex(MagMutexHandle *handler); MagErr_t Mag_DestroyMutex(MagMutexHandle *pHandler); MagErr_t Mag_TryAcquireMutex(MagMutexHandle handler); MagErr_t Mag_AcquireMutex(MagMutexHandle handler); MagErr_t Mag_ReleaseMutex(MagMutexHandle handler); /*for C++ static mutexes using*/ typedef pthread_mutex_t MagStaticMutex; #define MAG_STATIC_MUTEX_INITIALIZER(lock) \ lock = PTHREAD_MUTEX_INITIALIZER #define MAG_STATIC_MUTEX_Acquire(lock) \ pthread_mutex_lock(&lock) #define MAG_STATIC_MUTEX_Release(lock) \ pthread_mutex_unlock(&lock) ui64 Mag_GetSystemTime(i32 clock); void Mag_TimeTakenStatistic(boolean start, const char *func, const char *spec); #ifdef __cplusplus } #endif #endif
lgpl-3.0
Semantive/jts
src/test/test/jts/perf/operation/union/UnionPerfTester.java
3545
package test.jts.perf.operation.union; import java.util.Iterator; import java.util.List; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTWriter; import com.vividsolutions.jts.operation.union.CascadedPolygonUnion; import com.vividsolutions.jts.util.Stopwatch; public class UnionPerfTester { public static final int CASCADED = 1; public static final int ITERATED = 2; public static final int BUFFER0 = 3; public static final int ORDERED = 4; public static void run(String testName, int testType, List polys) { UnionPerfTester test = new UnionPerfTester(polys); test.run(testName, testType); } public static void runAll(List polys) { UnionPerfTester test = new UnionPerfTester(polys); test.runAll(); } static final int MAX_ITER = 1; static PrecisionModel pm = new PrecisionModel(); static GeometryFactory fact = new GeometryFactory(pm, 0); static WKTReader wktRdr = new WKTReader(fact); static WKTWriter wktWriter = new WKTWriter(); Stopwatch sw = new Stopwatch(); GeometryFactory factory = new GeometryFactory(); private List polys; public UnionPerfTester(List polys) { this.polys = polys; } public void runAll() { System.out.println("# items: " + polys.size()); run("Cascaded", CASCADED, polys); // run("Buffer-0", BUFFER0, polys); run("Iterated", ITERATED, polys); } public void run(String testName, int testType) { System.out.println(); System.out.println("======= Union Algorithm: " + testName + " ==========="); Stopwatch sw = new Stopwatch(); for (int i = 0; i < MAX_ITER; i++) { Geometry union = null; switch (testType) { case CASCADED: union = unionCascaded(polys); break; case ITERATED: union = unionAllSimple(polys); break; case BUFFER0: union = unionAllBuffer(polys); break; } // printFormatted(union); } System.out.println("Finished in " + sw.getTimeString()); } private void printFormatted(Geometry geom) { WKTWriter writer = new WKTWriter(); System.out.println(writer.writeFormatted(geom)); } public Geometry unionAllSimple(List geoms) { Geometry unionAll = null; int count = 0; for (Iterator i = geoms.iterator(); i.hasNext(); ) { Geometry geom = (Geometry) i.next(); if (unionAll == null) { unionAll = (Geometry) geom.clone(); } else { unionAll = unionAll.union(geom); } count++; if (count % 100 == 0) { System.out.print("."); // System.out.println("Adding geom #" + count); } } return unionAll; } public Geometry unionAllBuffer(List geoms) { Geometry gColl = factory.buildGeometry(geoms); Geometry unionAll = gColl.buffer(0.0); return unionAll; } public Geometry unionCascaded(List geoms) { return CascadedPolygonUnion.union(geoms); } /* public Geometry unionAllOrdered(List geoms) { // return OrderedUnion.union(geoms); } */ void printItemEnvelopes(List tree) { Envelope itemEnv = new Envelope(); for (Iterator i = tree.iterator(); i.hasNext(); ) { Object o = i.next(); if (o instanceof List) { printItemEnvelopes((List) o); } else if (o instanceof Geometry) { itemEnv.expandToInclude( ((Geometry) o).getEnvelopeInternal()); } } System.out.println(factory.toGeometry(itemEnv)); } }
lgpl-3.0
LeverylTeam/Leveryl
src/pocketmine/network/protocol/PlayerActionPacket.php
461
<?php // ---------- CREDITS ---------- // Mirrored from pocketmine\network\mcpe\protocol\PlayerActionPacket.php // Mirroring was done by @CortexPE of @LeverylTeam :D // // NOTE: We know that this was hacky... But It's here to still provide support for old plugins // ---------- CREDITS ---------- namespace pocketmine\network\protocol; use pocketmine\network\mcpe\protocol\PlayerActionPacket as Original; class PlayerActionPacket extends Original { }
lgpl-3.0
krathjen/studiolibrary
src/studiovendor/six.py
32901
# Copyright (c) 2010-2018 Benjamin Peterson # # 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. """ Utilities for writing code that runs on Python 2 and 3 WARNING: THIS VERSION OF SIX HAS BEEN MODIFIED. Changed line 658: def u(s): s = s.replace(r'\\', r'\\\\') if isinstance(s, unicode): return s else: return unicode(s, "unicode_escape") """ from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson <[email protected]>" __version__ = "1.12.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("getoutput", "commands", "subprocess"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("splitvalue", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), MovedAttribute("parse_http_list", "urllib2", "urllib.request"), MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s, encoding=None): return str(s) unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" else: def b(s): return s # Workaround for standalone backslash def u(s, encoding="unicode_escape"): if not isinstance(s, basestring): s = unicode(s, encoding) s = s.replace(r'\\', r'\\\\') if isinstance(s, unicode): return s else: return unicode(s, encoding) unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): try: raise tp, value, tb finally: tb = None """) if sys.version_info[:2] == (3, 2): exec_("""def raise_from(value, from_value): try: if from_value is None: raise value raise value from from_value finally: value = None """) elif sys.version_info[:2] > (3, 2): exec_("""def raise_from(value, from_value): try: raise value from from_value finally: value = None """) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) if hasattr(cls, '__qualname__'): orig_vars['__qualname__'] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s def ensure_text(s, encoding='utf-8', errors='strict'): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/dxguid/dxguid0000011E.c
447
// Created file "Lib\src\dxguid\dxguid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(GUID_RampForce, 0x13541c21, 0x8e33, 0x11d0, 0x9a, 0xd0, 0x00, 0xa0, 0xc9, 0xa0, 0x6e, 0x35);
lgpl-3.0
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/src/objects/mmdb2/Reference_frame.cpp
1865
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: ....... * * File Description: * ....... * * Remark: * This code was originally generated by application DATATOOL * using the following specifications: * 'mmdb2.asn'. */ // standard includes #include <ncbi_pch.hpp> // generated includes #include <objects/mmdb2/Reference_frame.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // destructor CReference_frame::~CReference_frame(void) { } END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE /* Original file checksum: lines: 57, chars: 1738, CRC32: 6dc78079 */
lgpl-3.0
konvergeio/cofoja-example
src/test/java/com/example/ExampleTest.java
212
package com.example; import org.testng.Assert; import org.testng.annotations.Test; public class ExampleTest { @Test public void foo() { Assert.assertTrue(new Example().foo()); } }
lgpl-3.0
jjm223/MyPet
modules/API/src/main/java/de/Keyle/MyPet/api/skill/experience/MonsterExperience.java
5371
/* * This file is part of MyPet * * Copyright © 2011-2016 Keyle * MyPet is licensed under the GNU Lesser General Public License. * * MyPet is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyPet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.Keyle.MyPet.api.skill.experience; import org.bukkit.entity.EntityType; import java.util.HashMap; import java.util.Map; public class MonsterExperience { public static final Map<String, MonsterExperience> mobExp = new HashMap<>(); private static MonsterExperience unknown = new MonsterExperience(0., "UNKNOWN"); static { mobExp.put("SKELETON", new MonsterExperience(5., "SKELETON")); mobExp.put("ZOMBIE", new MonsterExperience(5., "ZOMBIE")); mobExp.put("SPIDER", new MonsterExperience(5., "SPIDER")); mobExp.put("WOLF", new MonsterExperience(1., 3., "WOLF")); mobExp.put("CREEPER", new MonsterExperience(5., "CREEPER")); mobExp.put("GHAST", new MonsterExperience(5., "GHAST")); mobExp.put("PIG_ZOMBIE", new MonsterExperience(5., "PIG_ZOMBIE")); mobExp.put("ENDERMAN", new MonsterExperience(5., "ENDERMAN")); mobExp.put("ENDERMITE", new MonsterExperience(3., "ENDERMITE")); mobExp.put("CAVE_SPIDER", new MonsterExperience(5., "CAVE_SPIDER")); mobExp.put("MAGMA_CUBE", new MonsterExperience(1., 4., "MAGMA_CUBE")); mobExp.put("SLIME", new MonsterExperience(1., 4., "SLIME")); mobExp.put("SILVERFISH", new MonsterExperience(5., "SILVERFISH")); mobExp.put("BLAZE", new MonsterExperience(10., "BLAZE")); mobExp.put("GIANT", new MonsterExperience(25., "GIANT")); mobExp.put("GUARDIAN", new MonsterExperience(10., "GUARDIAN")); mobExp.put("COW", new MonsterExperience(1., 3., "COW")); mobExp.put("PIG", new MonsterExperience(1., 3., "PIG")); mobExp.put("CHICKEN", new MonsterExperience(1., 3., "CHICKEN")); mobExp.put("SQUID", new MonsterExperience(1., 3., "SQUID")); mobExp.put("SHEEP", new MonsterExperience(1., 3., "SHEEP")); mobExp.put("OCELOT", new MonsterExperience(1., 3., "OCELOT")); mobExp.put("MUSHROOM_COW", new MonsterExperience(1., 3., "MUSHROOM_COW")); mobExp.put("VILLAGER", new MonsterExperience(0., "VILLAGER")); mobExp.put("SHULKER", new MonsterExperience(5., "SHULKER")); mobExp.put("SNOWMAN", new MonsterExperience(0., "SNOWMAN")); mobExp.put("IRON_GOLEM", new MonsterExperience(0., "IRON_GOLEM")); mobExp.put("ENDER_DRAGON", new MonsterExperience(20000., "ENDER_DRAGON")); mobExp.put("WITCH", new MonsterExperience(10., "WITCH")); mobExp.put("BAT", new MonsterExperience(1., "BAT")); mobExp.put("ENDER_CRYSTAL", new MonsterExperience(10., "ENDER_CRYSTAL")); mobExp.put("WITHER", new MonsterExperience(100., "WITHER")); mobExp.put("RABBIT", new MonsterExperience(1., "RABBIT")); mobExp.put("VINDICATOR", new MonsterExperience(5., "VINDICATOR")); mobExp.put("EVOKER", new MonsterExperience(10., "EVOKER")); mobExp.put("VEX", new MonsterExperience(3., "VEX")); mobExp.put("LLAMA", new MonsterExperience(0., "LLAMA")); } private double min; private double max; private String entityType; public MonsterExperience(double min, double max, String entityType) { if (max >= min) { this.max = max; this.min = min; } else if (max <= min) { this.max = min; this.min = max; } this.entityType = entityType; } public MonsterExperience(double exp, String entityType) { this.max = exp; this.min = exp; this.entityType = entityType; } public double getRandomExp() { return max == min ? max : ((int) (doubleRandom(min, max) * 100)) / 100.; } public double getMin() { return min; } public double getMax() { return max; } public EntityType getEntityType() { return EntityType.valueOf(entityType); } public void setMin(double min) { this.min = min; if (min > max) { max = min; } } public void setMax(double max) { this.max = max; if (max < min) { min = max; } } public void setExp(double exp) { max = (min = exp); } private static double doubleRandom(double low, double high) { return Math.random() * (high - low) + low; } @Override public String toString() { return entityType + "{min=" + min + ", max=" + max + "}"; } public static MonsterExperience getMonsterExperience(EntityType type) { if (mobExp.containsKey(type.name())) { return mobExp.get(type.name()); } return unknown; } }
lgpl-3.0
socialwareinc/html-parser
parser/src/test/java/org/htmlparser/tests/utilTests/AllTests.java
2165
// HTMLParser Library - A java-based parser for HTML // http://htmlparser.org // Copyright (C) 2006 Somik Raha // // Revision Control Information // // $URL: file:///svn/p/htmlparser/code/tags/HTMLParserProject-2.1/parser/src/test/java/org/htmlparser/tests/utilTests/AllTests.java $ // $Author: derrickoswald $ // $Date: 2006-09-16 14:44:17 +0000 (Sat, 16 Sep 2006) $ // $Revision: 4 $ // // This library is free software; you can redistribute it and/or // modify it under the terms of the Common Public License; either // version 1.0 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Common Public License for more details. // // You should have received a copy of the Common Public License // along with this library; if not, the license is available from // the Open Source Initiative (OSI) website: // http://opensource.org/licenses/cpl1.0.php package org.htmlparser.tests.utilTests; import junit.framework.TestSuite; import org.htmlparser.tests.ParserTestCase; /** * Insert the type's description here. * Creation date: (6/17/2001 6:07:04 PM) */ public class AllTests extends ParserTestCase { static { System.setProperty ("org.htmlparser.tests.utilTests.AllTests", "AllTests"); } /** * AllTests constructor comment. * @param name java.lang.String */ public AllTests(String name) { super(name); } /** * Insert the method's description here. * Creation date: (6/17/2001 6:07:15 PM) * @return junit.framework.TestSuite */ public static TestSuite suite() { TestSuite suite = new TestSuite("Utility Tests"); suite.addTestSuite(BeanTest.class); suite.addTestSuite(HTMLParserUtilsTest.class); suite.addTestSuite(NodeListTest.class); suite.addTestSuite(NonEnglishTest.class); suite.addTestSuite(SortTest.class); return suite; } }
lgpl-3.0
dihedron/dihedron-commons
src/main/java/org/dihedron/patterns/visitor/nodes/ModifiableMapEntryNode.java
888
/** * Copyright (c) 2012-2014, Andrea Funto'. All rights reserved. See LICENSE for details. */ package org.dihedron.patterns.visitor.nodes; import java.util.Map; import org.dihedron.core.License; import org.dihedron.patterns.visitor.VisitorException; /** * @author Andrea Funto' */ @License public class ModifiableMapEntryNode extends UnmodifiableMapEntryNode { /** * Constructor. * * @param name * the pseudo-OGNL path of the node. * @param map * the map owning this node. * @param key * the key of this entry in the map. */ public ModifiableMapEntryNode(String name, Map<?, ?> map, Object key) { super(name, map, key); } /** * @see org.dihedron.patterns.visitor.nodes.AbstractNode#getValue() */ @SuppressWarnings("unchecked") public void setValue(Object value) throws VisitorException { ((Map<Object, Object>)map).put(key, value); } }
lgpl-3.0
svn2github/dynamicreports-jasper
dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/condition/EqualExpression.java
2144
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2015 Ricardo Mariaca * http://www.dynamicreports.org * * This file is part of DynamicReports. * * DynamicReports 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. * * DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.report.builder.condition; import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression; import net.sf.dynamicreports.report.constant.Constants; import net.sf.dynamicreports.report.definition.DRIValue; import net.sf.dynamicreports.report.definition.ReportParameters; import org.apache.commons.lang3.Validate; /** * @author Ricardo Mariaca ([email protected]) */ public class EqualExpression extends AbstractSimpleExpression<Boolean> { private static final long serialVersionUID = Constants.SERIAL_VERSION_UID; private DRIValue<?> value; private Object[] values; public <T> EqualExpression(DRIValue<T> value, T ...values) { Validate.notNull(value, "value must not be null"); Validate.noNullElements(values, "values must not contains null value"); this.value = value; this.values = values; } @Override public Boolean evaluate(ReportParameters reportParameters) { Object actualValue = reportParameters.getValue(value); for (Object value : values) { if (value.equals(actualValue)) { return true; } } return false; } @Override public Class<Boolean> getValueClass() { return Boolean.class; } }
lgpl-3.0
grappendorf/arduino-framework
EEPROMEx/EEPROMex.h
5044
/* EEPROMEx.h - Extended EEPROM library Copyright (c) 2012 Thijs Elenbaas. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EEPROMEX_h #define EEPROMEX_h #if ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif #include <inttypes.h> #include <avr/eeprom.h> // Boards with ATmega328, Duemilanove, Uno, UnoSMD, Lilypad - 1024 bytes (1 kilobyte) // Boards with ATmega1280 or 2560, Arduino Mega series � 4096 bytes (4 kilobytes) // Boards with ATmega168, Lilypad, old Nano, Diecimila � 512 bytes (1/2 kilobyte) #define EEPROMSizeATmega168 512 #define EEPROMSizeATmega328 1024 #define EEPROMSizeATmega1280 4096 #define EEPROMSizeATmega32u4 1024 #define EEPROMSizeAT90USB1286 4096 #define EEPROMSizeMK20DX128 2048 #define EEPROMSizeUno EEPROMSizeATmega328 #define EEPROMSizeUnoSMD EEPROMSizeATmega328 #define EEPROMSizeLilypad EEPROMSizeATmega328 #define EEPROMSizeDuemilanove EEPROMSizeATmega328 #define EEPROMSizeMega EEPROMSizeATmega1280 #define EEPROMSizeDiecimila EEPROMSizeATmega168 #define EEPROMSizeNano EEPROMSizeATmega168 #define EEPROMSizeTeensy2 EEPROMSizeATmega32u4 #define EEPROMSizeLeonardo EEPROMSizeATmega32u4 #define EEPROMSizeMicro EEPROMSizeATmega32u4 #define EEPROMSizeYun EEPROMSizeATmega32u4 #define EEPROMSizeTeensy2pp EEPROMSizeAT90USB1286 #define EEPROMSizeTeensy3 EEPROMSizeMK20DX128 class EEPROMClassEx { public: EEPROMClassEx(); bool isReady(); int writtenBytes(); void setMemPool(int base, int memSize); void setMaxAllowedWrites(int allowedWrites); int getAddress(int noOfBytes); uint8_t read(int); bool readBit(int, byte); uint8_t readByte(int); uint16_t readInt(int); // uint32_t readLong(int); float readFloat(int); double readDouble(int); bool write(int, uint8_t); bool writeBit(int , uint8_t, bool); bool writeByte(int, uint8_t); bool writeInt(int, uint16_t); // bool writeLong(int, uint32_t); bool writeFloat(int, float); bool writeDouble(int, double); bool update(int, uint8_t); bool updateBit(int , uint8_t, bool); bool updateByte(int, uint8_t); bool updateInt(int, uint16_t); bool updateLong(int, uint32_t); bool updateFloat(int, float); bool updateDouble(int, double); // Use template for other data formats template <class T> int readBlock(int address, const T value[], int items) { if (!isWriteOk(address+items*sizeof(T))) return 0; unsigned int i; for (i = 0; i < (unsigned int)items; i++) readBlock<T>(address+(i*sizeof(T)),value[i]); return i; } template <class T> int readBlock(int address, const T& value) { eeprom_read_block((void*)&value, (const void*)address, sizeof(value)); return sizeof(value); } template <class T> int writeBlock(int address, const T value[], int items) { if (!isWriteOk(address+items*sizeof(T))) return 0; unsigned int i; for (i = 0; i < (unsigned int)items; i++) writeBlock<T>(address+(i*sizeof(T)),value[i]); return i; } template <class T> int writeBlock(int address, const T& value) { if (!isWriteOk(address+sizeof(value))) return 0; eeprom_write_block((void*)&value, (void*)address, sizeof(value)); return sizeof(value); } template <class T> int updateBlock(int address, const T value[], int items) { int writeCount=0; if (!isWriteOk(address+items*sizeof(T))) return 0; unsigned int i; for (i = 0; i < (unsigned int)items; i++) writeCount+= updateBlock<T>(address+(i*sizeof(T)),value[i]); return writeCount; } template <class T> int updateBlock(int address, const T& value) { int writeCount=0; if (!isWriteOk(address+sizeof(value))) return 0; const byte* bytePointer = (const byte*)(const void*)&value; for (unsigned int i = 0; i < (unsigned int)sizeof(value); i++) { if (read(address)!=*bytePointer) { write(address, *bytePointer); writeCount++; } address++; bytePointer++; } return writeCount; } private: //Private variables static int _base; static int _memSize; static int _nextAvailableaddress; static int _writeCounts; int _allowedWrites; bool checkWrite(int base,int noOfBytes); bool isWriteOk(int address); bool isReadOk(int address); }; extern EEPROMClassEx EEPROM; #endif
lgpl-3.0
n2n/rocket
src/app/rocket/si/content/impl/split/SplitOutSiField.php
1814
<?php /* * Copyright (c) 2012-2016, Hofmänner New Media. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of the n2n module ROCKET. * * ROCKET 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. * * ROCKET is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/ * * The following people participated in this project: * * Andreas von Burg...........: Architect, Lead Developer, Concept * Bert Hofmänner.............: Idea, Frontend UI, Design, Marketing, Concept * Thomas Günther.............: Developer, Frontend UI, Rocket Capability for Hangar */ namespace rocket\si\content\impl\split; use n2n\util\ex\IllegalStateException; use rocket\si\content\impl\OutSiFieldAdapter; class SplitOutSiField extends OutSiFieldAdapter { private $subFields = []; private $splitContents = []; function __construct() { } /** * {@inheritDoc} * @see \rocket\si\content\SiField::getType() */ function getType(): string { return 'split-out'; } /** * {@inheritDoc} * @see \rocket\si\content\SiField::getData() */ function getData(): array { return [ 'splitContentsMap' => $this->splitContents ]; } /** * {@inheritDoc} * @see \rocket\si\content\impl\OutSiFieldAdapter::handleInput() */ function handleInput(array $data): array { throw new IllegalStateException(); } }
lgpl-3.0
iclcv/icl
ICLUtils/src/ICLUtils/CLImage2D.cpp
10270
/******************************************************************** ** Image Component Library (ICL) ** ** ** ** Copyright (C) 2006-2013 CITEC, University of Bielefeld ** ** Neuroinformatics Group ** ** Website: www.iclcv.org and ** ** http://opensource.cit-ec.de/projects/icl ** ** ** ** File : ICLUtils/src/ICLUtils/CLBuffer.cpp ** ** Module : ICLUtils ** ** Authors: Viktor Losing ** ** ** ** ** ** GNU LESSER GENERAL PUBLIC LICENSE ** ** This file may be used under the terms of the GNU Lesser General ** ** Public License version 3.0 as published by the ** ** ** ** Free Software Foundation and appearing in the file LICENSE.GPL ** ** included in the packaging of this file. Please review the ** ** following information to ensure the license requirements will ** ** be met: http://www.gnu.org/licenses/lgpl-3.0.txt ** ** ** ** The development of this software was supported by the ** ** Excellence Cluster EXC 277 Cognitive Interaction Technology. ** ** The Excellence Cluster EXC 277 is a grant of the Deutsche ** ** Forschungsgemeinschaft (DFG) in the context of the German ** ** Excellence Initiative. ** ** ** ********************************************************************/ #ifdef ICL_HAVE_OPENCL #define __CL_ENABLE_EXCEPTIONS #include <ICLUtils/CLImage2D.h> #include <ICLUtils/Macros.h> #include <ICLUtils/CLIncludes.h> #include <iostream> #include <sstream> #include <set> #include <map> using namespace std; namespace icl { namespace utils { struct CLImage2D::Impl { size_t width; size_t height; cl::Image2D image2D; cl::CommandQueue cmdQueue; std::map< uint32_t, set<uint32_t> > supported_channel_orders; static cl_mem_flags stringToMemFlags(const string &accessMode) { switch(accessMode.length()) { case 1: if(accessMode[0] == 'w') return CL_MEM_WRITE_ONLY; if(accessMode[0] == 'r') return CL_MEM_READ_ONLY; case 2: if( (accessMode[0] == 'r' && accessMode[1] == 'w') || (accessMode[0] == 'w' && accessMode[1] == 'r') ) { return CL_MEM_READ_WRITE; } default: throw CLBufferException("undefined access-mode '"+accessMode+"' (allowed are 'r', 'w' and 'rw')"); return CL_MEM_READ_WRITE; } } static cl_channel_order parseChannelOrder(const int num_channels) { cl_channel_order order = CL_R; switch(num_channels) { case(1): order = CL_R; break; case(2): order = CL_RA; break; case(3): order = CL_RGB; break; case(4): order = CL_RGBA; break; default: { std::stringstream sstream; sstream << num_channels; throw CLBufferException("unsupported number of channels: "+sstream.str()); } } return order; } bool checkSupportedImageFormat(cl_channel_order order, cl_channel_type type) { if (supported_channel_orders.count(order)) { return supported_channel_orders[order].count(type); } return false; } Impl() {} ~Impl() {} Impl(Impl& other):cmdQueue(other.cmdQueue) { width = other.width; height = other.height; image2D = other.image2D; supported_channel_orders = other.supported_channel_orders; } Impl(cl::Context &context, cl::CommandQueue &cmdQueue, const string &accessMode, const size_t width, const size_t height, int depth, int num_channel, const void *src = 0, const std::map<uint32_t, std::set<uint32_t> > &supported_formats = std::map< uint32_t,std::set<uint32_t> >()) :cmdQueue(cmdQueue), supported_channel_orders(supported_formats) { cl_mem_flags memFlags = stringToMemFlags(accessMode); if (src) { memFlags = memFlags | CL_MEM_COPY_HOST_PTR; } this->width = width; this->height = height; try { cl_channel_type channelType; switch(depth) { case 0: channelType = CL_UNSIGNED_INT8; break; case 1: channelType = CL_SIGNED_INT16; break; case 2: channelType = CL_SIGNED_INT32; break; case 3: channelType = CL_FLOAT; break; default: throw CLBufferException("unknown depth value"); } cl_channel_order order = parseChannelOrder(num_channel); if (!checkSupportedImageFormat(order,channelType)) { std::stringstream sstream; sstream << "channel: " << num_channel << ", depth-type: " << depth; throw CLBufferException("No such image type is supported: "+sstream.str()); } image2D = cl::Image2D(context, memFlags, cl::ImageFormat(order, channelType), width, height, 0, (void*) src); } catch (cl::Error& error) { throw CLBufferException(CLException::getMessage(error.err(), error.what())); } } void regionToCLTypes(const utils::Rect &region, cl::size_t<3> &clOrigin, cl::size_t<3> &clRegion) { clOrigin[0] = region.x; clOrigin[1] = region.y; clOrigin[2] = 0; if (region == Rect::null) { clRegion[0] = width; clRegion[1] = height; } else { clRegion[0] = region.width; clRegion[1] = region.height; } clRegion[2] = 1; } void read(void *dst, const utils::Rect &region=utils::Rect::null, bool block = true) { cl_bool blocking; if (block) blocking = CL_TRUE; else blocking = CL_FALSE; try { cl::size_t<3> clOrigin; cl::size_t<3> clRegion; regionToCLTypes(region, clOrigin, clRegion); cmdQueue.enqueueReadImage(image2D, blocking, clOrigin, clRegion, 0, 0, dst); } catch (cl::Error& error) { throw CLBufferException(CLException::getMessage(error.err(), error.what())); } } void write(void *src, const utils::Rect &region=utils::Rect::null, bool block = true) { cl_bool blocking; if (block) blocking = CL_TRUE; else blocking = CL_FALSE; try { cl::size_t<3> clOrigin; cl::size_t<3> clRegion; regionToCLTypes(region, clOrigin, clRegion); cmdQueue.enqueueWriteImage(image2D, blocking, clOrigin, clRegion, 0, 0, src); } catch (cl::Error& error) { throw CLBufferException(CLException::getMessage(error.err(), error.what())); } } static const icl32s iclDepthToByteDepth(int icl_depth) { switch (icl_depth) { case(0): return 1; case(1): return 2; case(2): return 4; case(3): return 4; case(4): return 8; default: return 1; // maybe better to throw an exception here? } } }; CLImage2D::CLImage2D(cl::Context &context, cl::CommandQueue &cmdQueue, const string &accessMode, const size_t width, const size_t height, int depth, int num_channel, const void *src, const std::map<uint32_t, std::set<uint32_t> > &supported_formats) : CLMemory(CLMemory::Image2D) { impl = new Impl(context, cmdQueue, accessMode, width, height, depth, num_channel, src, supported_formats); setDimensions(width,height,num_channel); m_byte_depth = Impl::iclDepthToByteDepth(depth); } CLImage2D::CLImage2D() : CLMemory(CLMemory::Image2D) { impl = new Impl(); } CLImage2D::CLImage2D(const CLImage2D& other) : CLMemory(other) { impl = new Impl(*(other.impl)); } CLImage2D& CLImage2D::operator=(CLImage2D const& other) { CLMemory::operator=(other); impl->cmdQueue = other.impl->cmdQueue; impl->image2D = other.impl->image2D; impl->width = other.impl->width; impl->height = other.impl->height; impl->supported_channel_orders = other.impl->supported_channel_orders; return *this; } CLImage2D::~CLImage2D() { delete impl; } void CLImage2D::read(void *dst, const utils::Rect &region, bool block) { impl->read(dst, region, block); } void CLImage2D::write(const void *src, const utils::Rect &region, bool block) { impl->write((void *)src, region, block); } cl::Image2D CLImage2D::getImage2D() { return impl->image2D; } const cl::Image2D CLImage2D::getImage2D() const { return impl->image2D; } } } #endif
lgpl-3.0
TheAnswer/FirstTest
bin/scripts/creatures/objects/dathomir/creatures/injuredVerne.lua
4632
--Copyright (C) 2008 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. injuredVerne = Creature:new { objectName = "injuredVerne", -- Lua Object Name creatureType = "ANIMAL", gender = "", speciesName = "injured_verne", stfName = "mob/creature_names", objectCRC = 1915375945, socialGroup = "Verne", level = 6, combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG, healthMax = 220, healthMin = 180, strength = 0, constitution = 0, actionMax = 220, actionMin = 180, quickness = 0, stamina = 0, mindMax = 220, mindMin = 180, focus = 0, willpower = 0, height = 1, -- Size of creature armor = 0, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy kinetic = 0, energy = 0, electricity = 0, stun = -1, blast = 0, heat = 0, cold = 0, acid = 0, lightsaber = 0, accuracy = 0, healer = 0, pack = 0, herd = 1, stalker = 0, killer = 0, ferocity = 0, aggressive = 0, invincible = 0, meleeDefense = 1, rangedDefense = 1, attackCreatureOnSight = "", -- Enter socialGroups weapon = "object/weapon/creature/shared_creature_default_weapon.iff", -- File path to weapon -> object\xxx\xxx\xx weaponName = "Creature Defualt", -- Name ex. 'a Vibrolance' weaponTemp = "creature_default_weapon", -- Weapon Template ex. 'lance_vibrolance' weaponClass = "UnarmedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon' weaponEquipped = 0, weaponMinDamage = 50, weaponMaxDamage = 55, weaponAttackSpeed = 2, weaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx alternateWeaponName = "", -- Name ex. 'a Vibrolance' alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance' alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon' alternateWeaponEquipped = 0, alternateWeaponMinDamage = 0, alternateWeaponMaxDamage = 0, alternateWeaponAttackSpeed = 0, alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc alternateWeaponArmorPiercing = "", -- LIGHT, NONE, MEDIUM, HEAVY internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's lootGroup = "0", -- Group it belongs to for loot tame = 0, -- Likely hood to be tamed datapadItemCRC = 0, mountCRC = 0, mountSpeed = 0, mountAcceleration = 0, milk = 0, boneType = "bone_mammal_dathomir", boneMax = 22, hideType = "hide_leathery_dathomir", hideMax = 25, meatType = "meat_wild_dathomir", meatMax = 30, skills = { "verneAttack1" }, respawnTimer = 60, behaviorScript = "", -- Link to the behavior script for this object } Creatures:addCreature(injuredVerne, 1915375945) -- Add to Global Table
lgpl-3.0
borzole/borzole
bin/zmkfs.ext3.sh
458
#!/bin/bash # symulacja formatowania partycji lista_menu(){ for p in $( fdisk -l 2>/dev/null | grep '^/dev/' | cut -d' ' -f1 ) ; do echo "TRUE $p " done } menu(){ zenity --title "Formatowanie Dysków" --text "bedzie formacik panie?" \ --width=400 --height=300 \ --list --checklist \ --column="zaznacz" --column "partycja" \ $(lista_menu) \ --separator " " --multiple \ --print-column=2 } for d in $(menu) ; do echo "mkfs.ext4 $d" done
lgpl-3.0