code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
//============================================================================================================= /** * @file networktreeitem.cpp * @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date January, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief NetworkTreeItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "networktreeitem.h" #include "../../workers/rtSourceLoc/rtsourcelocdataworker.h" #include "../common/metatreeitem.h" #include "../../3dhelpers/renderable3Dentity.h" #include "../../materials/networkmaterial.h" #include "../../3dhelpers/custommesh.h" #include "../../3dhelpers/geometrymultiplier.h" #include "../../materials/geometrymultipliermaterial.h" #include <connectivity/network/networknode.h> #include <connectivity/network/networkedge.h> #include <fiff/fiff_types.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_forwardsolution.h> //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <Qt3DExtras/QSphereGeometry> #include <Qt3DCore/QTransform> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/Core> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace MNELIB; using namespace DISP3DLIB; using namespace CONNECTIVITYLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= NetworkTreeItem::NetworkTreeItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : AbstractMeshTreeItem(p3DEntityParent, iType, text) , m_bNodesPlotted(false) { initItem(); } //************************************************************************************************************* void NetworkTreeItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip("Network item"); //Add meta information as item children QList<QStandardItem*> list; QVariant data; QVector3D vecEdgeTrehshold(0,5,10); if(!m_pItemNetworkThreshold) { m_pItemNetworkThreshold = new MetaTreeItem(MetaTreeItemTypes::NetworkThreshold, QString("%1,%2,%3").arg(vecEdgeTrehshold.x()).arg(vecEdgeTrehshold.y()).arg(vecEdgeTrehshold.z())); } list << m_pItemNetworkThreshold; list << new QStandardItem(m_pItemNetworkThreshold->toolTip()); this->appendRow(list); data.setValue(vecEdgeTrehshold); m_pItemNetworkThreshold->setData(data, MetaTreeItemRoles::NetworkThreshold); connect(m_pItemNetworkThreshold.data(), &MetaTreeItem::dataChanged, this, &NetworkTreeItem::onNetworkThresholdChanged); list.clear(); MetaTreeItem* pItemNetworkMatrix = new MetaTreeItem(MetaTreeItemTypes::NetworkMatrix, "Show network matrix"); list << pItemNetworkMatrix; list << new QStandardItem(pItemNetworkMatrix->toolTip()); this->appendRow(list); //Set shaders this->removeComponent(m_pMaterial); this->removeComponent(m_pTessMaterial); this->removeComponent(m_pNormalMaterial); NetworkMaterial* pNetworkMaterial = new NetworkMaterial(); this->addComponent(pNetworkMaterial); } //************************************************************************************************************* void NetworkTreeItem::addData(const Network& tNetworkData) { //Add data which is held by this NetworkTreeItem QVariant data; data.setValue(tNetworkData); this->setData(data, Data3DTreeModelItemRoles::NetworkData); MatrixXd matDist = tNetworkData.getConnectivityMatrix(); data.setValue(matDist); this->setData(data, Data3DTreeModelItemRoles::NetworkDataMatrix); //Plot network if(m_pItemNetworkThreshold) { plotNetwork(tNetworkData, m_pItemNetworkThreshold->data(MetaTreeItemRoles::NetworkThreshold).value<QVector3D>()); } } //************************************************************************************************************* void NetworkTreeItem::onNetworkThresholdChanged(const QVariant& vecThresholds) { if(vecThresholds.canConvert<QVector3D>()) { Network tNetwork = this->data(Data3DTreeModelItemRoles::NetworkData).value<Network>(); plotNetwork(tNetwork, vecThresholds.value<QVector3D>()); } } //************************************************************************************************************* void NetworkTreeItem::plotNetwork(const Network& tNetworkData, const QVector3D& vecThreshold) { //Create network vertices and normals QList<NetworkNode::SPtr> lNetworkNodes = tNetworkData.getNodes(); MatrixX3f tMatVert(lNetworkNodes.size(), 3); for(int i = 0; i < lNetworkNodes.size(); ++i) { tMatVert(i,0) = lNetworkNodes.at(i)->getVert()(0); tMatVert(i,1) = lNetworkNodes.at(i)->getVert()(1); tMatVert(i,2) = lNetworkNodes.at(i)->getVert()(2); } MatrixX3f tMatNorm(lNetworkNodes.size(), 3); tMatNorm.setZero(); //Draw network nodes //TODO: Dirty hack using m_bNodesPlotted flag to get rid of memory leakage problem when putting parent to the nodes entities. Internal Qt3D problem? if(!m_bNodesPlotted) { Renderable3DEntity* pSourceSphereEntity = new Renderable3DEntity(this); //create geometry QSharedPointer<Qt3DExtras::QSphereGeometry> pSourceSphereGeometry = QSharedPointer<Qt3DExtras::QSphereGeometry>::create(); pSourceSphereGeometry->setRadius(0.001f); //create instanced renderer GeometryMultiplier *pSphereMesh = new GeometryMultiplier(pSourceSphereGeometry); //Create transform matrix for each sphere instance QVector<QMatrix4x4> vTransforms; vTransforms.reserve(tMatVert.rows()); QVector3D tempPos; for(int i = 0; i < tMatVert.rows(); ++i) { QMatrix4x4 tempTransform; tempPos.setX(tMatVert(i, 0)); tempPos.setY(tMatVert(i, 1)); tempPos.setZ(tMatVert(i, 2)); //Set position tempTransform.translate(tempPos); vTransforms.push_back(tempTransform); } //Set instance Transform pSphereMesh->setTransforms(vTransforms); pSourceSphereEntity->addComponent(pSphereMesh); //Add material GeometryMultiplierMaterial* pMaterial = new GeometryMultiplierMaterial(true); pMaterial->setAmbient(Qt::blue); pMaterial->setAlpha(1.0f); pSourceSphereEntity->addComponent(pMaterial); m_bNodesPlotted = true; } //Generate connection indices for Qt3D buffer MatrixXi tMatLines; int count = 0; int start, end; for(int i = 0; i < lNetworkNodes.size(); ++i) { //Plot in edges for(int j = 0; j < lNetworkNodes.at(i)->getEdgesIn().size(); ++j) { start = lNetworkNodes.at(i)->getEdgesIn().at(j)->getStartNode()->getId(); end = lNetworkNodes.at(i)->getEdgesIn().at(j)->getEndNode()->getId(); if(std::fabs(lNetworkNodes.at(i)->getEdgesIn().at(j)->getWeight()) >= vecThreshold.x() && start != end) { tMatLines.conservativeResize(count+1,2); tMatLines(count,0) = start; tMatLines(count,1) = end; ++count; } } //Plot out edges for(int j = 0; j < lNetworkNodes.at(i)->getEdgesOut().size(); ++j) { start = lNetworkNodes.at(i)->getEdgesOut().at(j)->getStartNode()->getId(); end = lNetworkNodes.at(i)->getEdgesOut().at(j)->getEndNode()->getId(); if(std::fabs(lNetworkNodes.at(i)->getEdgesOut().at(j)->getWeight()) >= vecThreshold.x() && start != end) { tMatLines.conservativeResize(count+1,2); tMatLines(count,0) = start; tMatLines(count,1) = end; ++count; } } } //Generate colors for Qt3D buffer MatrixX3f matLineColor(tMatVert.rows(),3); for(int i = 0; i < matLineColor.rows(); ++i) { matLineColor(i,0) = 0.0f; matLineColor(i,1) = 0.0f; matLineColor(i,2) = 1.0f; } m_pCustomMesh->setMeshData(tMatVert, tMatNorm, tMatLines, matLineColor, Qt3DRender::QGeometryRenderer::Lines); }
ViktorKL/mne-cpp
libraries/disp3D/engine/model/items/network/networktreeitem.cpp
C++
bsd-3-clause
11,515
var Tag = require('./tag'); var ScriptTag = require('./script-tag'); var Utils = require('./../utils'); /** * Script tag class that is loaded in a synchronous way. * * This is the class that will generate script tags that will be appended to the * page using the document.write method. * * @param string The tag data. * @param TagLoader The loader instance that has instantiated the tag. * * @return void */ class SynchronousScriptTag extends ScriptTag { constructor(data = {}, loader_instance) { super(data, loader_instance); this.data = Utils.mergeObject(this.data, { attributes: { async: false, defer: false } }, false); this.data = Utils.mergeObject(this.data, data); if (this.data !== data) { this.data = Utils.getSanitizedObject(this.data, Tag.properties); } } /** * Returns the script node that will be appended to the DOM. * * @return HTMLElement */ getDomNode() { var s, data; if (!this.data.src) { return false; } if (Utils.isDomReady() === true) { data = Utils.mergeObject({}, this.data, false); data.type = 'script'; this.loader_instance.addToQueue([data]); return false; } s = this.getScriptNode(false); s.text = this.getDomNodeSource(s); return s; } /** * Returns the JS code that will insert the script source using * document.write. * * @return string */ getDomNodeSource(s) { var text; text = 'document.write(\'<script src="' + this.data.src + '"'; text += ' id="' + this.data.id + '"'; if (s.addEventListener) { text += ' onload="' + this.getOnTagLoadPageCode() + '"'; } else { text += ' onreadystatechange="' + this.getIeOnLoadFunction() + '"'; } text += '></scr' + 'ipt>\');'; return text; } /** * Returns function that will be called only on older IE versions when the * tag has been loaded by the browser. * * @return string */ getIeOnLoadFunction() { var text = ''; text += 'if (this.addEventListener || '; text += 'this.amc_load || '; text += '(this.readyState && '; text += 'this.readyState !== \\\'complete\\\')'; text += ') { return; } '; text += 'this.amc_load = true; '; text += this.getOnTagLoadPageCode(); return text; } } module.exports = SynchronousScriptTag;
dompuiu/personal-tag-manager-enhanced-js-library
src/engine/tags/synchronous-script-tag.js
JavaScript
bsd-3-clause
2,396
/* * VertexMenuListener.java * * Created on March 21, 2007, 1:50 PM; Updated May 29, 2007 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.jungstudy; import edu.uci.ics.jung.visualization.VisualizationViewer; /** * Used to indicate that this class wishes to be told of a selected vertex * along with its visualization component context. Note that the VisualizationViewer * has full access to the graph and layout. * @author Dr. Greg M. Bernstein */ public interface VertexMenuListener<V> { void setVertexAndView(V v, VisualizationViewer visView); }
buptwufengjiao/weibo4j
src/com/jungstudy/VertexMenuListener.java
Java
bsd-3-clause
660
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dijit.Editor"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dijit.Editor"] = true; dojo.provide("dijit.Editor"); dojo.require("dijit._editor.RichText"); dojo.require("dijit.Toolbar"); dojo.require("dijit.ToolbarSeparator"); dojo.require("dijit._editor._Plugin"); dojo.require("dijit._editor.plugins.EnterKeyHandling"); dojo.require("dijit._editor.range"); dojo.require("dijit._Container"); dojo.require("dojo.i18n"); dojo.require("dijit.layout._LayoutWidget"); dojo.require("dijit._editor.range"); dojo.requireLocalization("dijit._editor", "commands", null, "ROOT,ar,ca,cs,da,de,el,es,fi,fr,he,hu,it,ja,kk,ko,nb,nl,pl,pt,pt-pt,ro,ru,sk,sl,sv,th,tr,zh,zh-tw"); dojo.declare( "dijit.Editor", dijit._editor.RichText, { // summary: // A rich text Editing widget // // description: // This widget provides basic WYSIWYG editing features, based on the browser's // underlying rich text editing capability, accompanied by a toolbar (`dijit.Toolbar`). // A plugin model is available to extend the editor's capabilities as well as the // the options available in the toolbar. Content generation may vary across // browsers, and clipboard operations may have different results, to name // a few limitations. Note: this widget should not be used with the HTML // &lt;TEXTAREA&gt; tag -- see dijit._editor.RichText for details. // plugins: Object[] // A list of plugin names (as strings) or instances (as objects) // for this widget. // // When declared in markup, it might look like: // | plugins="['bold',{name:'dijit._editor.plugins.FontChoice', command:'fontName', generic:true}]" plugins: null, // extraPlugins: Object[] // A list of extra plugin names which will be appended to plugins array extraPlugins: null, constructor: function(){ // summary: // Runs on widget initialization to setup arrays etc. // tags: // private if(!dojo.isArray(this.plugins)){ this.plugins=["undo","redo","|","cut","copy","paste","|","bold","italic","underline","strikethrough","|", "insertOrderedList","insertUnorderedList","indent","outdent","|","justifyLeft","justifyRight","justifyCenter","justifyFull", "dijit._editor.plugins.EnterKeyHandling" /*, "createLink"*/]; } this._plugins=[]; this._editInterval = this.editActionInterval * 1000; //IE will always lose focus when other element gets focus, while for FF and safari, //when no iframe is used, focus will be lost whenever another element gets focus. //For IE, we can connect to onBeforeDeactivate, which will be called right before //the focus is lost, so we can obtain the selected range. For other browsers, //no equivelent of onBeforeDeactivate, so we need to do two things to make sure //selection is properly saved before focus is lost: 1) when user clicks another //element in the page, in which case we listen to mousedown on the entire page and //see whether user clicks out of a focus editor, if so, save selection (focus will //only lost after onmousedown event is fired, so we can obtain correct caret pos.) //2) when user tabs away from the editor, which is handled in onKeyDown below. if(dojo.isIE){ this.events.push("onBeforeDeactivate"); this.events.push("onBeforeActivate"); } }, postMixInProperties: function() { // summary: // Extension to make sure a deferred is in place before certain functions // execute, like making sure all the plugins are properly inserted. // Set up a deferred so that the value isn't applied to the editor // until all the plugins load, needed to avoid timing condition // reported in #10537. this.setValueDeferred = new dojo.Deferred(); this.inherited(arguments); }, postCreate: function(){ //for custom undo/redo, if enabled. this._steps=this._steps.slice(0); this._undoedSteps=this._undoedSteps.slice(0); if(dojo.isArray(this.extraPlugins)){ this.plugins=this.plugins.concat(this.extraPlugins); } this.inherited(arguments); this.commands = dojo.i18n.getLocalization("dijit._editor", "commands", this.lang); if(!this.toolbar){ // if we haven't been assigned a toolbar, create one this.toolbar = new dijit.Toolbar({ dir: this.dir, lang: this.lang }); this.header.appendChild(this.toolbar.domNode); } dojo.forEach(this.plugins, this.addPlugin, this); // Okay, denote the value can now be set. this.setValueDeferred.callback(true); dojo.addClass(this.iframe.parentNode, "dijitEditorIFrameContainer"); dojo.addClass(this.iframe, "dijitEditorIFrame"); dojo.attr(this.iframe, "allowTransparency", true); if(dojo.isWebKit){ // Disable selecting the entire editor by inadvertant double-clicks. // on buttons, title bar, etc. Otherwise clicking too fast on // a button such as undo/redo selects the entire editor. dojo.style(this.domNode, "KhtmlUserSelect", "none"); } this.toolbar.startup(); this.onNormalizedDisplayChanged(); //update toolbar button status }, destroy: function(){ dojo.forEach(this._plugins, function(p){ if(p && p.destroy){ p.destroy(); } }); this._plugins=[]; this.toolbar.destroyRecursive(); delete this.toolbar; this.inherited(arguments); }, addPlugin: function(/*String||Object*/plugin, /*Integer?*/index){ // summary: // takes a plugin name as a string or a plugin instance and // adds it to the toolbar and associates it with this editor // instance. The resulting plugin is added to the Editor's // plugins array. If index is passed, it's placed in the plugins // array at that index. No big magic, but a nice helper for // passing in plugin names via markup. // // plugin: String, args object or plugin instance // // args: // This object will be passed to the plugin constructor // // index: Integer // Used when creating an instance from // something already in this.plugins. Ensures that the new // instance is assigned to this.plugins at that index. var args=dojo.isString(plugin)?{name:plugin}:plugin; if(!args.setEditor){ var o={"args":args,"plugin":null,"editor":this}; dojo.publish(dijit._scopeName + ".Editor.getPlugin",[o]); if(!o.plugin){ var pc = dojo.getObject(args.name); if(pc){ o.plugin=new pc(args); } } if(!o.plugin){ console.warn('Cannot find plugin',plugin); return; } plugin=o.plugin; } if(arguments.length > 1){ this._plugins[index] = plugin; }else{ this._plugins.push(plugin); } plugin.setEditor(this); if(dojo.isFunction(plugin.setToolbar)){ plugin.setToolbar(this.toolbar); } }, //the following 3 functions are required to make the editor play nice under a layout widget, see #4070 startup: function(){ // summary: // Exists to make Editor work as a child of a layout widget. // Developers don't need to call this method. // tags: // protected //console.log('startup',arguments); }, resize: function(size){ // summary: // Resize the editor to the specified size, see `dijit.layout._LayoutWidget.resize` if(size){ // we've been given a height/width for the entire editor (toolbar + contents), calls layout() // to split the allocated size between the toolbar and the contents dijit.layout._LayoutWidget.prototype.resize.apply(this, arguments); } /* else{ // do nothing, the editor is already laid out correctly. The user has probably specified // the height parameter, which was used to set a size on the iframe } */ }, layout: function(){ // summary: // Called from `dijit.layout._LayoutWidget.resize`. This shouldn't be called directly // tags: // protected // Converts the iframe (or rather the <div> surrounding it) to take all the available space // except what's needed for the header (toolbars) and footer (breadcrumbs, etc). // A class was added to the iframe container and some themes style it, so we have to // calc off the added margins and padding too. See tracker: #10662 var areaHeight = (this._contentBox.h - (this.getHeaderHeight() + this.getFooterHeight() + dojo._getPadBorderExtents(this.iframe.parentNode).h + dojo._getMarginExtents(this.iframe.parentNode).h)); this.editingArea.style.height = areaHeight + "px"; if(this.iframe){ this.iframe.style.height="100%"; } this._layoutMode = true; }, _onIEMouseDown: function(/*Event*/ e){ // summary: // IE only to prevent 2 clicks to focus // tags: // private var outsideClientArea; // IE 8's componentFromPoint is broken, which is a shame since it // was smaller code, but oh well. We have to do this brute force // to detect if the click was scroller or not. var b = this.document.body; var clientWidth = b.clientWidth; var clientHeight = b.clientHeight; var clientLeft = b.clientLeft; var offsetWidth = b.offsetWidth; var offsetHeight = b.offsetHeight; var offsetLeft = b.offsetLeft; //Check for vertical scroller click. bodyDir = b.dir?b.dir.toLowerCase():"" if(bodyDir != "rtl"){ if(clientWidth < offsetWidth && e.x > clientWidth && e.x < offsetWidth){ // Check the click was between width and offset width, if so, scroller outsideClientArea = true; } }else{ // RTL mode, we have to go by the left offsets. if(e.x < clientLeft && e.x > offsetLeft){ // Check the click was between width and offset width, if so, scroller outsideClientArea = true; } } if(!outsideClientArea){ // Okay, might be horiz scroller, check that. if(clientHeight < offsetHeight && e.y > clientHeight && e.y < offsetHeight){ // Horizontal scroller. outsideClientArea = true; } } if(!outsideClientArea){ delete this._cursorToStart; // Remove the force to cursor to start position. delete this._savedSelection; // new mouse position overrides old selection if(e.target.tagName == "BODY"){ setTimeout(dojo.hitch(this, "placeCursorAtEnd"), 0); } this.inherited(arguments); } }, onBeforeActivate: function(e){ this._restoreSelection(); }, onBeforeDeactivate: function(e){ // summary: // Called on IE right before focus is lost. Saves the selected range. // tags: // private if(this.customUndo){ this.endEditing(true); } //in IE, the selection will be lost when other elements get focus, //let's save focus before the editor is deactivated if(e.target.tagName != "BODY"){ this._saveSelection(); } //console.log('onBeforeDeactivate',this); }, /* beginning of custom undo/redo support */ // customUndo: Boolean // Whether we shall use custom undo/redo support instead of the native // browser support. By default, we only enable customUndo for IE, as it // has broken native undo/redo support. Note: the implementation does // support other browsers which have W3C DOM2 Range API implemented. // It was also enabled on WebKit, to fix undo/redo enablement. (#9613) customUndo: dojo.isIE || dojo.isWebKit, // editActionInterval: Integer // When using customUndo, not every keystroke will be saved as a step. // Instead typing (including delete) will be grouped together: after // a user stops typing for editActionInterval seconds, a step will be // saved; if a user resume typing within editActionInterval seconds, // the timeout will be restarted. By default, editActionInterval is 3 // seconds. editActionInterval: 3, beginEditing: function(cmd){ // summary: // Called to note that the user has started typing alphanumeric characters, if it's not already noted. // Deals with saving undo; see editActionInterval parameter. // tags: // private if(!this._inEditing){ this._inEditing=true; this._beginEditing(cmd); } if(this.editActionInterval>0){ if(this._editTimer){ clearTimeout(this._editTimer); } this._editTimer = setTimeout(dojo.hitch(this, this.endEditing), this._editInterval); } }, _steps:[], _undoedSteps:[], execCommand: function(cmd){ // summary: // Main handler for executing any commands to the editor, like paste, bold, etc. // Called by plugins, but not meant to be called by end users. // tags: // protected if(this.customUndo && (cmd == 'undo' || cmd == 'redo')){ return this[cmd](); }else{ if(this.customUndo){ this.endEditing(); this._beginEditing(); } var r; try{ r = this.inherited('execCommand', arguments); if(dojo.isWebKit && cmd == 'paste' && !r){ //see #4598: safari does not support invoking paste from js throw { code: 1011 }; // throw an object like Mozilla's error } }catch(e){ //TODO: when else might we get an exception? Do we need the Mozilla test below? if(e.code == 1011 /* Mozilla: service denied */ && /copy|cut|paste/.test(cmd)){ // Warn user of platform limitation. Cannot programmatically access clipboard. See ticket #4136 var sub = dojo.string.substitute, accel = {cut:'X', copy:'C', paste:'V'}; alert(sub(this.commands.systemShortcut, [this.commands[cmd], sub(this.commands[dojo.isMac ? 'appleKey' : 'ctrlKey'], [accel[cmd]])])); } r = false; } if(this.customUndo){ this._endEditing(); } return r; } }, queryCommandEnabled: function(cmd){ // summary: // Returns true if specified editor command is enabled. // Used by the plugins to know when to highlight/not highlight buttons. // tags: // protected if(this.customUndo && (cmd == 'undo' || cmd == 'redo')){ return cmd == 'undo' ? (this._steps.length > 1) : (this._undoedSteps.length > 0); }else{ return this.inherited('queryCommandEnabled',arguments); } }, _moveToBookmark: function(b){ // summary: // Selects the text specified in bookmark b // tags: // private var bookmark = b.mark; var mark = b.mark; var col = b.isCollapsed; var r, sNode, eNode, sel; if(mark){ if(dojo.isIE){ if(dojo.isArray(mark)){ //IE CONTROL, have to use the native bookmark. bookmark = []; dojo.forEach(mark,function(n){ bookmark.push(dijit.range.getNode(n,this.editNode)); },this); dojo.withGlobal(this.window,'moveToBookmark',dijit,[{mark: bookmark, isCollapsed: col}]); }else{ if(mark.startContainer && mark.endContainer){ // Use the pseudo WC3 range API. This works better for positions // than the IE native bookmark code. sel = dijit.range.getSelection(this.window); if(sel && sel.removeAllRanges){ sel.removeAllRanges(); r = dijit.range.create(this.window); sNode = dijit.range.getNode(mark.startContainer,this.editNode); eNode = dijit.range.getNode(mark.endContainer,this.editNode); if(sNode && eNode){ // Okay, we believe we found the position, so add it into the selection // There are cases where it may not be found, particularly in undo/redo, when // IE changes the underlying DOM on us (wraps text in a <p> tag or similar. // So, in those cases, don't bother restoring selection. r.setStart(sNode,mark.startOffset); r.setEnd(eNode,mark.endOffset); sel.addRange(r); } } } } }else{//w3c range sel = dijit.range.getSelection(this.window); if(sel && sel.removeAllRanges){ sel.removeAllRanges(); r = dijit.range.create(this.window); sNode = dijit.range.getNode(mark.startContainer,this.editNode); eNode = dijit.range.getNode(mark.endContainer,this.editNode); if(sNode && eNode){ // Okay, we believe we found the position, so add it into the selection // There are cases where it may not be found, particularly in undo/redo, when // formatting as been done and so on, so don't restore selection then. r.setStart(sNode,mark.startOffset); r.setEnd(eNode,mark.endOffset); sel.addRange(r); } } } } }, _changeToStep: function(from, to){ // summary: // Reverts editor to "to" setting, from the undo stack. // tags: // private this.setValue(to.text); var b=to.bookmark; if(!b){ return; } this._moveToBookmark(b); }, undo: function(){ // summary: // Handler for editor undo (ex: ctrl-z) operation // tags: // private //console.log('undo'); var ret = false; if(!this._undoRedoActive){ this._undoRedoActive = true; this.endEditing(true); var s=this._steps.pop(); if(s && this._steps.length>0){ this.focus(); this._changeToStep(s,this._steps[this._steps.length-1]); this._undoedSteps.push(s); this.onDisplayChanged(); delete this._undoRedoActive; ret = true; } delete this._undoRedoActive; } return ret; }, redo: function(){ // summary: // Handler for editor redo (ex: ctrl-y) operation // tags: // private //console.log('redo'); var ret = false; if(!this._undoRedoActive){ this._undoRedoActive = true; this.endEditing(true); var s=this._undoedSteps.pop(); if(s && this._steps.length>0){ this.focus(); this._changeToStep(this._steps[this._steps.length-1],s); this._steps.push(s); this.onDisplayChanged(); ret = true; } delete this._undoRedoActive; } return ret; }, endEditing: function(ignore_caret){ // summary: // Called to note that the user has stopped typing alphanumeric characters, if it's not already noted. // Deals with saving undo; see editActionInterval parameter. // tags: // private if(this._editTimer){ clearTimeout(this._editTimer); } if(this._inEditing){ this._endEditing(ignore_caret); this._inEditing=false; } }, _getBookmark: function(){ // summary: // Get the currently selected text // tags: // protected var b=dojo.withGlobal(this.window,dijit.getBookmark); var tmp=[]; if(b && b.mark){ var mark = b.mark; if(dojo.isIE){ // Try to use the pseudo range API on IE for better accuracy. var sel = dijit.range.getSelection(this.window); if(!dojo.isArray(mark)){ if(sel){ var range; if(sel.rangeCount){ range = sel.getRangeAt(0); } if(range){ b.mark = range.cloneRange(); }else{ b.mark = dojo.withGlobal(this.window,dijit.getBookmark); } } }else{ // Control ranges (img, table, etc), handle differently. dojo.forEach(b.mark,function(n){ tmp.push(dijit.range.getIndex(n,this.editNode).o); },this); b.mark = tmp; } } try{ if(b.mark && b.mark.startContainer){ tmp=dijit.range.getIndex(b.mark.startContainer,this.editNode).o; b.mark={startContainer:tmp, startOffset:b.mark.startOffset, endContainer:b.mark.endContainer===b.mark.startContainer?tmp:dijit.range.getIndex(b.mark.endContainer,this.editNode).o, endOffset:b.mark.endOffset}; } }catch(e){ b.mark = null; } } return b; }, _beginEditing: function(cmd){ // summary: // Called when the user starts typing alphanumeric characters. // Deals with saving undo; see editActionInterval parameter. // tags: // private if(this._steps.length === 0){ // You want to use the editor content without post filtering // to make sure selection restores right for the 'initial' state. // and undo is called. So not using this.savedContent, as it was 'processed' // and the line-up for selections may have been altered. this._steps.push({'text':dijit._editor.getChildrenHtml(this.editNode),'bookmark':this._getBookmark()}); } }, _endEditing: function(ignore_caret){ // summary: // Called when the user stops typing alphanumeric characters. // Deals with saving undo; see editActionInterval parameter. // tags: // private // Avoid filtering to make sure selections restore. var v = dijit._editor.getChildrenHtml(this.editNode); this._undoedSteps=[];//clear undoed steps this._steps.push({text: v, bookmark: this._getBookmark()}); }, onKeyDown: function(e){ // summary: // Handler for onkeydown event. // tags: // private //We need to save selection if the user TAB away from this editor //no need to call _saveSelection for IE, as that will be taken care of in onBeforeDeactivate if(!dojo.isIE && !this.iframe && e.keyCode == dojo.keys.TAB && !this.tabIndent){ this._saveSelection(); } if(!this.customUndo){ this.inherited(arguments); return; } var k = e.keyCode, ks = dojo.keys; if(e.ctrlKey && !e.altKey){//undo and redo only if the special right Alt + z/y are not pressed #5892 if(k == 90 || k == 122){ //z dojo.stopEvent(e); this.undo(); return; }else if(k == 89 || k == 121){ //y dojo.stopEvent(e); this.redo(); return; } } this.inherited(arguments); switch(k){ case ks.ENTER: case ks.BACKSPACE: case ks.DELETE: this.beginEditing(); break; case 88: //x case 86: //v if(e.ctrlKey && !e.altKey && !e.metaKey){ this.endEditing();//end current typing step if any if(e.keyCode == 88){ this.beginEditing('cut'); //use timeout to trigger after the cut is complete setTimeout(dojo.hitch(this, this.endEditing), 1); }else{ this.beginEditing('paste'); //use timeout to trigger after the paste is complete setTimeout(dojo.hitch(this, this.endEditing), 1); } break; } //pass through default: if(!e.ctrlKey && !e.altKey && !e.metaKey && (e.keyCode<dojo.keys.F1 || e.keyCode>dojo.keys.F15)){ this.beginEditing(); break; } //pass through case ks.ALT: this.endEditing(); break; case ks.UP_ARROW: case ks.DOWN_ARROW: case ks.LEFT_ARROW: case ks.RIGHT_ARROW: case ks.HOME: case ks.END: case ks.PAGE_UP: case ks.PAGE_DOWN: this.endEditing(true); break; //maybe ctrl+backspace/delete, so don't endEditing when ctrl is pressed case ks.CTRL: case ks.SHIFT: case ks.TAB: break; } }, _onBlur: function(){ // summary: // Called from focus manager when focus has moved away from this editor // tags: // protected //this._saveSelection(); this.inherited('_onBlur',arguments); this.endEditing(true); }, _saveSelection: function(){ // summary: // Save the currently selected text in _savedSelection attribute // tags: // private this._savedSelection=this._getBookmark(); //console.log('save selection',this._savedSelection,this); }, _restoreSelection: function(){ // summary: // Re-select the text specified in _savedSelection attribute; // see _saveSelection(). // tags: // private if(this._savedSelection){ // Clear off cursor to start, we're deliberately going to a selection. delete this._cursorToStart; // only restore the selection if the current range is collapsed // if not collapsed, then it means the editor does not lose // selection and there is no need to restore it if(dojo.withGlobal(this.window,'isCollapsed',dijit)){ this._moveToBookmark(this._savedSelection); } delete this._savedSelection; } }, onClick: function(){ // summary: // Handler for when editor is clicked // tags: // protected this.endEditing(true); this.inherited(arguments); }, _setDisabledAttr: function(/*Boolean*/ value){ var disableFunc = dojo.hitch(this, function(){ if((!this.disabled && value) || (!this._buttonEnabledPlugins && value)){ // Disable editor: disable all enabled buttons and remember that list this._buttonEnabledPlugins = dojo.filter(this._plugins, function(p){ if(p && p.button && !p.button.get("disabled")){ p.button.set("disabled", true); return true; } return false; }); }else if(this.disabled && !value){ // Enable editor: we only want to enable the buttons that should be // enabled (for example, the outdent button shouldn't be enabled if the current // text can't be outdented). dojo.forEach(this._buttonEnabledPlugins, function(p){ p.button.attr("disabled", false); p.updateState && p.updateState(); // just in case something changed, like caret position }); } }); this.setValueDeferred.addCallback(disableFunc); this.inherited(arguments); }, _setStateClass: function(){ this.inherited(arguments); // Let theme set the editor's text color based on editor enabled/disabled state. // We need to jump through hoops because the main document (where the theme CSS is) // is separate from the iframe's document. if(this.document && this.document.body){ dojo.style(this.document.body, "color", dojo.style(this.iframe, "color")); } } } ); // Register the "default plugins", ie, the built-in editor commands dojo.subscribe(dijit._scopeName + ".Editor.getPlugin",null,function(o){ if(o.plugin){ return; } var args = o.args, p; var _p = dijit._editor._Plugin; var name = args.name; switch(name){ case "undo": case "redo": case "cut": case "copy": case "paste": case "insertOrderedList": case "insertUnorderedList": case "indent": case "outdent": case "justifyCenter": case "justifyFull": case "justifyLeft": case "justifyRight": case "delete": case "selectAll": case "removeFormat": case "unlink": case "insertHorizontalRule": p = new _p({ command: name }); break; case "bold": case "italic": case "underline": case "strikethrough": case "subscript": case "superscript": p = new _p({ buttonClass: dijit.form.ToggleButton, command: name }); break; case "|": p = new _p({ button: new dijit.ToolbarSeparator(), setEditor: function(editor) {this.editor = editor;} }); } // console.log('name',name,p); o.plugin=p; }); }
najamelan/vhffs-4.5
vhffs-panel/js/dijit/Editor.js
JavaScript
bsd-3-clause
26,465
using JetBrains.Annotations; using Orchard.ContentManagement.Handlers; using Orchard.Data; using DevOffice.Secret.Models; namespace DevOffice.Secret.Handlers { [UsedImplicitly] public class EmailSettingsPartHandler : ContentHandler { public EmailSettingsPartHandler(IRepository<EmailSettingsPartRecord> repository) { Filters.Add(new ActivatingFilter<EmailSettingsPart>("Site")); Filters.Add(StorageFilter.For(repository)); } } }
ShuanWang/devoffice.com-shuanTestRepo
src/Orchard.Web/Modules/DevOffice.Secret/Handlers/EmailSettingsPartHandler.cs
C#
bsd-3-clause
496
/* * Copyright (C) 2016-2017 Fabrice Bouyé * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ package com.bouye.gw2.sab.scene.account; import api.web.gw2.mapping.v1.guilddetails.GuildDetails; import api.web.gw2.mapping.v2.account.Account; import api.web.gw2.mapping.v2.account.AccountAccessType; import api.web.gw2.mapping.v2.tokeninfo.TokenInfo; import api.web.gw2.mapping.v2.worlds.World; import com.bouye.gw2.sab.SABConstants; import com.bouye.gw2.sab.scene.SABControllerBase; import com.bouye.gw2.sab.session.Session; import com.bouye.gw2.sab.query.WebQuery; import com.bouye.gw2.sab.text.LabelUtils; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.css.PseudoClass; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.Labeled; import javafx.scene.layout.FlowPane; import javafx.scene.text.TextFlow; /** * FXML Controller class * @author Fabrice Bouyé */ public final class AccountInfoPaneController extends SABControllerBase<AccountInfoPane> { @FXML private Label accountIconLabel; @FXML private Label accountNameLabel; @FXML private Label accessLabel; @FXML private Hyperlink worldLink; @FXML private CheckBox commanderCheck; @FXML private TextFlow guildsTextFlow; @FXML private Label dailyApLabel; @FXML private Label monthlyApLabel; @FXML private Label wvwRankLabel; @FXML private FlowPane permissionsFlowPane; /** * Creates a new instance. */ public AccountInfoPaneController() { } @Override public void initialize(final URL url, final ResourceBundle rb) { } @Override public void dispose() { try { if (infoService != null) { infoService.cancel(); } } finally { super.dispose(); } } /** * Called whenever observed values are invalidated. */ private final InvalidationListener valueInvalidationListener = observable -> updateUI(); /** * Monitors the session validity. */ private BooleanBinding validBinding; @Override protected void uninstallNode(final AccountInfoPane parent) { parent.sessionProperty().removeListener(valueInvalidationListener); validBinding.removeListener(valueInvalidationListener); validBinding.dispose(); validBinding = null; clearOldStyle(parent); } @Override protected void installNode(final AccountInfoPane parent) { parent.sessionProperty().addListener(valueInvalidationListener); validBinding = Bindings.selectBoolean(parent.sessionProperty(), "valid"); // NOI18N. validBinding.addListener(valueInvalidationListener); } @Override protected void updateUI() { if (infoService != null) { infoService.cancel(); } final Optional<AccountInfoPane> parent = parentNode(); final Session session = parent.isPresent() ? parent.get().getSession() : null; parent.ifPresent(this::clearOldStyle); if (session == null || !session.isValid()) { // Other. accountNameLabel.setText(null); accessLabel.setText(null); commanderCheck.setSelected(false); dailyApLabel.setText(null); monthlyApLabel.setText(null); wvwRankLabel.setText(null); guildsTextFlow.getChildren().clear(); // Permissions. permissionsFlowPane.getChildren().clear(); } else { final Account account = session.getAccount(); final TokenInfo tokenInfo = session.getTokenInfo(); // Name. accountNameLabel.setText(account.getName()); final String accessText = account.getAccess() .stream() .map(LabelUtils.INSTANCE::toLabel) .collect(Collectors.joining(", ", "[", "]")); // NOI18N. accessLabel.setText(accessText); // final int worldId = account.getWorld(); worldLink.setUserData(worldId); worldLink.setOnAction(actionEvent -> displayWorldDetails(worldId)); worldLink.setText(String.valueOf(worldId)); // commanderCheck.setSelected(account.isCommander()); dailyApLabel.setText(String.valueOf(account.getDailyAp())); monthlyApLabel.setText(String.valueOf(account.getMonthlyAp())); wvwRankLabel.setText(String.valueOf(account.getWvwRank())); // final List<Labeled> guildLinks = account.getGuilds() .stream() .map(guildId -> { final Hyperlink guildLink = new Hyperlink(String.valueOf(guildId)); guildLink.setUserData(guildId); guildLink.setOnAction(actionEvent -> displayGuildDetails(guildId)); return guildLink; }) .collect(Collectors.toList()); guildsTextFlow.getChildren().setAll(guildLinks); // Permissions. final List<Label> permissionLabels = tokenInfo.getPermissions() .stream() .map(permission -> { final Label icon = new Label(SABConstants.I18N.getString("icon.fa.gear")); // NOI18N. icon.getStyleClass().addAll("awesome-icon", "permission-icon"); // NOI18N. final Label label = new Label(); label.getStyleClass().add("permission-label"); // NOI18N. final String text = LabelUtils.INSTANCE.toLabel(permission); label.setText(text); label.setGraphic(icon); return label; }) .collect(Collectors.toList()); permissionsFlowPane.getChildren().setAll(permissionLabels); updateOtherValuesAsync(session, worldLink, guildLinks); parent.ifPresent(this::installNewStyle); } } /** * Clear old style from given parent. * @param parent The parent, never {@code null}. */ private void clearOldStyle(final AccountInfoPane parent) { Arrays.stream(AccountAccessType.values()).forEach(accessType -> { final PseudoClass pseudoClass = LabelUtils.INSTANCE.toPseudoClass(accessType); parent.pseudoClassStateChanged(pseudoClass, false); }); } /** * Apply new style to given parent. * @param parent The parent, never {@code null}. */ private void installNewStyle(final AccountInfoPane parent) { final Session session = parent.getSession(); if (session != null && session.isValid()) { final Account account = session.getAccount(); final Set<AccountAccessType> access = account.getAccess(); final PseudoClass pseudoClass = LabelUtils.INSTANCE.toPseudoClass(access.stream() .findFirst() .orElse(AccountAccessType.NONE)); parent.pseudoClassStateChanged(pseudoClass, true); } } /** * Invoked when the user clicks on the world hyperlink. * @param worldId The id of the world to inspect. */ private void displayWorldDetails(final int worldId) { final Optional<AccountInfoPane> parent = Optional.ofNullable(getNode()); parent.ifPresent(p -> { final Optional<BiConsumer<Session, Integer>> onWorldDetails = Optional.ofNullable(p.getOnWorldDetails()); onWorldDetails.ifPresent(c -> c.accept(p.getSession(), worldId)); }); } /** * Invoked when the user clicks on one of the guild hyperlinks. * @param guildId The id of the guild to inspect. */ private void displayGuildDetails(final String guildId) { final Optional<AccountInfoPane> parent = Optional.ofNullable(getNode()); parent.ifPresent(p -> { final Optional<BiConsumer<Session, String>> onGuildDetails = Optional.ofNullable(p.getOnGuildDetails()); onGuildDetails.ifPresent(c -> c.accept(p.getSession(), guildId)); }); } private Service<Void> infoService; private void updateOtherValuesAsync(final Session session, final Labeled worldLabel, final List<Labeled> guildLinks) { if (infoService == null) { infoService = new Service<Void>() { @Override protected Task<Void> createTask() { return new AccountInfoUpdateTaks(session, worldLabel, guildLinks); } }; } addAndStartService(infoService, "AccountInfoPaneController::updateOtherValuesAsync"); } /** * Update info associated to an account (ie: server name, guilds' names, etc.). * @author Fabrice Bouyé */ private class AccountInfoUpdateTaks extends Task<Void> { private final Session session; private final Labeled worldLabel; private final List<Labeled> guildLinks; public AccountInfoUpdateTaks(final Session session, final Labeled worldLabel, final List<Labeled> guildLinks) { this.session = session; this.worldLabel = worldLabel; this.guildLinks = guildLinks; } @Override protected Void call() throws Exception { // World. final int worldId = (Integer) worldLabel.getUserData(); final List<World> worlds = WebQuery.INSTANCE.queryWorlds(worldId); if (!worlds.isEmpty()) { final World world = worlds.get(0); // Update on JavaFX application thread. Platform.runLater(() -> worldLabel.setText(world.getName())); } // Guild. final String[] guildIds = guildLinks.stream() .map(hyperlink -> (String) hyperlink.getUserData()) .toArray(size -> new String[size]); final Map<String, GuildDetails> guilds = WebQuery.INSTANCE.queryGuildDetails(guildIds) .stream() .collect(Collectors.toMap(guildDetails -> guildDetails.getGuildId(), Function.identity())); // Update on JavaFX application thread. Platform.runLater(() -> { guildLinks.stream().forEach(guildLink -> { final String guildId = (String) guildLink.getUserData(); final GuildDetails guildDetails = guilds.get(guildId); final String label = String.format("%s [%s]", guildDetails.getGuildName(), guildDetails.getTag()); guildLink.setText(label); }); }); return null; } } }
fabricebouye/gw2-sab
gw2-sab/src/com/bouye/gw2/sab/scene/account/AccountInfoPaneController.java
Java
bsd-3-clause
11,512
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_FILTERS_IMPL_PASSTHROUGH_HPP_ #define PCL_FILTERS_IMPL_PASSTHROUGH_HPP_ #include <pcl/filters/passthrough.h> #include <pcl/common/io.h> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::PassThrough<PointT>::applyFilter (PointCloud &output) { std::vector<int> indices; if (keep_organized_) { bool temp = extract_removed_indices_; extract_removed_indices_ = true; applyFilterIndices (indices); extract_removed_indices_ = temp; output = *input_; for (int rii = 0; rii < static_cast<int> (removed_indices_->size ()); ++rii) // rii = removed indices iterator output.points[(*removed_indices_)[rii]].x = output.points[(*removed_indices_)[rii]].y = output.points[(*removed_indices_)[rii]].z = user_filter_value_; if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; } else { output.is_dense = true; applyFilterIndices (indices); copyPointCloud (*input_, indices, output); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::PassThrough<PointT>::applyFilterIndices (std::vector<int> &indices) { // The arrays to be used indices.resize (indices_->size ()); removed_indices_->resize (indices_->size ()); int oii = 0, rii = 0; // oii = output indices iterator, rii = removed indices iterator // Has a field name been specified? if (filter_field_name_.empty ()) { // Only filter for non-finite entries then for (int iii = 0; iii < static_cast<int> (indices_->size ()); ++iii) // iii = input indices iterator { // Non-finite entries are always passed to removed indices if (!pcl_isfinite (input_->points[(*indices_)[iii]].x) || !pcl_isfinite (input_->points[(*indices_)[iii]].y) || !pcl_isfinite (input_->points[(*indices_)[iii]].z)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } indices[oii++] = (*indices_)[iii]; } } else { // Attempt to get the field name's index std::vector<pcl::PCLPointField> fields; int distance_idx = pcl::getFieldIndex (*input_, filter_field_name_, fields); if (distance_idx == -1) { PCL_WARN ("[pcl::%s::applyFilter] Unable to find field name in point type.\n", getClassName ().c_str ()); indices.clear (); removed_indices_->clear (); return; } // Filter for non-finite entries and the specified field limits for (int iii = 0; iii < static_cast<int> (indices_->size ()); ++iii) // iii = input indices iterator { // Non-finite entries are always passed to removed indices if (!pcl_isfinite (input_->points[(*indices_)[iii]].x) || !pcl_isfinite (input_->points[(*indices_)[iii]].y) || !pcl_isfinite (input_->points[(*indices_)[iii]].z)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Get the field's value const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&input_->points[(*indices_)[iii]]); float field_value = 0; memcpy (&field_value, pt_data + fields[distance_idx].offset, sizeof (float)); // Remove NAN/INF/-INF values. We expect passthrough to output clean valid data. if (!pcl_isfinite (field_value)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Outside of the field limits are passed to removed indices if (!negative_ && (field_value < filter_limit_min_ || field_value > filter_limit_max_)) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Inside of the field limits are passed to removed indices if negative was set if (negative_ && field_value > filter_limit_min_ && field_value < filter_limit_max_) { if (extract_removed_indices_) (*removed_indices_)[rii++] = (*indices_)[iii]; continue; } // Otherwise it was a normal point for output (inlier) indices[oii++] = (*indices_)[iii]; } } // Resize the output arrays indices.resize (oii); removed_indices_->resize (rii); } #define PCL_INSTANTIATE_PassThrough(T) template class PCL_EXPORTS pcl::PassThrough<T>; #endif // PCL_FILTERS_IMPL_PASSTHROUGH_HPP_
brucewu0329/pcl
filters/include/pcl/filters/impl/passthrough.hpp
C++
bsd-3-clause
6,347
import sys import collections class GeocoderResult(collections.Iterator): """ A geocoder resultset to iterate through address results. Exemple: results = Geocoder.geocode('paris, us') for result in results: print(result.formatted_address, result.location) Provide shortcut to ease field retrieval, looking at 'types' in each 'address_components'. Example: result.country result.postal_code You can also choose a different property to display for each lookup type. Example: result.country__short_name By default, use 'long_name' property of lookup type, so: result.country and: result.country__long_name are equivalent. """ attribute_mapping = { "state": "administrative_area_level_1", "province": "administrative_area_level_1", "city": "locality", "county": "administrative_area_level_2", } def __init__(self, data): """ Creates instance of GeocoderResult from the provided JSON data array """ self.data = data self.len = len(self.data) self.current_index = 0 self.current_data = self.data[0] def __len__(self): return self.len def __iter__(self): return self def return_next(self): if self.current_index >= self.len: raise StopIteration self.current_data = self.data[self.current_index] self.current_index += 1 return self def __getitem__(self, key): """ Accessing GeocoderResult by index will return a GeocoderResult with just one data entry """ return GeocoderResult([self.data[key]]) def __unicode__(self): return self.formatted_address if sys.version_info[0] >= 3: # Python 3 def __str__(self): return self.__unicode__() def __next__(self): return self.return_next() else: # Python 2 def __str__(self): return self.__unicode__().encode('utf8') def next(self): return self.return_next() @property def count(self): return self.len @property def coordinates(self): """ Return a (latitude, longitude) coordinate pair of the current result """ location = self.current_data['geometry']['location'] return location['lat'], location['lng'] @property def latitude(self): return self.coordinates[0] @property def longitude(self): return self.coordinates[1] @property def raw(self): """ Returns the full result set in dictionary format """ return self.data @property def valid_address(self): """ Returns true if queried address is valid street address """ return self.current_data['types'] == ['street_address'] @property def formatted_address(self): return self.current_data['formatted_address'] def __getattr__(self, name): lookup = name.split('__') attribute = lookup[0] if (attribute in GeocoderResult.attribute_mapping): attribute = GeocoderResult.attribute_mapping[attribute] try: prop = lookup[1] except IndexError: prop = 'long_name' for elem in self.current_data['address_components']: if attribute in elem['types']: return elem[prop] class GeocoderError(Exception): """Base class for errors in the :mod:`pygeocoder` module. Methods of the :class:`Geocoder` raise this when something goes wrong. """ #: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes #: for information on the meaning of these status codes. G_GEO_OK = "OK" G_GEO_ZERO_RESULTS = "ZERO_RESULTS" G_GEO_OVER_QUERY_LIMIT = "OVER_QUERY_LIMIT" G_GEO_REQUEST_DENIED = "REQUEST_DENIED" G_GEO_MISSING_QUERY = "INVALID_REQUEST" def __init__(self, status, url=None, response=None): """Create an exception with a status and optional full response. :param status: Either a ``G_GEO_`` code or a string explaining the exception. :type status: int or string :param url: The query URL that resulted in the error, if any. :type url: string :param response: The actual response returned from Google, if any. :type response: dict """ Exception.__init__(self, status) # Exception is an old-school class self.status = status self.url = url self.response = response def __str__(self): """Return a string representation of this :exc:`GeocoderError`.""" return 'Error %s\nQuery: %s' % (self.status, self.url) def __unicode__(self): """Return a unicode representation of this :exc:`GeocoderError`.""" return unicode(self.__str__())
zoeren/pygeocoder
pygeolib.py
Python
bsd-3-clause
4,972
(function() { 'use strict'; angular.module('character-tracker.charactersheet') .controller('GearController', GearController); GearController.$inject =['GearService', 'InventoryService', '$scope']; function GearController(GearService, InventoryService, $scope) { var vm = this; var currentItem = ''; vm.inventory = InventoryService.getItems(); vm.gearSlots = GearService.getGearSlots(); vm.equipItem = function (item, slot){ if (item.equipped) { vm.unequipItem(item); } for (i = 0; i < vm.gearSlots.length; i++) { if (vm.gearSlots[i].slot === slot) { vm.gearSlots[i].equipped = true; vm.gearSlots[i].equippedItem = item; } } InventoryService.equipItem(item); } vm.unequipItem = function(item) { for (i = 0; i < vm.gearSlots.length; i++) { if (vm.gearSlots[i].equippedItem == item) { vm.gearSlots[i].equippedItem = {}; } InventoryService.unequipItem(item); } } vm.getItemAtSlot = function(slot) { currentItem = InventoryService.getItemAtSlot(slot); } init(); function init() { $.material.init(); } return vm; } }());
tenthirtyone/character-tracker
app/js/tracker/gear/gear.controller.js
JavaScript
bsd-3-clause
1,270
<?php /** * Classe de abstração para as controllers de crud do sistema * Define as funções principais dos cruds do sistema */ namespace Estrutura\Controller; use Zend\View\Model\JsonModel; use Zend\View\Model\ViewModel; use Estrutura\Helpers\Cript; abstract class AbstractCrudController extends AbstractEstruturaController { public function index($service, $form, $atributos = []) { $dadosView = [ 'service' => $service, 'form' => $form, 'lista' => $service->filtrarObjeto(), 'controller' => $this->params('controller'), 'atributos' => $atributos ]; return new ViewModel($dadosView); } public function cadastro($service, $form, $atributos = []) { $id = Cript::dec($this->params('id')); $post = $this->getPost(); if ($id) { $form->setData($service->buscar($id)->toArray()); } if (!empty($post)) { $form->setData($post); } $dadosView = [ 'service' => $service, 'form' => $form, 'controller' => $this->params('controller'), 'atributos' => $atributos ]; return new ViewModel($dadosView); } public function gravar($service, $form) { try { $controller = $this->params('controller'); $request = $this->getRequest(); if (!$request->isPost()) { throw new \Exception('Dados Inválidos'); } $post = \Estrutura\Helpers\Utilities::arrayMapArray('trim', $request->getPost()->toArray()); $files = $request->getFiles(); $upload = $this->uploadFile($files); $post = array_merge($post, $upload); if (isset($post['id']) && $post['id']) { $post['id'] = Cript::dec($post['id']); } $form->setData($post); if (!$form->isValid()) { $this->addValidateMessages($form); $this->setPost($post); $this->redirect()->toRoute('navegacao', array('controller' => $controller, 'action' => 'cadastro')); return false; } $service->exchangeArray($form->getData()); return $service->salvar(); } catch (\Exception $e) { $this->setPost($post); $this->addErrorMessage($e->getMessage()); $this->redirect()->toRoute('navegacao', array('controller' => $controller, 'action' => 'cadastro')); return false; } } public function gravarEmTabelaNaoIdentity($service, $form) { try { $controller = $this->params('controller'); $request = $this->getRequest(); if (!$request->isPost()) { throw new \Exception('Dados Inválidos'); } $post = \Estrutura\Helpers\Utilities::arrayMapArray('trim', $request->getPost()->toArray()); $form->setData($post); if (!$form->isValid()) { $this->addValidateMessages($form); $this->setPost($post); $this->redirect()->toRoute('navegacao', array('controller' => $controller, 'action' => 'cadastro')); return false; } $service->exchangeArray($form->getData()); return $service->inserir_nao_identity(); } catch (\Exception $e) { $this->setPost($post); $this->addErrorMessage($e->getMessage()); $this->redirect()->toRoute('navegacao', array('controller' => $controller, 'action' => 'cadastro')); return false; } } public function excluir($service, $form, $atributos = []) { try { $request = $this->getRequest(); if ($request->isPost()) { return new JsonModel(); } $controller = $this->params('controller'); $id = Cript::dec($this->params('id')); $service->setId($id); $dados = $service->filtrarObjeto()->current(); if (!$dados) { throw new \Exception('Registro não encontrado'); } $service->excluir(); $this->addSuccessMessage('Registro excluido com sucesso'); return $this->redirect()->toRoute('navegacao', ['controller' => $controller]); } catch (\Exception $e) { if( strstr($e->getMessage(), '1451') ) { #ERRO de SQL (Mysql) para nao excluir registro que possua filhos $this->addErrorMessage('Para excluir a academia voce deve excluir todos os atletas da academia. Verifique!'); }else { $this->addErrorMessage($e->getMessage()); } return $this->redirect()->toRoute('navegacao', ['controller' => $controller]); } } public function uploadFile($files, $local = './data/arquivos') { $retorno = []; foreach ($files as $name => $file) { $filter = new \Zend\Filter\File\RenameUpload(array( 'target' => $local, 'randomize' => true, )); $filter->setUseUploadName(true); $filter->setOverwrite(true); // $filter->filter($file); $retorno[$name] = $filter->filter($file); } return $retorno; } }
Igor-Oliveira-Mota-Pires/pi1_ls
module/Estrutura/src/Estrutura/Controller/AbstractCrudController.php
PHP
bsd-3-clause
5,435
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup from djangocms_carousel import __version__ INSTALL_REQUIRES = [ ] CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Communications', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ] setup( name='djangocms-carousel', version=__version__, description='Slider Plugin for django CMS', author='Andrew Mirsky', author_email='andrew@mirsky.net', url='https://git.mirsky.net/mirskyconsulting/djangocms-carousel', packages=['djangocms_carousel', 'djangocms_carousel.migrations'], install_requires=INSTALL_REQUIRES, license='LICENSE.txt', platforms=['OS Independent'], classifiers=CLASSIFIERS, long_description=open('README.md').read(), include_package_data=True, zip_safe=False )
mirskytech/djangocms-carousel
setup.py
Python
bsd-3-clause
1,241
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/mocks/mock_webhyphenator.h" #include "base/logging.h" #include "base/memory/scoped_handle.h" #include "base/memory/scoped_ptr.h" #include "base/string_util.h" #include "third_party/hyphen/hyphen.h" namespace webkit_glue { MockWebHyphenator::MockWebHyphenator() : hyphen_dictionary_(NULL) { } MockWebHyphenator::~MockWebHyphenator() { if (hyphen_dictionary_) hnj_hyphen_free(hyphen_dictionary_); } void MockWebHyphenator::LoadDictionary(base::PlatformFile dict_file) { CHECK(!hyphen_dictionary_); // Initialize the hyphen library with a sample dictionary. To avoid test // flakiness, this code synchronously loads the dictionary. if (dict_file == base::kInvalidPlatformFileValue) { NOTREACHED(); return; } ScopedStdioHandle dict_handle(base::FdopenPlatformFile(dict_file, "r")); if (!dict_handle.get()) { NOTREACHED(); base::ClosePlatformFile(dict_file); return; } hyphen_dictionary_ = hnj_hyphen_load_file(dict_handle.get()); DCHECK(hyphen_dictionary_); } bool MockWebHyphenator::canHyphenate(const WebKit::WebString& locale) { return locale.isEmpty() || locale.equals("en") || locale.equals("en_US") || locale.equals("en_GB"); } size_t MockWebHyphenator::computeLastHyphenLocation( const char16* characters, size_t length, size_t before_index, const WebKit::WebString& locale) { DCHECK(locale.isEmpty() || locale.equals("en") || locale.equals("en_US") || locale.equals("en_GB")); if (!hyphen_dictionary_) return 0; // Retrieve the positions where we can insert hyphens. This function assumes // the input word is an English word so it can use the position returned by // the hyphen library without conversion. string16 word_utf16(characters, length); if (!IsStringASCII(word_utf16)) return 0; std::string word = StringToLowerASCII(UTF16ToASCII(word_utf16)); scoped_array<char> hyphens(new char[word.length() + 5]); char** rep = NULL; int* pos = NULL; int* cut = NULL; int error = hnj_hyphen_hyphenate2(hyphen_dictionary_, word.data(), static_cast<int>(word.length()), hyphens.get(), NULL, &rep, &pos, &cut); if (error) return 0; // Release all resources allocated by the hyphen library now because they are // not used when hyphenating English words. if (rep) { for (size_t i = 0; i < word.length(); ++i) { if (rep[i]) free(rep[i]); } free(rep); } if (pos) free(pos); if (cut) free(cut); // Retrieve the last position where we can insert a hyphen before the given // index. if (before_index >= 2) { for (size_t index = before_index - 2; index > 0; --index) { if (hyphens[index] & 1) return index + 1; } } return 0; } } // namespace webkit_glue
timopulkkinen/BubbleFish
webkit/mocks/mock_webhyphenator.cc
C++
bsd-3-clause
3,201
<?php /** * Generates the model * * @author Thiago Rigo <thiagophx@gmail.com> * @since 1.0 * @package crudigniter * @subpackage generator */ class ModelGenerator extends Generator { /** * Constructor * * @see crudigniter/generator/Generator#__construct() */ public function __construct() { parent::__construct('Model'); } /** * Generates the model's file * * @see crudigniter/generator/Generator#generate() */ public function generate() { $model = ProjectIgniter::getName() . DS . 'application' . DS . strtolower($this->layer . 's') . DS . strtolower($this->tables[$this->choosedLayer]['Name']) . '_' . strtolower($this->layer) . '.php'; $content = parent::getTemplate(); if ($content === false) { ConsoleIgniter::write($this->layer . ' ' . $model . ' was not created!'); } else { if ($this->overrideFile(PROJECTS_PATH . DS . $model)) { file_put_contents(PROJECTS_PATH . DS . $model, $content); ConsoleIgniter::write($this->layer . ' ' . $model . ' was successfully created!'); } else { ConsoleIgniter::write($this->layer . ' ' . $model . ' was not created!'); } } } }
thiagophx/CrudIgniter
crudigniter/generator/ModelGenerator.php
PHP
bsd-3-clause
1,142
/* * Copyright (c) 2009-2012, 2016 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.bullet.joints; import com.jme3.bullet.objects.PhysicsRigidBody; import com.jme3.export.*; import com.jme3.math.Vector3f; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> * PhysicsJoint - Basic Phyiscs Joint * </p> * * @author normenhansen */ public abstract class PhysicsJoint implements Savable { protected long objectId = 0; protected PhysicsRigidBody nodeA; protected PhysicsRigidBody nodeB; protected Vector3f pivotA; protected Vector3f pivotB; protected boolean collisionBetweenLinkedBodys = true; public PhysicsJoint() { } /** * @param nodeA first node of the joint * @param nodeB second node of the joint * @param pivotA local translation of the joint connection point in node A * @param pivotB local translation of the joint connection point in node B */ public PhysicsJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB) { this.nodeA = nodeA; this.nodeB = nodeB; this.pivotA = pivotA; this.pivotB = pivotB; nodeA.addJoint(this); nodeB.addJoint(this); } public float getAppliedImpulse() { return getAppliedImpulse(objectId); } private native float getAppliedImpulse(long objectId); /** * @return the constraint */ public long getObjectId() { return objectId; } /** * @return the collisionBetweenLinkedBodys */ public boolean isCollisionBetweenLinkedBodys() { return collisionBetweenLinkedBodys; } /** * toggles collisions between linked bodys<br> * joint has to be removed from and added to PhyiscsSpace to apply this. * * @param collisionBetweenLinkedBodys set to false to have no collisions * between linked bodys */ public void setCollisionBetweenLinkedBodys(boolean collisionBetweenLinkedBodys) { this.collisionBetweenLinkedBodys = collisionBetweenLinkedBodys; } public PhysicsRigidBody getBodyA() { return nodeA; } public PhysicsRigidBody getBodyB() { return nodeB; } public Vector3f getPivotA() { return pivotA; } public Vector3f getPivotB() { return pivotB; } /** * destroys this joint and removes it from its connected PhysicsRigidBodys * joint lists */ public void destroy() { getBodyA().removeJoint(this); getBodyB().removeJoint(this); } @Override public void write(JmeExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(nodeA, "nodeA", null); capsule.write(nodeB, "nodeB", null); capsule.write(pivotA, "pivotA", null); capsule.write(pivotB, "pivotB", null); } @Override public void read(JmeImporter im) throws IOException { InputCapsule capsule = im.getCapsule(this); this.nodeA = ((PhysicsRigidBody) capsule.readSavable("nodeA", new PhysicsRigidBody())); this.nodeB = (PhysicsRigidBody) capsule.readSavable("nodeB", new PhysicsRigidBody()); this.pivotA = (Vector3f) capsule.readSavable("pivotA", new Vector3f()); this.pivotB = (Vector3f) capsule.readSavable("pivotB", new Vector3f()); } @Override protected void finalize() throws Throwable { try { Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Finalizing Joint {0}", Long.toHexString(objectId)); finalizeNative(objectId); } finally { super.finalize(); } } protected native void finalizeNative(long objectId); }
bertleft/jmonkeyengine
jme3-bullet/src/main/java/com/jme3/bullet/joints/PhysicsJoint.java
Java
bsd-3-clause
5,286
using System; using Microservice.Membership.Subsys.v1.Actions; using StoryLine; using StoryLine.Rest.Actions; using StoryLine.Rest.Expectations; using StoryLine.Rest.Expectations.Extensions; using StoryLine.Rest.Extensions; using StoryLine.Rest.Services.Http; using StoryLine.Utils.Actions; using StoryLine.Utils.Services; using Xunit; namespace Microservice.Membership.Subsys.v1.Resources.User { public class Get : ApiTestBase { [Fact] public void When_User_Not_Found_Should_Return_404() { Scenario.New() .When() .Performs<HttpRequest>(x => x .Method("GET") .Url("/v1/users/" + Guid.NewGuid())) .Then() .Expects<HttpResponse>(x => x .Status(404)) .Run(); } [Fact] public void When_User_Exists_Should_Return_200_And_Body_Should_Match_Resource_File() { Scenario.New() .Given() .HasPerformed<AddUser>(x => x .FirstName("Diamond") .LastName("Dragon") .Age(33)) .HasPerformed<Transform, IResponse>((x, response) => x .From(response.GetText()) .To<Models.User>() .Using<JsonConverter>()) .When() .Performs<HttpRequest, Models.User>((x, user) => x .Method("GET") .Url($"/v1/users/{user.Id}")) .Then() .Expects<HttpResponse>(x => x .Status(200) .JsonBody() .Matches() .ResourceFile(new[] { "$.id", "$.createdOn", "$.updatedOn" })) .Run(); } } }
DiamondDragon/StoryLine.Rest
Examples/Microservice.Membership.Subsys/v1/Resources/User/Get.cs
C#
bsd-3-clause
1,947
#ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_GCC_ARM_HPP_INCLUDED #define BOOST_SMART_PTR_DETAIL_SPINLOCK_GCC_ARM_HPP_INCLUDED // // Copyright (c) 2008, 2011 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/smart_ptr/detail/yield_k.hpp> #if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7S__) # define BOOST_SP_ARM_BARRIER "dmb" # define BOOST_SP_ARM_HAS_LDREX #elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) # define BOOST_SP_ARM_BARRIER "mcr p15, 0, r0, c7, c10, 5" # define BOOST_SP_ARM_HAS_LDREX #else # define BOOST_SP_ARM_BARRIER "" #endif namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace detail { class spinlock { public: int v_; public: bool try_lock() { int r; #ifdef BOOST_SP_ARM_HAS_LDREX __asm__ __volatile__( "ldrex %0, [%2]; \n" "cmp %0, %1; \n" "strexne %0, %1, [%2]; \n" BOOST_SP_ARM_BARRIER : "=&r"( r ): // outputs "r"( 1 ), "r"( &v_ ): // inputs "memory", "cc" ); #else __asm__ __volatile__( "swp %0, %1, [%2];\n" BOOST_SP_ARM_BARRIER : "=&r"( r ): // outputs "r"( 1 ), "r"( &v_ ): // inputs "memory", "cc" ); #endif return r == 0; } void lock() { for( unsigned k = 0; !try_lock(); ++k ) { pdalboost::detail::yield( k ); } } void unlock() { __asm__ __volatile__( BOOST_SP_ARM_BARRIER ::: "memory" ); *const_cast< int volatile* >( &v_ ) = 0; } public: class scoped_lock { private: spinlock & sp_; scoped_lock( scoped_lock const & ); scoped_lock & operator=( scoped_lock const & ); public: explicit scoped_lock( spinlock & sp ): sp_( sp ) { sp.lock(); } ~scoped_lock() { sp_.unlock(); } }; }; } // namespace detail } // namespace pdalboost #define BOOST_DETAIL_SPINLOCK_INIT {0} #undef BOOST_SP_ARM_BARRIER #undef BOOST_SP_ARM_HAS_LDREX #endif // #ifndef BOOST_SMART_PTR_DETAIL_SPINLOCK_GCC_ARM_HPP_INCLUDED
verma/PDAL
boost/boost/smart_ptr/detail/spinlock_gcc_arm.hpp
C++
bsd-3-clause
2,554
module.exports = { selector: '.skilifts .skilift', parse: { name: 1, status: { child: 0, attribute: 'class', regex: / ([a-z]+)$/ } } };
pirxpilot/liftie
lib/resorts/larosiere/index.js
JavaScript
bsd-3-clause
172
<?php namespace MyClient\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator; use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator; use Zend\Paginator\Paginator; use MyClient\Entity; use Zend\Form\Element; use Zend\Form\Form; class ClientController extends AbstractActionController { private $repository; public function indexAction() { $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $page = $this->params()->fromRoute('page'); $max = 15; //---Paging with query $query = $objectManager->createQuery('SELECT f FROM \MyClient\Entity\Client f ORDER by f.state DESC, f.id ASC'); $adapter = new DoctrinePaginator(new ORMPaginator($query)); $paginator = new Paginator($adapter); // var_dump($page); $paginator ->setCurrentPageNumber($page) ->setItemCountPerPage($max); $pgCntrl = $this->getServiceLocator()->get('viewhelpermanager')->get('paginationcontrol'); // var_dump($paginator->getItemsByPage($page)); $view = new ViewModel(array( 'clients' => $paginator, 'paginator' => $pgCntrl($paginator, 'sliding', array('partial/paginator.twig', 'Clients'), array('route' => 'clients')) )); return $view; } public function viewAction() { // Check if id and blogpost exists. $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { $this->flashMessenger()->addErrorMessage('Client id doesn\'t set'); return $this->redirect()->toRoute('clients'); } $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $client = $objectManager ->getRepository('\MyClient\Entity\Client') ->findOneBy(array('id' => $id)); if (!$client) { $this->flashMessenger()->addErrorMessage(sprintf('Client with id %s doesn\'t exists', $id)); return $this->redirect()->toRoute('clients'); } /** @var \MyUser\Entity\User $user */ $user = $this->zfcUserAuthentication()->getIdentity(); var_dump($user->getRoles()); //var_dump($client); // Render template. $view = new ViewModel(array( 'client' => $client->getArrayCopy(), )); // WMD if can use diferent tamplate $view->setTemplate('school/school/details.phtml'); return $view; } public function addAction() { $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $form = new \MyClient\Form\ClientForm($objectManager); $form->get('submit')->setValue('Add'); // $form->add(array( // 'type' => 'Zend\Form\Element\Select', // 'name' => 'language', // 'options' => array( // 'label' => 'Which is your mother tongue?', // 'empty_option' => 'Please choose your language', // 'value_options' => array( // '0' => 'French', // '1' => 'English', // '2' => 'Japanese', // '3' => 'Chinese', // ), // ) // )); // // $select = new Element\Select('language'); // $select->setLabel('Which is your mother tongue?'); // $select->setValueOptions(array( // 'european' => array( // 'label' => 'European languages', // 'options' => array( // '0' => 'French', // '1' => 'Italian', // ), // ), // 'asian' => array( // 'label' => 'Asian languages', // 'options' => array( // '2' => 'Japanese', // '3' => 'Chinese', // ), // ), // )); // // $form = new Form('language'); // $form->add($select); $request = $this->getRequest(); if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $firm = $objectManager->getRepository('\MyFirm\Entity\Firm')->findOneBy(array('id' => $form->get("firm_id")->getValue())); $user = $this->zfcUserAuthentication()->getIdentity(); $client = new \MyClient\Entity\Client(); $client->exchangeArray($form->getData()); $client->setState(1); $client->setUser($user); $client->setFirm($firm); if (!$client->getUse_Balance()) $client->setUse_Balance(0); // Get addmount $formArr = $form->getData(); $amount = (float) str_replace(",",".",$formArr['addamount']); $client->setBalance($amount); $objectManager->persist($client); $objectManager->flush(); if ($amount != 0) { // New Invoice to add amount $invoice = new \MyApi\Entity\Invoice(); $user = $this->zfcUserAuthentication()->getIdentity(); $invoice->setState(1); $invoice->setAmount($amount); $invoice->setClient($client); $invoice->setUser($user); $invoice->setBalance($amount); $invoice->setComment('Прямое начисление'); $objectManager->persist($invoice); $objectManager->flush(); $message = $amount . ' UAH succesfully added! <br>'; $this->flashMessenger()->addMessage($message); } $message = 'Client succesfully saved!'; $this->flashMessenger()->addMessage($message); // Redirect to list of blogposts return $this->redirect()->toRoute('clients'); } else { $message = 'Error while saving client'; $this->flashMessenger()->addErrorMessage($message); } } return array('form' => $form); } public function editAction() { // Check if id set. $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { $this->flashMessenger()->addErrorMessage('Client id doesn\'t set'); return $this->redirect()->toRoute('clients'); } $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); // Create form. $form = new \MyClient\Form\ClientForm($objectManager); $form->get('submit')->setValue('Save'); $request = $this->getRequest(); if (!$request->isPost()) { /** @var \MyClient\Entity\Client $client */ $client = $objectManager ->getRepository('\MyClient\Entity\Client') ->findOneBy(array('id' => $id)); if (!$client) { $this->flashMessenger()->addErrorMessage(sprintf('Client with id %s doesn\'t exists', $id)); return $this->redirect()->toRoute('clients'); } $invoices = $objectManager->getRepository('MyApi\Entity\Invoice')->findBy(array('client_id' => $client->getId()), array('created' => 'DESC')); // Fill form data. $form->bind($client); return array('form' => $form, 'id' => $id, 'client' => $client, 'invoices' => $invoices); } else { $form->setData($request->getPost()); if ($form->isValid()) { $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $data = $form->getData(); $id = $data['id']; try { /** @var \MyClient\Entity\Client $clientP */ $clientP = $objectManager->find('\MyClient\Entity\Client', $id); } catch (\Exception $ex) { return $this->redirect()->toRoute('clients', array( 'action' => 'index' )); } // Save current balance $balance = $clientP->getBalance(); $clientP->exchangeArray($form->getData()); // Get addmount $formArr = $form->getData(); $amount = (float) str_replace(",",".",$formArr['addamount']); if ($amount != 0) { $balance += $amount; // New Invoice to add amount $invoice = new \MyApi\Entity\Invoice(); $user = $this->zfcUserAuthentication()->getIdentity(); $invoice->setState(1); $invoice->setAmount($amount); $invoice->setClient($clientP); $invoice->setUser($user); $invoice->setBalance($balance); $invoice->setComment('Прямое начисление'); $objectManager->persist($invoice); $objectManager->flush(); $message = $amount . ' UAH succesfully added! <br>'; $this->flashMessenger()->addMessage($message); } $clientP->setBalance($balance); $objectManager->persist($clientP); $objectManager->flush(); $message = 'Client succesfully saved!'; $this->flashMessenger()->addMessage($message); // Redirect to list of blogposts return $this->redirect()->toRoute('clients'); } else { $message = 'Error while saving client'; $this->flashMessenger()->addErrorMessage($message); return array('form' => $form, 'id' => $id); } } } /** Delete user method * @return array|\Zend\Http\Response */ public function deleteAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { $this->flashMessenger()->addErrorMessage('Client id doesn\'t set'); return $this->redirect()->toRoute('clients'); } $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $request = $this->getRequest(); if ($request->isPost()) { $del = $request->getPost('del', 'No'); if ($del == 'Yes') { $id = (int) $request->getPost('id'); try { /** @var \MyClient\Entity\Client $user */ $user = $objectManager->find('MyClient\Entity\Client', $id); $user->setState(0); $objectManager->persist($user); //remove $objectManager->flush(); } catch (\Exception $ex) { $this->flashMessenger()->addErrorMessage('Error while deleting data'); return $this->redirect()->toRoute('clients', array( 'action' => 'index' )); } $this->flashMessenger()->addMessage(sprintf('Client %d was succesfully deleted', $id)); } return $this->redirect()->toRoute('clients'); } return array( 'id' => $id, 'client' => $objectManager->find('MyClient\Entity\Client', $id)->getArrayCopy(), ); } /** Restore user method * @return array|\Zend\Http\Response */ public function restoreAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { $this->flashMessenger()->addErrorMessage('Client id doesn\'t set'); return $this->redirect()->toRoute('clients'); } $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $request = $this->getRequest(); if ($request->isPost()) { $res = $request->getPost('res', 'No'); if ($res == 'Yes') { $id = (int) $request->getPost('id'); try { /** @var \MyClient\Entity\Client $user */ $user = $objectManager->find('MyClient\Entity\Client', $id); $user->setState(1); $objectManager->persist($user); //remove $objectManager->flush(); } catch (\Exception $ex) { $this->flashMessenger()->addErrorMessage('Error while restored data'); return $this->redirect()->toRoute('clients', array( 'action' => 'index' )); } $this->flashMessenger()->addMessage(sprintf('Client %d was succesfully restored', $id)); } return $this->redirect()->toRoute('clients'); } return array( 'id' => $id, 'client' => $objectManager->find('MyUser\Entity\User', $id)->getArrayCopy(), ); } }
wmdmgv/crm
module/MyClient/src/MyClient/Controller/ClientController.php
PHP
bsd-3-clause
13,341
/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.core.stub; import org.jmock.core.Invocation; import org.jmock.core.Stub; import org.jmock.util.Assert; public class ThrowStub extends Assert implements Stub { private Throwable throwable; public ThrowStub(Throwable throwable) { this.throwable = throwable; } public Object invoke(Invocation invocation) throws Throwable { if (isThrowingCheckedException()) { checkTypeCompatiblity(invocation.invokedMethod.getExceptionTypes()); } throwable.fillInStackTrace(); throw throwable; } public StringBuffer describeTo(StringBuffer buffer) { return buffer.append("throws <").append(throwable).append(">"); } private void checkTypeCompatiblity(Class[] allowedExceptionTypes) { for (int i = 0; i < allowedExceptionTypes.length; i++) { if (allowedExceptionTypes[i].isInstance(throwable)) return; } reportIncompatibleCheckedException(allowedExceptionTypes); } private void reportIncompatibleCheckedException(Class[] allowedTypes) { StringBuffer message = new StringBuffer(); message.append("tried to throw a "); message.append(throwable.getClass().getName()); message.append(" from a method that throws "); if (allowedTypes.length == 0) { message.append("no exceptions"); } else { for (int i = 0; i < allowedTypes.length; i++) { if (i > 0) message.append(","); message.append(allowedTypes[i].getName()); } } fail(message.toString()); } private boolean isThrowingCheckedException() { return !(throwable instanceof RuntimeException || throwable instanceof Error); } }
al3xandru/testng-jmock
core/src/org/jmock/core/stub/ThrowStub.java
Java
bsd-3-clause
1,847
<?php namespace Catalog\Service; use Catalog\Model\Product; use Catalog\Mapper\ProductMapperInterface; class ProductService implements ProductServiceInterface { protected $productMapper; public function __construct(ProductMapperInterface $productMapper) { $this->productMapper = $productMapper; } /** * {@inheritDoc} */ public function findAllProducts() { return $this->productMapper->findAll(); } /** * {@inheritDoc} */ public function findProduct($id) { return $this->productMapper->find($id); } /** * {@inheritDoc} */ public function saveOrderLinks( $data ) { return $this->productMapper->saveOrderLinks( $data ); } /** * {@inheritDoc} */ public function getOrderLink( $id ) { return $this->productMapper->getOrderLink( $id ); } public function getOptions( ) { return $this->productMapper->getOptions( ); } public function getCategories( ) { return $this->productMapper->getCategories( ); } public function saveProducts( $data ) { return $this->productMapper->saveProducts( $data ); } public function getProducts( $where ) { return $this->productMapper->getProducts( $where ); } public function disableProducts( $parent_id, $ids ) { return $this->productMapper->disableProducts( $parent_id, $ids ); } public function getProductsByCategory( ) { return $this->productMapper->getProductsByCategory( ); } public function getOrderdProducts( $pids = array(), $cat_ids = array() ) { return $this->productMapper->getOrderdProducts( $pids , $cat_ids ); } public function saveOrder( $data = array() ) { return $this->productMapper->saveOrder( $data ); } public function getOrder( $id = 0 ) { return $this->productMapper->getOrder( $id ); } public function login($data ) { return $this->productMapper->login( $data); } }
izaap/bsp
module/Catalog/src/Catalog/Service/ProductService.php
PHP
bsd-3-clause
2,187
import amitgroup as ag import numpy as np ag.set_verbose(True) # This requires you to have the MNIST data set. data, digits = ag.io.load_mnist('training', selection=slice(0, 100)) pd = ag.features.PartsDescriptor((5, 5), 20, patch_frame=1, edges_threshold=5, samples_per_image=10) # Use only 100 of the digits pd.train_from_images(data) # Save the model to a file. #pd.save('parts_model.npy') # You can then load it again by #pd = ag.features.PartsDescriptor.load(filename) # Then you can extract features by #features = pd.extract_features(image) # Visualize the parts ag.plot.images(pd.visparts)
amitgroup/amitgroup
examples/parts_descriptor_test.py
Python
bsd-3-clause
608
<?php return array( 'translator' => array( 'locale' => 'zh_TW', ) ); ?>
hale0124/H2o
config/autoload/language.global.php
PHP
bsd-3-clause
88
#ifndef STAN_MATH_REV_FUN_ASIN_HPP #define STAN_MATH_REV_FUN_ASIN_HPP #include <stan/math/prim/fun/asin.hpp> #include <stan/math/prim/fun/abs.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/rev/meta.hpp> #include <stan/math/rev/fun/abs.hpp> #include <stan/math/rev/fun/asinh.hpp> #include <stan/math/rev/fun/value_of_rec.hpp> #include <cmath> #include <complex> namespace stan { namespace math { /** * Return the principal value of the arc sine, in radians, of the * specified variable (cmath). * * The derivative is defined by * * \f$\frac{d}{dx} \arcsin x = \frac{1}{\sqrt{1 - x^2}}\f$. * * \f[ \mbox{asin}(x) = \begin{cases} \textrm{NaN} & \mbox{if } x < -1\\ \arcsin(x) & \mbox{if } -1\leq x\leq 1 \\ \textrm{NaN} & \mbox{if } x > 1\\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{asin}(x)}{\partial x} = \begin{cases} \textrm{NaN} & \mbox{if } x < -1\\ \frac{\partial\, \arcsin(x)}{\partial x} & \mbox{if } -1\leq x\leq 1 \\ \textrm{NaN} & \mbox{if } x < -1\\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial \, \arcsin(x)}{\partial x} = \frac{1}{\sqrt{1-x^2}} \f] * * @param x Variable in range [-1, 1]. * @return Arc sine of variable, in radians. */ inline var asin(const var& x) { return make_callback_var(std::asin(x.val()), [x](const auto& vi) mutable { x.adj() += vi.adj() / std::sqrt(1.0 - (x.val() * x.val())); }); } /** * Return the principal value of the arc sine, in radians, of the * specified variable (cmath). * * @tparam Varmat a `var_value` with inner Eigen type * @param x Variable with cells in range [-1, 1]. * @return Arc sine of variable, in radians. */ template <typename VarMat, require_var_matrix_t<VarMat>* = nullptr> inline auto asin(const VarMat& x) { return make_callback_var( x.val().array().asin().matrix(), [x](const auto& vi) mutable { x.adj().array() += vi.adj().array() / (1.0 - (x.val().array().square())).sqrt(); }); } /** * Return the arc sine of the complex argument. * * @param[in] z argument * @return arc sine of the argument */ inline std::complex<var> asin(const std::complex<var>& z) { return stan::math::internal::complex_asin(z); } } // namespace math } // namespace stan #endif
stan-dev/math
stan/math/rev/fun/asin.hpp
C++
bsd-3-clause
2,377
from django.contrib.gis.geoip2 import GeoIP2 from geoip2.errors import GeoIP2Error from ipware import get_client_ip def get_location_from_ip(request): client_ip, is_routable = get_client_ip(request) if client_ip is not None: g = GeoIP2() try: record = g.city(client_ip) except GeoIP2Error: return None if record: city = record.get('city') or '' country = record.get('country') or '' delimeter = ', ' if city and country else '' return f'{city}{delimeter}{country}' return None
richardcornish/smsweather
emojiweather/utils/utils.py
Python
bsd-3-clause
596
function postTodo ({input, state, output, services}) { const todo = state.get(`app.todos.${input.ref}`) services.http.post('/api/todos', todo) .then(output.success) .catch(output.error) } postTodo.async = true postTodo.outputs = ['success', 'error'] export default postTodo
morepath/morepath_cerebral_todomvc
client/modules/app/actions/postTodo.js
JavaScript
bsd-3-clause
289
using Toggl.Core.Services; namespace Toggl.Droid.Services { public class AccessibilityServiceAndroid : IAccessibilityService { public void PostAnnouncement(string message) { } } }
toggl/mobileapp
Toggl.Droid/Services/AccessibilityServiceAndroid.cs
C#
bsd-3-clause
220
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Runtime.Serialization; namespace DDay.iCal { /// <summary> /// A class that represents an RFC 2445 VALARM component. /// FIXME: move GetOccurrences() logic into an AlarmEvaluator. /// </summary> #if !SILVERLIGHT [Serializable] #endif public class Alarm : CalendarComponent, IAlarm { #region Private Fields private List<AlarmOccurrence> m_Occurrences; #endregion #region Public Properties virtual public AlarmAction Action { get { return Properties.Get<AlarmAction>("ACTION"); } set { Properties.Set("ACTION", value); } } virtual public IAttachment Attachment { get { return Properties.Get<IAttachment>("ATTACH"); } set { Properties.Set("ATTACH", value); } } virtual public IList<IAttendee> Attendees { get { return Properties.GetMany<IAttendee>("ATTENDEE"); } set { Properties.Set("ATTENDEE", value); } } virtual public string Description { get { return Properties.Get<string>("DESCRIPTION"); } set { Properties.Set("DESCRIPTION", value); } } virtual public TimeSpan Duration { get { return Properties.Get<TimeSpan>("DURATION"); } set { Properties.Set("DURATION", value); } } virtual public int Repeat { get { return Properties.Get<int>("REPEAT"); } set { Properties.Set("REPEAT", value); } } virtual public string Summary { get { return Properties.Get<string>("SUMMARY"); } set { Properties.Set("SUMMARY", value); } } virtual public ITrigger Trigger { get { return Properties.Get<ITrigger>("TRIGGER"); } set { Properties.Set("TRIGGER", value); } } #endregion #region Protected Properties virtual protected List<AlarmOccurrence> Occurrences { get { return m_Occurrences; } set { m_Occurrences = value; } } #endregion #region Constructors public Alarm() { Initialize(); } void Initialize() { Name = Components.ALARM; Occurrences = new List<AlarmOccurrence>(); } #endregion #region Public Methods /// <summary> /// Gets a list of alarm occurrences for the given recurring component, <paramref name="rc"/> /// that occur between <paramref name="FromDate"/> and <paramref name="ToDate"/>. /// </summary> virtual public IList<AlarmOccurrence> GetOccurrences(IRecurringComponent rc, IDateTime FromDate, IDateTime ToDate) { Occurrences.Clear(); if (Trigger != null) { // If the trigger is relative, it can recur right along with // the recurring items, otherwise, it happens once and // only once (at a precise time). if (Trigger.IsRelative) { // Ensure that "FromDate" has already been set if (FromDate == null) FromDate = rc.Start.Copy<IDateTime>(); TimeSpan d = default(TimeSpan); foreach (Occurrence o in rc.GetOccurrences(FromDate, ToDate)) { IDateTime dt = o.Period.StartTime; if (Trigger.Related == TriggerRelation.End) { if (o.Period.EndTime != null) { dt = o.Period.EndTime; if (d == default(TimeSpan)) d = o.Period.Duration; } // Use the "last-found" duration as a reference point else if (d != default(TimeSpan)) dt = o.Period.StartTime.Add(d); else throw new ArgumentException("Alarm trigger is relative to the END of the occurrence; however, the occurence has no discernible end."); } Occurrences.Add(new AlarmOccurrence(this, dt.Add(Trigger.Duration.Value), rc)); } } else { IDateTime dt = Trigger.DateTime.Copy<IDateTime>(); dt.AssociatedObject = this; Occurrences.Add(new AlarmOccurrence(this, dt, rc)); } // If a REPEAT and DURATION value were specified, // then handle those repetitions here. AddRepeatedItems(); } return Occurrences; } /// <summary> /// Polls the <see cref="Alarm"/> component for alarms that have been triggered /// since the provided <paramref name="Start"/> date/time. If <paramref name="Start"/> /// is null, all triggered alarms will be returned. /// </summary> /// <param name="Start">The earliest date/time to poll trigerred alarms for.</param> /// <returns>A list of <see cref="AlarmOccurrence"/> objects, each containing a triggered alarm.</returns> virtual public IList<AlarmOccurrence> Poll(IDateTime Start, IDateTime End) { List<AlarmOccurrence> Results = new List<AlarmOccurrence>(); // Evaluate the alarms to determine the recurrences RecurringComponent rc = Parent as RecurringComponent; if (rc != null) { Results.AddRange(GetOccurrences(rc, Start, End)); Results.Sort(); } return Results; } #endregion #region Protected Methods /// <summary> /// Handles the repetitions that occur from the <c>REPEAT</c> and /// <c>DURATION</c> properties. Each recurrence of the alarm will /// have its own set of generated repetitions. /// </summary> virtual protected void AddRepeatedItems() { #pragma warning disable 0472 if (Repeat != null) { int len = Occurrences.Count; for (int i = 0; i < len; i++) { AlarmOccurrence ao = Occurrences[i]; IDateTime alarmTime = ao.DateTime.Copy<IDateTime>(); for (int j = 0; j < Repeat; j++) { alarmTime = alarmTime.Add(Duration); Occurrences.Add(new AlarmOccurrence(this, alarmTime.Copy<IDateTime>(), ao.Component)); } } } #pragma warning restore 0472 } #endregion #region Overrides protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } #endregion } }
nachocove/DDay-iCal-Xamarin
DDay.iCal/Components/Alarm.cs
C#
bsd-3-clause
7,597
<?php function getNewsByCategoryID($category_id) { /*criteria order by*/ $criteria = new CDbCriteria( array('order' => 'news_date DESC', 'condition' => 'category_id LIKE :criteria', 'params' => array(':criteria' => "%{$category_id}%"))); $model = SBNews::model() -> findAll($criteria); return $model; /*hitung jumlah data*/ } function getCategoryNews() { $ParentCategories = SBNewsCategory::model() -> findAll(array('order' => 'category_name ASC')); if (!empty($ParentCategories)) { $menuCategory = "<ul class=\"nav navbar-nav navbar-left\">"; foreach ($ParentCategories as $menuu) { $categoryID=getNewsByCategoryID($menuu -> category_id); if (!empty($categoryID)) { $menuCategory .= "<li>"; $menuCategory .= "<a href='" . $menuu -> url_link . "'>{$menuu->category_name}</a>"; $menuCategory .= "</li>"; } } $menuCategory .= "</ul>"; } return empty($menuCategory) ? '' : $menuCategory; } function get_menu($data, $parent = 0) { static $i = 1; $tab = str_repeat(" ", $i); if (!empty($data[$parent])) { if (empty($parent)) { $html = "$tab<ul class=\"nav navbar-nav navbar-left\">"; } else { $html = "$tab<ul class=\"nav navbar-nav navbar-left\">"; } $i++; $number = 1; foreach ($data[$parent] as $menu) { $home_icon = $menu->positions == 0 ? '<i class="fa fa-home"></i>' : ''; $link = $menu -> link; $css = ''; if ($menu -> link == Website::catchFullUrl()) { $css = 'active'; } $blog = ""; if ($menu -> action == 'link-to-module' && $menu -> module == 'blog') { $blog = getCategoryNews(); } $child = get_menu($data, $menu -> menu_id); $html .= "$tab<li class=\"parent {$css}\">"; $products = ""; $html .= "<a href='{$link}' target='{$menu -> target}'>{$home_icon} {$menu -> menu_name} </a>{$blog}"; if ($child) { $i--; $html .= $child; $html .= "$tab"; } $html .= '</li>'; $number++; } $html .= "$tab</ul>"; return $html; } else { return false; } } $MENU = SBMenu::model() -> findAll(array('order' => 'positions ASC')); foreach ($MENU as $menu) { $data[$menu -> parent_id][] = $menu; } echo get_menu($data); ?>
akaidrive2014/persseleb
protected/views/layouts/top-menu.php
PHP
bsd-3-clause
2,150
# BinGrep, version 1.0.0 # Copyright 2017 Hiroki Hada # coding:UTF-8 import sys, os, time, argparse import re import pprint #import pydot import math import cPickle import ged_node from idautils import * from idc import * import idaapi def idascript_exit(code=0): idc.Exit(code) def get_short_function_name(function): return function.replace("?", "")[:100] def mkdir(dirname): if not os.path.exists(dirname): os.mkdir(dirname) def cPickle_dump(filename, data): with open(filename, "wb") as f: cPickle.dump(data, f) def print_cfg(cfg): for block in cfg: print "[%02d]" % block.id, print hex(block.startEA), succs = list(block.succs()) print "(succs(%d): " % len(succs), for i in range(len(succs)): sys.stdout.write(hex(succs[i].startEA)) if i < len(succs) - 1: sys.stdout.write(", ") print ")" def output_cfg_as_png_rec(g, block, memo): functions1, dummy = get_marks(block, 0) hashed_label1 = hash_label(functions1) label1 = hex(block.startEA) + ("\n%08x" % hashed_label1) g.add_node(pydot.Node(label1, fontcolor='#FFFFFF', color='#333399')) for b in list(block.succs()): functions2, dummy = get_marks(b, 0) hashed_label2 = hash_label(functions2) label2 = hex(b.startEA) + ("\n%08x" % hashed_label2) if b.startEA not in memo: memo.append(b.startEA) g.add_edge(pydot.Edge(label1, label2, color='#333399', style='bold')) output_cfg_as_png_rec(g, b, memo) else: g.add_edge(pydot.Edge(label1, label2, color='#333399', style='bold, dotted')) def output_cfg_as_png(cfg, filename, overwrite_flag): blocks_src = {} blocks_dst = {} block = cfg[0] f_name = GetFunctionName(block.startEA) if not overwrite_flag and os.path.exists(filename): return g = pydot.Dot(graph_type='digraph', bgcolor="#F0E0FF") size = "21" g.set_rankdir('TB') g.set_size(size) g.add_node(pydot.Node('node', shape='ellipse', margin='0.05', fontcolor='#FFFFFF', fontsize=size, color='#333399', style='filled', fontname='Consolas Bold')) g.add_node(pydot.Node('edge', color='lightgrey')) memo = [] output_cfg_as_png_rec(g, block, memo) g.write_png(filename) def get_cfg(function_start, function_end): f_name = GetFunctionName(function_start) cfg = idaapi.FlowChart(idaapi.get_func(function_start)) return list(cfg) def get_cfgs(): cfgs = [] for ea in Segments(): functions = list(Functions(SegStart(ea), SegEnd(ea))) functions.append(SegEnd(ea)) for i in range(len(functions) - 1): function_start = functions[i] function_end = functions[i+1] cfg = get_cfg(function_start, function_end) cfgs.append(cfg) return cfgs def hash_label(marks): tmp = sorted(set(marks)) tmp = "".join(tmp) tmp = tmp.upper() def rot13(string): return reduce(lambda h,c: ((h>>13 | h<<19)+ord(c)) & 0xFFFFFFFF, [0]+list(string)) hashed_label = rot13(tmp) hashed_label = hashed_label & 0xFFFFFFFF return hashed_label def get_marks(block, gamma): marks = [] for head in Heads(block.startEA, block.endEA): mnem = GetMnem(head) opnd = (GetOpnd(head, 0), GetOpnd(head, 1), GetOpnd(head, 2)) if mnem not in ["call"]: for buf in (opnd[1], opnd[2]): if buf: match = re.search("([\dA-F]+)h", buf) if match: magic = int(match.group(1), 16) if 0x00001000 <= magic <= 0xffffffff: marks.append(hex(magic)) for buf in (opnd[0], opnd[1], opnd[2]): if buf: match = re.search("offset (a[\S]+)", buf) if match: offset_a = match.group(1) if offset_a[:4] == "asc_": continue marks.append(offset_a) continue else: gamma += 1 if opnd[0][:4] == "sub_": continue if opnd[0][0] in ["?", "$"]: continue if opnd[0] in ["eax", "ebx", "ecx", "edx", "esi", "edi"]: continue if opnd[0] in ["__SEH_prolog4", "__SEH_epilog4", "__EH_prolog3_catch"]: continue if opnd[0].find("cookie") >= 0: continue marks.append(opnd[0]) continue return marks, gamma def get_mnems(block): mnems = [] for head in Heads(block.startEA, block.endEA): mnem = GetMnem(head) opnd = (GetOpnd(head, 0), GetOpnd(head, 1), GetOpnd(head, 2)) buf = " " for o in opnd: if not o: break elif o in ["eax", "ebx", "ecx", "edx", "ax", "bx", "cx", "dx", "al", "bl", "cl", "dl", "ah", "bh", "ch", "dh", "esi", "edi", "si", "di", "esp", "ebp"]: buf += "reg " elif o[:3] == "xmm": buf += "reg " elif o.find("[") >= 0: buf += "mem " elif o[:6] == "offset": buf += "off " elif o[:4] == "loc_": buf += "loc " elif o[:4] == "sub_": buf += "sub " elif o.isdigit(): buf += "num " elif re.match("[\da-fA-F]+h", o): buf += "num " elif o[:6] == "dword_": buf += "dwd " else: buf += "lbl " mnems.append(mnem + buf) return mnems def cfg_to_cft_rec(block, memo, abr): (alpha, beta, gamma) = abr alpha += 1 marks, gamma = get_marks(block, gamma) hashed_label = hash_label(marks) mnems = get_mnems(block) tree = ged_node.Node(hashed_label) for b in list(block.succs()): beta += 1 if b.startEA not in memo: memo.append(b.startEA) tmp, (alpha, beta, gamma), tmp2 = cfg_to_cft_rec(b, memo, (alpha, beta, gamma)) tree = tree.addkid(tmp) mnems += tmp2 return tree, (alpha, beta, gamma), mnems def cfg_to_cft(cfg): block = cfg[0] memo = [] memo.append(block.startEA) return cfg_to_cft_rec(block, memo, (0, 0, 0)) def dump_function_info(cfgs, program, function, f_image, f_all, f_overwrite): function_num = len(cfgs) dump_data_list = {} for cfg in cfgs: function_name = GetFunctionName(cfg[0].startEA) (cft, abr, mnems) = cfg_to_cft(cfg) dump_data_list[function_name] = {} dump_data_list[function_name]["FUNCTION_NAME"] = function_name dump_data_list[function_name]["CFT"] = cft dump_data_list[function_name]["ABR"] = abr dump_data_list[function_name]["MNEMS"] = mnems def dump_pickle(dump_data_list, program, function, f_overwrite): function_name_short = get_short_function_name(function) filename_pickle = os.path.join(function_name_short + ".pickle") if f_overwrite or not os.path.exists(filename_pickle): cPickle_dump(filename_pickle, dump_data_list[function]) cPickle_dump(program + ".dmp", dump_data_list) def main(function, f_image, f_all, f_overwrite): sys.setrecursionlimit(3000) program = idaapi.get_root_filename() start_time = time.time() cfgs = get_cfgs() dump_function_info(cfgs, program, function, f_image, f_all, f_overwrite) result_time = time.time() - start_time print "Dump finished." print "result_time: " + str(result_time) + " sec." if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description="") parser.add_argument('-f', dest='function', default=None, type=str, help='') parser.add_argument('-a', dest='f_all', default=False, action='store_true', help='') parser.add_argument('-i', dest='f_image', default=False, action='store_true', help='Image Flag (Output as PNG)') parser.add_argument('-o', dest='f_overwrite', default=False, action='store_true', help='Overwrite file') args = parser.parse_args() function = args.function f_image = args.f_image f_all = args.f_all f_overwrite = args.f_overwrite main(function, f_image, f_all, f_overwrite) #idascript_exit()
hada2/bingrep
bingrep_dump.py
Python
bsd-3-clause
8,471
/* * This file is part of RHexLib, * * Copyright (c) 2001 The University of Michigan, its Regents, * Fellows, Employees and Agents. All rights reserved, and distributed as * free software under the following license. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions, the following disclaimer and the * file called "CREDITS" which accompanies this distribution. * * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, the following disclaimer and the file * called "CREDITS" which accompanies this distribution in the * documentation and/or other materials provided with the distribution. * * 3) Neither the name of the University of Michigan, Ann Arbor or the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /********************************************************************* * $Id: enc_test.cc,v 1.2 2001/07/12 17:14:10 ulucs Exp $ * * Example program to test the low level EncoderHW interface * * Created : Uluc Saranli, 10/16/2000 * Last Modified : Uluc Saranli, 06/27/2001 * ********************************************************************/ // ========================================================================== // This program tests the encoder interfaces in RHexLib. On execution, // the program continuously prints the encoder reads for all 6 // axex. The following keyboard commands are implemented: // // 'r' : reset all encoders // 'd' : Disable all encoders // 'e' : Enable all encoders // // All other keys exit the program // // Note: This example does not function with the virtual hardware // because the virtual hardware requires the module manager to be // active to function. // // ========================================================================== #include <stdio.h> #include "sysutil.hh" // If we are running QNX, determine which Hardware we should use. // Note that the RHEX_HARDWARE environment variable determines this. #ifdef _QNX4_ #ifdef _MICHIGAN_ #include "MichiganHW.hh" MichiganHW hw; #endif #ifdef _MCGILL_ #include "McGillHW.hh" McGillHW hw; #endif #endif // #ifdef _QNX4_ #ifdef _LINUX_ #include "SimSectHW.hh" SimSectHW hw; #endif int main( void ) { int axis; int done = 0; int inp; // This is necessary in the abscence of a call to MMChooseHardware() hw.initialize(); // Enable all 6 encoders for ( axis = 0; axis < 6; axis++ ) hw.encoders->enable( axis ); // Loop until user interrupt while ( !done ) { // Read and print all the encoder values printf( " Encoders: 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x\n", hw.encoders->read( 0 ), hw.encoders->read( 1 ), hw.encoders->read( 2 ), hw.encoders->read( 3 ), hw.encoders->read( 4 ), hw.encoders->read( 5 ) ); // Check for user input if ( kbhit() ) { inp = getch(); switch ( inp ) { case 'r': // Reset all encoders for ( axis = 0; axis < 6; axis++ ) hw.encoders->reset( axis ); break; case 'd': // Disable all encoders for ( axis = 0; axis < 6; axis++ ) hw.encoders->disable( axis ); break; case 'e': // Enable all encoders for ( axis = 0; axis < 6; axis++ ) hw.encoders->enable( axis ); break; default: // Exit on any other keystroke done = 1; } } } for ( axis = 0; axis < 6; axis++ ) hw.encoders->disable( axis ); // This is necessary in the abscence of a call to MMChooseHardware() hw.cleanup(); return 0; }
kiik/RHexLib
examples/enc_test.cc
C++
bsd-3-clause
4,666
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jme3.input.vr.oculus; import com.jme3.app.VREnvironment; import com.jme3.input.vr.HmdType; import com.jme3.input.vr.VRAPI; import com.jme3.math.*; import com.jme3.renderer.Camera; import com.jme3.texture.*; import org.lwjgl.*; import org.lwjgl.ovr.*; import java.nio.IntBuffer; import java.util.logging.Logger; import static org.lwjgl.BufferUtils.createPointerBuffer; import static org.lwjgl.ovr.OVR.*; import static org.lwjgl.ovr.OVRErrorCode.ovrSuccess; import static org.lwjgl.ovr.OVRUtil.ovr_Detect; import static org.lwjgl.system.MemoryUtil.*; /** * Oculus VR (LibOVR 1.3.0) Native support. * <p> * A few notes about the Oculus coordinate system: * <ul> * <li>Matrices should be transposed</li> * <li>Quaternions should be inverted<li/> * <li>Vectors should have their X and Z axes flipped, but apparently not Y.</li> * </ul> * * @author Campbell Suter (znix@znix.xyz) */ public class OculusVR implements VRAPI { private static final Logger LOGGER = Logger.getLogger(OculusVR.class.getName()); private final VREnvironment environment; private boolean initialized; /** * Pointer to the HMD object */ private long session; /** * Information about the VR session (should the app quit, is * it visible or is the universal menu open, etc) */ private OVRSessionStatus sessionStatus; /** * HMD information, such as product name and manufacturer. */ private OVRHmdDesc hmdDesc; /** * The horizontal resolution of the HMD */ private int resolutionW; /** * The vertical resolution of the HMD */ private int resolutionH; /** * Field-of-view data for each eye (how many degrees from the * center can the user see). */ private final OVRFovPort fovPorts[] = new OVRFovPort[2]; /** * Data about each eye to be rendered - in particular, the * offset from the center of the HMD to the eye. */ private final OVREyeRenderDesc eyeRenderDesc[] = new OVREyeRenderDesc[2]; /** * Store the projections for each eye, so we don't have to malloc * and recalculate them each frame. */ private final OVRMatrix4f[] projections = new OVRMatrix4f[2]; /** * Store the poses for each eye, relative to the HMD. * * @see #getHMDMatrixPoseLeftEye() */ private final Matrix4f[] hmdRelativeEyePoses = new Matrix4f[2]; /** * Store the positions for each eye, relative to the HMD. * * @see #getHMDVectorPoseLeftEye() */ private final Vector3f[] hmdRelativeEyePositions = new Vector3f[2]; /** * The current state of the tracked components (HMD, touch) */ private OVRTrackingState trackingState; /** * The position and orientation of the user's head. */ private OVRPosef headPose; /** * The state of the Touch controllers. */ private OculusVRInput input; // The size of the texture drawn onto the HMD private int textureW; private int textureH; // Layers to render into private PointerBuffer layers; private OVRLayerEyeFov layer0; /** * Chain texture set thing. */ private long chains[]; /** * Frame buffers we can draw into. */ private FrameBuffer framebuffers[][]; public OculusVR(VREnvironment environment) { this.environment = environment; } @Override public OculusVRInput getVRinput() { return input; } @Override public String getName() { return "OVR"; } @Override public int getDisplayFrequency() { // TODO find correct frequency. I'm not sure // if LibOVR has a way to do that, though. return 60; } @Override public boolean initialize() { // Check to make sure the HMD is connected OVRDetectResult detect = OVRDetectResult.calloc(); ovr_Detect(0, detect); boolean connected = detect.IsOculusHMDConnected(); LOGGER.config("OVRDetectResult.IsOculusHMDConnected = " + connected); LOGGER.config("OVRDetectResult.IsOculusServiceRunning = " + detect.IsOculusServiceRunning()); detect.free(); if (!connected) { LOGGER.info("Oculus Rift not connected"); return false; } initialized = true; // Set up the HMD OVRLogCallback callback = new OVRLogCallback() { @Override public void invoke(long userData, int level, long message) { LOGGER.fine("LibOVR [" + userData + "] [" + level + "] " + memASCII(message)); } }; OVRInitParams initParams = OVRInitParams.calloc(); initParams.LogCallback(callback); if (ovr_Initialize(initParams) != ovrSuccess) { LOGGER.severe("LibOVR Init Failed"); return false; // TODO fix memory leak - destroy() is not called } LOGGER.config("LibOVR Version " + ovr_GetVersionString()); initParams.free(); // Get access to the HMD LOGGER.info("Initialize HMD Session"); PointerBuffer pHmd = memAllocPointer(1); OVRGraphicsLuid luid = OVRGraphicsLuid.calloc(); if (ovr_Create(pHmd, luid) != ovrSuccess) { LOGGER.severe("Failed to create HMD"); return false; // TODO fix memory leak - destroy() is not called } session = pHmd.get(0); memFree(pHmd); luid.free(); sessionStatus = OVRSessionStatus.calloc(); // Get the information about the HMD LOGGER.fine("Get HMD properties"); hmdDesc = OVRHmdDesc.malloc(); ovr_GetHmdDesc(session, hmdDesc); if (hmdDesc.Type() == ovrHmd_None) { LOGGER.warning("No HMD connected"); return false; // TODO fix memory leak - destroy() is not called } resolutionW = hmdDesc.Resolution().w(); resolutionH = hmdDesc.Resolution().h(); LOGGER.config("HMD Properties: " + "\t Manufacturer: " + hmdDesc.ManufacturerString() + "\t Product: " + hmdDesc.ProductNameString() + "\t Serial: <hidden>" // + hmdDesc.SerialNumberString() // Hidden for privacy reasons + "\t Type: " + hmdDesc.Type() + "\t Resolution (total): " + resolutionW + "," + resolutionH); if (resolutionW == 0) { LOGGER.severe("HMD witdth=0 : aborting"); return false; // TODO fix memory leak - destroy() is not called } // Find the FOV for each eye for (int eye = 0; eye < 2; eye++) { fovPorts[eye] = hmdDesc.DefaultEyeFov(eye); } // Get the pose for each eye, and cache it for later. for (int eye = 0; eye < 2; eye++) { // Create the projection objects projections[eye] = OVRMatrix4f.malloc(); hmdRelativeEyePoses[eye] = new Matrix4f(); hmdRelativeEyePositions[eye] = new Vector3f(); // Find the eye render information - we use this in the // view manager for giving LibOVR its timewarp information. eyeRenderDesc[eye] = OVREyeRenderDesc.malloc(); ovr_GetRenderDesc(session, eye, fovPorts[eye], eyeRenderDesc[eye]); // Get the pose of the eye OVRPosef pose = eyeRenderDesc[eye].HmdToEyePose(); // Get the position and rotation of the eye vecO2J(pose.Position(), hmdRelativeEyePositions[eye]); Quaternion rotation = quatO2J(pose.Orientation(), new Quaternion()); // Put it into a matrix for the get eye pose functions hmdRelativeEyePoses[eye].loadIdentity(); hmdRelativeEyePoses[eye].setTranslation(hmdRelativeEyePositions[eye]); hmdRelativeEyePoses[eye].setRotationQuaternion(rotation); } // Recenter the HMD. The game itself should do this too, but just in case / before they do. reset(); // Do this so others relying on our texture size (the GUI in particular) get it correct. findHMDTextureSize(); // Allocate the memory for the tracking state - we actually // set it up later, but Input uses it so calloc it now. trackingState = OVRTrackingState.calloc(); // Set up the input input = new OculusVRInput(this, session, sessionStatus, trackingState); // TODO find some way to get in ovrTrackingOrigin_FloorLevel // throw new UnsupportedOperationException("Not yet implemented!"); return true; } @Override public void updatePose() { double ftiming = ovr_GetPredictedDisplayTime(session, 0); ovr_GetTrackingState(session, ftiming, true, trackingState); ovr_GetSessionStatus(session, sessionStatus); input.updateControllerStates(); headPose = trackingState.HeadPose().ThePose(); } @Override public boolean isInitialized() { return initialized; } @Override public void destroy() { // fovPorts: contents are managed by LibOVR, no need to do anything. // Clean up the input input.dispose(); // Check if we've set up rendering - if so, clean that up. if (chains != null) { // Destroy our set of huge buffer images. for (long chain : chains) { ovr_DestroyTextureSwapChain(session, chain); } // Free up the layer layer0.free(); // The layers array apparently takes care of itself (and crashes if we try to free it) } for (OVREyeRenderDesc eye : eyeRenderDesc) { eye.free(); } for (OVRMatrix4f projection : projections) { projection.free(); } hmdDesc.free(); trackingState.free(); sessionStatus.free(); // Wrap everything up ovr_Destroy(session); ovr_Shutdown(); } @Override public void reset() { // Reset the coordinate system - where the user's head is now is facing forwards from [0,0,0] ovr_RecenterTrackingOrigin(session); } @Override public void getRenderSize(Vector2f store) { if (!isInitialized()) { throw new IllegalStateException("Cannot call getRenderSize() before initialized!"); } store.x = textureW; store.y = textureH; } @Override public float getInterpupillaryDistance() { return 0.065f; // TODO } @Override public Quaternion getOrientation() { return quatO2J(headPose.Orientation(), new Quaternion()); } @Override public Vector3f getPosition() { return vecO2J(headPose.Position(), new Vector3f()); } @Override public void getPositionAndOrientation(Vector3f storePos, Quaternion storeRot) { storePos.set(getPosition()); storeRot.set(getOrientation()); } private Matrix4f calculateProjection(int eye, Camera cam) { Matrix4f mat = new Matrix4f(); // Get LibOVR to find the correct projection OVRUtil.ovrMatrix4f_Projection(fovPorts[eye], cam.getFrustumNear(), cam.getFrustumFar(), OVRUtil.ovrProjection_None, projections[eye]); matrixO2J(projections[eye], mat); return mat; } @Override public Matrix4f getHMDMatrixProjectionLeftEye(Camera cam) { return calculateProjection(ovrEye_Left, cam); } @Override public Matrix4f getHMDMatrixProjectionRightEye(Camera cam) { return calculateProjection(ovrEye_Right, cam); } @Override public Vector3f getHMDVectorPoseLeftEye() { return hmdRelativeEyePositions[ovrEye_Left]; } @Override public Vector3f getHMDVectorPoseRightEye() { return hmdRelativeEyePositions[ovrEye_Right]; } @Override public Vector3f getSeatedToAbsolutePosition() { throw new UnsupportedOperationException(); } @Override public Matrix4f getHMDMatrixPoseLeftEye() { return hmdRelativeEyePoses[ovrEye_Left]; } @Override public Matrix4f getHMDMatrixPoseRightEye() { return hmdRelativeEyePoses[ovrEye_Left]; } @Override public HmdType getType() { return HmdType.OCULUS_RIFT; } @Override public boolean initVRCompositor(boolean set) { if (!set) { throw new UnsupportedOperationException("Cannot use LibOVR without compositor!"); } setupLayers(); framebuffers = new FrameBuffer[2][]; for (int eye = 0; eye < 2; eye++) setupFramebuffers(eye); // TODO move initialization code here from VRViewManagerOculus return true; } @Override public void printLatencyInfoToConsole(boolean set) { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public void setFlipEyes(boolean set) { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public Void getCompositor() { throw new UnsupportedOperationException("Not yet implemented!"); } @Override public Void getVRSystem() { throw new UnsupportedOperationException("Not yet implemented!"); } // Rendering-type stuff public void findHMDTextureSize() { // Texture sizes float pixelScaling = 1.0f; // pixelsPerDisplayPixel OVRSizei leftTextureSize = OVRSizei.malloc(); ovr_GetFovTextureSize(session, ovrEye_Left, fovPorts[ovrEye_Left], pixelScaling, leftTextureSize); OVRSizei rightTextureSize = OVRSizei.malloc(); ovr_GetFovTextureSize(session, ovrEye_Right, fovPorts[ovrEye_Right], pixelScaling, rightTextureSize); if (leftTextureSize.w() != rightTextureSize.w()) { throw new IllegalStateException("Texture sizes do not match [horizontal]"); } if (leftTextureSize.h() != rightTextureSize.h()) { throw new IllegalStateException("Texture sizes do not match [vertical]"); } textureW = leftTextureSize.w(); textureH = leftTextureSize.h(); leftTextureSize.free(); rightTextureSize.free(); } private long setupTextureChain() { // Set up the information for the texture buffer chain thing OVRTextureSwapChainDesc swapChainDesc = OVRTextureSwapChainDesc.calloc() .Type(ovrTexture_2D) .ArraySize(1) .Format(OVR_FORMAT_R8G8B8A8_UNORM_SRGB) .Width(textureW) .Height(textureH) .MipLevels(1) .SampleCount(1) .StaticImage(false); // ovrFalse // Create the chain PointerBuffer textureSetPB = createPointerBuffer(1); if (OVRGL.ovr_CreateTextureSwapChainGL(session, swapChainDesc, textureSetPB) != ovrSuccess) { throw new RuntimeException("Failed to create Swap Texture Set"); } swapChainDesc.free(); return textureSetPB.get(); // TODO is this a memory leak? } public void setupLayers() { //Layers layer0 = OVRLayerEyeFov.calloc(); layer0.Header().Type(ovrLayerType_EyeFov); layer0.Header().Flags(ovrLayerFlag_TextureOriginAtBottomLeft); chains = new long[2]; for (int eye = 0; eye < 2; eye++) { long eyeChain = setupTextureChain(); chains[eye] = eyeChain; OVRRecti viewport = OVRRecti.calloc(); viewport.Pos().x(0); viewport.Pos().y(0); viewport.Size().w(textureW); viewport.Size().h(textureH); layer0.ColorTexture(eye, eyeChain); layer0.Viewport(eye, viewport); layer0.Fov(eye, fovPorts[eye]); viewport.free(); // we update pose only when we have it in the render loop } layers = createPointerBuffer(1); layers.put(0, layer0); } /** * Create a framebuffer for an eye. */ public void setupFramebuffers(int eye) { // Find the chain length IntBuffer length = BufferUtils.createIntBuffer(1); ovr_GetTextureSwapChainLength(session, chains[eye], length); int chainLength = length.get(); LOGGER.fine("HMD Eye #" + eye + " texture chain length: " + chainLength); // Create the frame buffers framebuffers[eye] = new FrameBuffer[chainLength]; for (int i = 0; i < chainLength; i++) { // find the GL texture ID for this texture IntBuffer textureIdB = BufferUtils.createIntBuffer(1); OVRGL.ovr_GetTextureSwapChainBufferGL(session, chains[eye], i, textureIdB); int textureId = textureIdB.get(); // TODO less hacky way of getting our texture into JMonkeyEngine Image img = new Image(); img.setId(textureId); img.setFormat(Image.Format.RGBA8); img.setWidth(textureW); img.setHeight(textureH); Texture2D tex = new Texture2D(img); FrameBuffer buffer = new FrameBuffer(textureW, textureH, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorTexture(tex); framebuffers[eye][i] = buffer; } } // UTILITIES // TODO move to helper class /** * Copy the values from a LibOVR matrix into a jMonkeyEngine matrix. * * @param from The matrix to copy from. * @param to The matrix to copy to. * @return The {@code to} argument. */ public static Matrix4f matrixO2J(OVRMatrix4f from, Matrix4f to) { to.loadIdentity(); // For the additional columns (unless I'm badly misunderstanding matricies) for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { float val = from.M(x + y * 4); // TODO verify this to.set(x, y, val); } } to.transposeLocal(); // jME vs LibOVR coordinate spaces - Yay! return to; } /** * Copy the values from a LibOVR quaternion into a jMonkeyEngine quaternion. * * @param from The quaternion to copy from. * @param to The quaternion to copy to. * @return The {@code to} argument. */ public static Quaternion quatO2J(OVRQuatf from, Quaternion to) { // jME and LibOVR do their coordinate spaces differently for rotations, so flip Y and W (thanks, jMonkeyVR). to.set( from.x(), -from.y(), from.z(), -from.w() ); to.normalizeLocal(); return to; } /** * Copy the values from a LibOVR vector into a jMonkeyEngine vector. * * @param from The vector to copy from. * @param to The vector to copy to. * @return The {@code to} argument. */ public static Vector3f vecO2J(OVRVector3f from, Vector3f to) { // jME and LibOVR disagree on which way X and Z are, too. to.set( -from.x(), from.y(), -from.z() ); return to; } // Getters, intended for VRViewManager. public long getSessionPointer() { return session; } public long getChain(int eye) { return chains[eye]; } public FrameBuffer[] getFramebuffers(int eye) { return framebuffers[eye]; } public PointerBuffer getLayers() { return layers; } public OVRLayerEyeFov getLayer0() { return layer0; } public OVRFovPort getFovPort() { return fovPorts[ovrEye_Left]; // TODO checking the left and right eyes match } public OVRPosef getHeadPose() { return headPose; } public OVRPosef getEyePose(int eye) { return eyeRenderDesc[eye].HmdToEyePose(); } public VREnvironment getEnvironment() { return environment; } } /* vim: set ts=4 softtabstop=0 sw=4 expandtab: */
zzuegg/jmonkeyengine
jme3-vr/src/main/java/com/jme3/input/vr/oculus/OculusVR.java
Java
bsd-3-clause
20,261
/* Copyright (C) 2008-2015, Bit Miracle * http://www.bitmiracle.com * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * */ using System; using System.Collections.Generic; using System.Text; namespace BitMiracle.LibJpeg.Classic.Internal { /// <summary> /// Master control module /// </summary> class jpeg_comp_master { private enum c_pass_type { main_pass, /* input data, also do first output step */ huff_opt_pass, /* Huffman code optimization pass */ output_pass /* data output pass */ } private jpeg_compress_struct m_cinfo; private bool m_call_pass_startup; /* True if pass_startup must be called */ private bool m_is_last_pass; /* True during last pass */ private c_pass_type m_pass_type; /* the type of the current pass */ private int m_pass_number; /* # of passes completed */ private int m_total_passes; /* total # of passes needed */ private int m_scan_number; /* current index in scan_info[] */ public jpeg_comp_master(jpeg_compress_struct cinfo, bool transcode_only) { m_cinfo = cinfo; if (transcode_only) { /* no main pass in transcoding */ if (cinfo.m_optimize_coding) m_pass_type = c_pass_type.huff_opt_pass; else m_pass_type = c_pass_type.output_pass; } else { /* for normal compression, first pass is always this type: */ m_pass_type = c_pass_type.main_pass; } if (cinfo.m_optimize_coding) m_total_passes = cinfo.m_num_scans * 2; else m_total_passes = cinfo.m_num_scans; } /// <summary> /// Per-pass setup. /// /// This is called at the beginning of each pass. We determine which /// modules will be active during this pass and give them appropriate /// start_pass calls. /// We also set is_last_pass to indicate whether any more passes will /// be required. /// </summary> public void prepare_for_pass() { switch (m_pass_type) { case c_pass_type.main_pass: prepare_for_main_pass(); break; case c_pass_type.huff_opt_pass: if (!prepare_for_huff_opt_pass()) break; prepare_for_output_pass(); break; case c_pass_type.output_pass: prepare_for_output_pass(); break; default: m_cinfo.ERREXIT(J_MESSAGE_CODE.JERR_NOT_COMPILED); break; } m_is_last_pass = (m_pass_number == m_total_passes - 1); /* Set up progress monitor's pass info if present */ if (m_cinfo.m_progress != null) { m_cinfo.m_progress.Completed_passes = m_pass_number; m_cinfo.m_progress.Total_passes = m_total_passes; } } /// <summary> /// Special start-of-pass hook. /// /// This is called by jpeg_write_scanlines if call_pass_startup is true. /// In single-pass processing, we need this hook because we don't want to /// write frame/scan headers during jpeg_start_compress; we want to let the /// application write COM markers etc. between jpeg_start_compress and the /// jpeg_write_scanlines loop. /// In multi-pass processing, this routine is not used. /// </summary> public void pass_startup() { m_cinfo.m_master.m_call_pass_startup = false; /* reset flag so call only once */ m_cinfo.m_marker.write_frame_header(); m_cinfo.m_marker.write_scan_header(); } /// <summary> /// Finish up at end of pass. /// </summary> public void finish_pass() { /* The entropy coder always needs an end-of-pass call, * either to analyze statistics or to flush its output buffer. */ m_cinfo.m_entropy.finish_pass(); /* Update state for next pass */ switch (m_pass_type) { case c_pass_type.main_pass: /* next pass is either output of scan 0 (after optimization) * or output of scan 1 (if no optimization). */ m_pass_type = c_pass_type.output_pass; if (!m_cinfo.m_optimize_coding) m_scan_number++; break; case c_pass_type.huff_opt_pass: /* next pass is always output of current scan */ m_pass_type = c_pass_type.output_pass; break; case c_pass_type.output_pass: /* next pass is either optimization or output of next scan */ if (m_cinfo.m_optimize_coding) m_pass_type = c_pass_type.huff_opt_pass; m_scan_number++; break; } m_pass_number++; } public bool IsLastPass() { return m_is_last_pass; } public bool MustCallPassStartup() { return m_call_pass_startup; } private void prepare_for_main_pass() { /* Initial pass: will collect input data, and do either Huffman * optimization or data output for the first scan. */ select_scan_parameters(); per_scan_setup(); if (!m_cinfo.m_raw_data_in) { m_cinfo.m_cconvert.start_pass(); m_cinfo.m_prep.start_pass(J_BUF_MODE.JBUF_PASS_THRU); } m_cinfo.m_fdct.start_pass(); m_cinfo.m_entropy.start_pass(m_cinfo.m_optimize_coding); m_cinfo.m_coef.start_pass((m_total_passes > 1 ? J_BUF_MODE.JBUF_SAVE_AND_PASS : J_BUF_MODE.JBUF_PASS_THRU)); m_cinfo.m_main.start_pass(J_BUF_MODE.JBUF_PASS_THRU); if (m_cinfo.m_optimize_coding) { /* No immediate data output; postpone writing frame/scan headers */ m_call_pass_startup = false; } else { /* Will write frame/scan headers at first jpeg_write_scanlines call */ m_call_pass_startup = true; } } private bool prepare_for_huff_opt_pass() { /* Do Huffman optimization for a scan after the first one. */ select_scan_parameters(); per_scan_setup(); if (m_cinfo.m_Ss != 0 || m_cinfo.m_Ah == 0) { m_cinfo.m_entropy.start_pass(true); m_cinfo.m_coef.start_pass(J_BUF_MODE.JBUF_CRANK_DEST); m_call_pass_startup = false; return false; } /* Special case: Huffman DC refinement scans need no Huffman table * and therefore we can skip the optimization pass for them. */ m_pass_type = c_pass_type.output_pass; m_pass_number++; return true; } private void prepare_for_output_pass() { /* Do a data-output pass. */ /* We need not repeat per-scan setup if prior optimization pass did it. */ if (!m_cinfo.m_optimize_coding) { select_scan_parameters(); per_scan_setup(); } m_cinfo.m_entropy.start_pass(false); m_cinfo.m_coef.start_pass(J_BUF_MODE.JBUF_CRANK_DEST); /* We emit frame/scan headers now */ if (m_scan_number == 0) m_cinfo.m_marker.write_frame_header(); m_cinfo.m_marker.write_scan_header(); m_call_pass_startup = false; } // Set up the scan parameters for the current scan private void select_scan_parameters() { if (m_cinfo.m_scan_info != null) { /* Prepare for current scan --- the script is already validated */ jpeg_scan_info scanInfo = m_cinfo.m_scan_info[m_scan_number]; m_cinfo.m_comps_in_scan = scanInfo.comps_in_scan; for (int ci = 0; ci < scanInfo.comps_in_scan; ci++) m_cinfo.m_cur_comp_info[ci] = scanInfo.component_index[ci]; m_cinfo.m_Ss = scanInfo.Ss; m_cinfo.m_Se = scanInfo.Se; m_cinfo.m_Ah = scanInfo.Ah; m_cinfo.m_Al = scanInfo.Al; } else { /* Prepare for single sequential-JPEG scan containing all components */ if (m_cinfo.m_num_components > JpegConstants.MAX_COMPS_IN_SCAN) m_cinfo.ERREXIT(J_MESSAGE_CODE.JERR_COMPONENT_COUNT, m_cinfo.m_num_components, JpegConstants.MAX_COMPS_IN_SCAN); m_cinfo.m_comps_in_scan = m_cinfo.m_num_components; for (int ci = 0; ci < m_cinfo.m_num_components; ci++) m_cinfo.m_cur_comp_info[ci] = ci; m_cinfo.m_Ss = 0; m_cinfo.m_Se = JpegConstants.DCTSIZE2 - 1; m_cinfo.m_Ah = 0; m_cinfo.m_Al = 0; } } /// <summary> /// Do computations that are needed before processing a JPEG scan /// cinfo.comps_in_scan and cinfo.cur_comp_info[] are already set /// </summary> private void per_scan_setup() { if (m_cinfo.m_comps_in_scan == 1) { /* Noninterleaved (single-component) scan */ int compIndex = m_cinfo.m_cur_comp_info[0]; /* Overall image size in MCUs */ m_cinfo.m_MCUs_per_row = m_cinfo.Component_info[compIndex].Width_in_blocks; m_cinfo.m_MCU_rows_in_scan = m_cinfo.Component_info[compIndex].height_in_blocks; /* For noninterleaved scan, always one block per MCU */ m_cinfo.Component_info[compIndex].MCU_width = 1; m_cinfo.Component_info[compIndex].MCU_height = 1; m_cinfo.Component_info[compIndex].MCU_blocks = 1; m_cinfo.Component_info[compIndex].MCU_sample_width = JpegConstants.DCTSIZE; m_cinfo.Component_info[compIndex].last_col_width = 1; /* For noninterleaved scans, it is convenient to define last_row_height * as the number of block rows present in the last iMCU row. */ int tmp = m_cinfo.Component_info[compIndex].height_in_blocks % m_cinfo.Component_info[compIndex].V_samp_factor; if (tmp == 0) tmp = m_cinfo.Component_info[compIndex].V_samp_factor; m_cinfo.Component_info[compIndex].last_row_height = tmp; /* Prepare array describing MCU composition */ m_cinfo.m_blocks_in_MCU = 1; m_cinfo.m_MCU_membership[0] = 0; } else { /* Interleaved (multi-component) scan */ if (m_cinfo.m_comps_in_scan <= 0 || m_cinfo.m_comps_in_scan > JpegConstants.MAX_COMPS_IN_SCAN) m_cinfo.ERREXIT(J_MESSAGE_CODE.JERR_COMPONENT_COUNT, m_cinfo.m_comps_in_scan, JpegConstants.MAX_COMPS_IN_SCAN); /* Overall image size in MCUs */ m_cinfo.m_MCUs_per_row = JpegUtils.jdiv_round_up( m_cinfo.m_image_width, m_cinfo.m_max_h_samp_factor * JpegConstants.DCTSIZE); m_cinfo.m_MCU_rows_in_scan = JpegUtils.jdiv_round_up(m_cinfo.m_image_height, m_cinfo.m_max_v_samp_factor * JpegConstants.DCTSIZE); m_cinfo.m_blocks_in_MCU = 0; for (int ci = 0; ci < m_cinfo.m_comps_in_scan; ci++) { int compIndex = m_cinfo.m_cur_comp_info[ci]; /* Sampling factors give # of blocks of component in each MCU */ m_cinfo.Component_info[compIndex].MCU_width = m_cinfo.Component_info[compIndex].H_samp_factor; m_cinfo.Component_info[compIndex].MCU_height = m_cinfo.Component_info[compIndex].V_samp_factor; m_cinfo.Component_info[compIndex].MCU_blocks = m_cinfo.Component_info[compIndex].MCU_width * m_cinfo.Component_info[compIndex].MCU_height; m_cinfo.Component_info[compIndex].MCU_sample_width = m_cinfo.Component_info[compIndex].MCU_width * JpegConstants.DCTSIZE; /* Figure number of non-dummy blocks in last MCU column & row */ int tmp = m_cinfo.Component_info[compIndex].Width_in_blocks % m_cinfo.Component_info[compIndex].MCU_width; if (tmp == 0) tmp = m_cinfo.Component_info[compIndex].MCU_width; m_cinfo.Component_info[compIndex].last_col_width = tmp; tmp = m_cinfo.Component_info[compIndex].height_in_blocks % m_cinfo.Component_info[compIndex].MCU_height; if (tmp == 0) tmp = m_cinfo.Component_info[compIndex].MCU_height; m_cinfo.Component_info[compIndex].last_row_height = tmp; /* Prepare array describing MCU composition */ int mcublks = m_cinfo.Component_info[compIndex].MCU_blocks; if (m_cinfo.m_blocks_in_MCU + mcublks > JpegConstants.C_MAX_BLOCKS_IN_MCU) m_cinfo.ERREXIT(J_MESSAGE_CODE.JERR_BAD_MCU_SIZE); while (mcublks-- > 0) m_cinfo.m_MCU_membership[m_cinfo.m_blocks_in_MCU++] = ci; } } /* Convert restart specified in rows to actual MCU count. */ /* Note that count must fit in 16 bits, so we provide limiting. */ if (m_cinfo.m_restart_in_rows > 0) { int nominal = m_cinfo.m_restart_in_rows * m_cinfo.m_MCUs_per_row; m_cinfo.m_restart_interval = Math.Min(nominal, 65535); } } } }
nagyistoce/libtiff.net
LibTiff/LibJpeg/Internal/jpeg_comp_master.cs
C#
bsd-3-clause
15,132
'use strict'; angular.module('user-filters') .directive('zoUserFilters', function(){ return { restrict: 'E', replace: true, templateUrl: 'app/user-filters/list-directive.html', controller: 'UserFiltersDirectiveCtrl' } }) .controller('UserFiltersDirectiveCtrl', ['$scope', function($scope){ }]);
johnnycheng/AngularConcept
src/app/user-filters/list-directive.js
JavaScript
bsd-3-clause
347
<?php namespace frontend\models; use Yii; use \yii\db\ActiveRecord; use yii\data\Pagination; class Parttype extends \yii\db\ActiveRecord{ public static function tableName(){ return 'fin_part_type'; } public function select(){ $sql3="select * from fin_part_type "; $rows=Yii::$app->db->createCommand($sql3)->queryAll(); return $rows; } }
zcwzz/gittao
frontend/models/Parttype.php
PHP
bsd-3-clause
368
// Copyright 2011-2015 visualfc <visualfc@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runcmd import ( "fmt" "os" "os/exec" "strings" "github.com/visualfc/gotools/pkg/command" ) var Command = &command.Command{ Run: runCmd, UsageLine: "runcmd [-w work_path] <program_name> [arguments...]", Short: "run program", Long: `run program and arguments`, } var execWorkPath string var execWaitEnter bool func init() { Command.Flag.StringVar(&execWorkPath, "w", "", "work path") Command.Flag.BoolVar(&execWaitEnter, "e", true, "wait enter and continue") } func runCmd(cmd *command.Command, args []string) error { if len(args) == 0 { cmd.Usage() return os.ErrInvalid } if execWorkPath == "" { var err error execWorkPath, err = os.Getwd() if err != nil { return err } } fileName := args[0] filePath, err := exec.LookPath(fileName) if err != nil { filePath, err = exec.LookPath("./" + fileName) } if err != nil { return err } fmt.Println("Starting Process", filePath, strings.Join(args[1:], " "), "...") command := exec.Command(filePath, args[1:]...) command.Dir = execWorkPath command.Stdin = os.Stdin command.Stdout = os.Stdout command.Stderr = os.Stderr err = command.Run() if err != nil { fmt.Println("\nEnd Process", err) } else { fmt.Println("\nEnd Process", "exit status 0") } exitWaitEnter() return nil } func exitWaitEnter() { if !execWaitEnter { return } fmt.Println("\nPress enter key to continue") var s = [256]byte{} os.Stdin.Read(s[:]) }
visualfc/gotools
runcmd/runcmd.go
GO
bsd-3-clause
1,631
import React from 'react'; import PrivateRoute from '../../../routes/PrivateRoute'; import TextNodesEditorLayout from '../layouts/TextNodesLayout/TextNodesEditorLayout'; export default ( <PrivateRoute exact path="/textNodes/edit" component={TextNodesEditorLayout} roles={['commenter', 'editor', 'admin']} /> );
CtrHellenicStudies/Commentary
src/modules/textNodes/routes/index.js
JavaScript
bsd-3-clause
323
<?php use app\models\Upload; if ($object_id) { ?> <div> <img src="<?= Upload::getThumb($type, $value, true); ?>" data-toggle="lightbox" data-image="<?= Upload::getPicture($value, true); ?>" height="65" id="<?= $id; ?>_picture"> <p>预览缩略图</p> </div> <?php } else { ?> <img src="<?= Upload::getThumb($type, $value, true); ?>" height="65" id="<?= $id; ?>_picture"><p>预览缩略图</p> <?php } if ($display_upload && empty($value)) { ?> <div class="upload_picture"> <input type="file" name="file" id="uploadif_<?= $id; ?>"> </div> <?php } ?> <input name="<?= $old_name; ?>" type="hidden" value="<?= $value; ?>"> <input name="<?= $name; ?>" type="hidden" id="<?= $id; ?>_path" value="<?= $value; ?>"> <?php if ($object_id && $value && $delete_url) { ?> <p><button class="btn btn-sm btn-danger btn-confirm" type="button" data-title="删除图片" data-url="<?php echo $delete_url; ?>" data-params="_csrf=<?= \Yii::$app->request->csrfToken ?>"><span class="icon-remove"></span> 删除</button></p> <?php } ?> <script type="text/javascript"> $(function () { $('#uploadif_<?= $id; ?>').fileupload({ url: '<?= $upload_url; ?>', //文件上传地址 dataType: 'json', done: function (e, data) { //done方法就是上传完毕的回调函数,其他回调函数可以自行查看api if (data.result.error === 0) { $('#<?= $id; ?>_path').val(data.result.url); $('#<?= $id; ?>_picture').attr('src', '<?= \Yii::$app->params['upload_dir']; ?>' + data.result.url + '?' + Math.random()); $('#<?= $id; ?>_picture').attr('data-image', '<?= \Yii::$app->params['upload_dir']; ?>' + data.result.url + '?' + Math.random()); $('.upload_picture').hide(); } else { alert(data.result.message); } } }); }); </script>
sushipai/yii2basic
components/views/admin_picture.php
PHP
bsd-3-clause
2,006
require 'faraday' module SBA module Configuration VALID_OPTIONS_KEYS = [ :adapter, :endpoint, :user_agent, :proxy, :format].freeze VALID_FORMATS = [ :json, :xml].freeze DEFAULT_ADAPTER = Faraday.default_adapter DEFAULT_ENDPOINT = nil DEFAULT_PROXY = nil DEFAULT_FORMAT = :json DEFAULT_USER_AGENT = "SBA Ruby Gem #{SBA::VERSION}".freeze attr_accessor *VALID_OPTIONS_KEYS def self.extended(base) base.reset end def configure yield self end def options VALID_OPTIONS_KEYS.inject({}){|o,k| o.merge!(k => send(k)) } end def reset self.adapter = DEFAULT_ADAPTER self.user_agent = DEFAULT_USER_AGENT self.endpoint = DEFAULT_ENDPOINT self.format = DEFAULT_FORMAT self.proxy = DEFAULT_FORMAT end end end
codeforamerica/sba_ruby
lib/sba/configuration.rb
Ruby
bsd-3-clause
909
var slug = require('slug'); var async = require('async'); var _ = require('underscore'); var kwery = require('kwery'); var functions = { getInstances: function (state, next) { var result = kwery.flat(state.db, { path: new RegExp('^' + state.data.path + '(/|$)') }); result.many(function (instances) { state.instances = instances; next(null, state); }); }, parentData: function (state, next) { // Get parent data if parent exists if (!state.data.parent) { return next(null, state); } if (state.data.parent === '/') { state.parent = { path: '/', sort: [], }; return next(null, state); } var result = kwery.flat(state.db, { path: state.data.parent }); result.one(function (instance) { state.parent = instance; next(null, state); }); }, targetData: function (state, next) { // Instance that's being updated var target = JSON.parse(JSON.stringify(state.instances[0])); _.extend(target, state.data); target.order = state.data.order || target.sort[target.sort.length - 1]; target.sort[target.sort.length - 1] = target.order; delete target.parent; if (state.parent) { target.path = (state.parent.path + '/' + slug(target.name).toLowerCase()).replace('//', '/'); target.sort = state.parent.sort.concat([target.sort[target.sort.length - 1]]); } else { target.path = target.path.substr(0, target.path.lastIndexOf('/') + 1) + slug(target.name).toLowerCase(); } state.target = target; next(null, state); }, instancesData: function (state, next) { var base; var instances = JSON.parse(JSON.stringify(state.instances)); var original = instances[0]; instances.forEach(function (instance, i) { if (i === 0) { instances[i] = state.target; } else { instance.path = instance.path.replace(new RegExp('^' + original.path), state.target.path); instance.sort = state.target.sort.concat(instance.sort.slice(original.sort.length)); } }); state.data_instances = instances; next(null, state); }, updateInstances: function (state, next) { var stored_instances = []; state.data_instances.forEach(function (instance, i) { stored_instances.push(_.extend(state.instances[i], instance)); }); state.stored_instances = stored_instances; next(null, state); }, }; module.exports = functions;
Enome/jungles
data-memory/update/functions.js
JavaScript
bsd-3-clause
2,479
// Copyright (c) 2011 Hewlett-Packard Development Company, L.P. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <QDir> #include <QDoubleSpinBox> #include <QFileDialog> #include <QFileInfo> #include <QLabel> #include <QList> #include <QPlainTextEdit> #include <QPushButton> #include <QStringBuilder> #include <QTableWidget> #include <QTableWidgetItem> #include <QUrl> #include <QWebSettings> #include <QtGlobal> #include <webvfx/effects.h> #include <webvfx/image.h> #include <webvfx/parameters.h> #include <webvfx/webvfx.h> #include <webvfx/qml_content.h> #include <webvfx/web_content.h> #include "image_color.h" #include "render_dialog.h" #include "viewer.h" // Expose parameter name/value pairs from the table to the page content class ViewerParameters : public WebVfx::Parameters { public: ViewerParameters(QTableWidget* tableWidget) : tableWidget(tableWidget) {} double getNumberParameter(const QString& name) { QString value = findValue(name); return value.toDouble(); } QString getStringParameter(const QString& name) { return findValue(name); } private: QString findValue(const QString& name) { QList<QTableWidgetItem*> itemList = tableWidget->findItems(name, Qt::MatchFixedString|Qt::MatchCaseSensitive); foreach (const QTableWidgetItem* item, itemList) { // If the string matches column 0 (Name), then return column 1 (Value) if (item->column() == 0) { QTableWidgetItem* valueItem = tableWidget->item(item->row(), 1); if (valueItem) return valueItem->text(); } } return QString(); } QTableWidget* tableWidget; }; ///////////////// class ViewerLogger : public WebVfx::Logger { public: ViewerLogger(QPlainTextEdit* logText) : logText(logText) {} void log(const QString& msg) { logText->appendPlainText(msg); } private: QPlainTextEdit* logText; }; ///////////////// Viewer::Viewer() : QMainWindow(0) , sizeLabel(0) , timeSpinBox(0) , content(0) { setupUi(this); WebVfx::setLogger(new ViewerLogger(logTextEdit)); // Time display timeSpinBox = new QDoubleSpinBox(statusBar()); timeSpinBox->setDecimals(4); timeSpinBox->setSingleStep(0.01); timeSpinBox->setMaximum(1.0); timeSpinBox->setValue(sliderTimeValue(timeSlider->value())); statusBar()->addPermanentWidget(timeSpinBox); connect(timeSpinBox, SIGNAL(valueChanged(double)), SLOT(onTimeSpinBoxValueChanged(double))); // Size display sizeLabel = new QLabel(statusBar()); statusBar()->addPermanentWidget(sizeLabel); setContentUIEnabled(false); handleResize(); } void Viewer::setContentUIEnabled(bool enable) { timeSpinBox->setEnabled(enable); timeSlider->setEnabled(enable); actionReload->setEnabled(enable); actionRenderImage->setEnabled(enable); } void Viewer::onContentLoadFinished(bool result) { if (result) { setupImages(scrollArea->widget()->size()); content->renderContent(timeSpinBox->value(), 0); } else { statusBar()->showMessage(tr("Load failed"), 2000); setWindowFilePath(""); } setContentUIEnabled(result); } void Viewer::on_actionOpen_triggered(bool) { QString fileName = QFileDialog::getOpenFileName(this, tr("Open"), QString(), tr("WebVfx Files (*.html *.htm *.qml)")); loadFile(fileName); } void Viewer::on_actionReload_triggered(bool) { content->reload(); } void Viewer::on_actionRenderImage_triggered(bool) { QImage image(scrollArea->widget()->size(), QImage::Format_RGB888); WebVfx::Image renderImage(image.bits(), image.width(), image.height(), image.byteCount()); content->renderContent(timeSpinBox->value(), &renderImage); RenderDialog* dialog = new RenderDialog(this); dialog->setImage(image); dialog->show(); } void Viewer::on_resizeButton_clicked() { handleResize(); } void Viewer::loadFile(const QString& fileName) { if (fileName.isNull()) return; createContent(fileName); setWindowFilePath(fileName); } void Viewer::handleResize() { int width = widthSpinBox->value(); int height = heightSpinBox->value(); scrollArea->widget()->resize(width, height); if (content) content->setContentSize(QSize(width, height)); sizeLabel->setText(QString::number(width) % QLatin1Literal("x") % QString::number(height)); // Iterate over ImageColor widgets in table and change their sizes QSize size(width, height); int rowCount = imagesTable->rowCount(); for (int i = 0; i < rowCount; i++) { ImageColor* imageColor = static_cast<ImageColor*>(imagesTable->cellWidget(i, 1)); if (imageColor) imageColor->setImageSize(size); } } void Viewer::setImagesOnContent() { if (!content) return; int rowCount = imagesTable->rowCount(); for (int i = 0; i < rowCount; i++) { ImageColor* imageColor = static_cast<ImageColor*>(imagesTable->cellWidget(i, 1)); if (imageColor) { WebVfx::Image image(imageColor->getImage()); content->setImage(imageColor->objectName(), &image); } } } void Viewer::on_timeSlider_valueChanged(int value) { timeSpinBox->setValue(sliderTimeValue(value)); } void Viewer::onTimeSpinBoxValueChanged(double time) { if (content) { setImagesOnContent(); content->renderContent(time, 0); } timeSlider->blockSignals(true); timeSlider->setValue(time * timeSlider->maximum()); timeSlider->blockSignals(false); } void Viewer::on_addParameterButton_clicked() { int row = parametersTable->currentRow(); parametersTable->insertRow(row >= 0 ? row : 0); } void Viewer::on_deleteParameterButton_clicked() { int row = parametersTable->currentRow(); if (row >= 0) parametersTable->removeRow(row); } double Viewer::sliderTimeValue(int value) { return value / (double)timeSlider->maximum(); } void Viewer::createContent(const QString& fileName) { if (fileName.endsWith(".qml", Qt::CaseInsensitive)) { WebVfx::QmlContent* qmlContent = new WebVfx::QmlContent(scrollArea->widget()->size(), new ViewerParameters(parametersTable)); content = qmlContent; connect(qmlContent, SIGNAL(contentLoadFinished(bool)), SLOT(onContentLoadFinished(bool))); } else if (fileName.endsWith(".html", Qt::CaseInsensitive) || fileName.endsWith(".htm", Qt::CaseInsensitive)){ WebVfx::WebContent* webContent = new WebVfx::WebContent(scrollArea->widget()->size(), new ViewerParameters(parametersTable)); // User can right-click to open WebInspector on the page webContent->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); content = webContent; connect(webContent, SIGNAL(contentLoadFinished(bool)), SLOT(onContentLoadFinished(bool))); } QWidget* view = content->createView(scrollArea); view->resize(scrollArea->widget()->size()); // Set content as direct widget of QScrollArea, // otherwise it creates an intermediate QWidget which messes up resizing. // setWidget will destroy the old view. scrollArea->setWidget(view); logTextEdit->clear(); setContentUIEnabled(true); content->loadContent(QUrl::fromLocalFile(QFileInfo(fileName).absoluteFilePath())); } void Viewer::setupImages(const QSize& size) { imagesTable->setRowCount(0); int row = 0; WebVfx::Effects::ImageTypeMapIterator it(content->getImageTypeMap()); while (it.hasNext()) { it.next(); imagesTable->insertRow(row); QString imageName(it.key()); // Image name in column 0 QTableWidgetItem* item = new QTableWidgetItem(imageName); item->setFlags(Qt::NoItemFlags); imagesTable->setItem(row, 0, item); // Image color swatch in column 1 ImageColor* imageColor = new ImageColor(); imageColor->setImageSize(size); imageColor->setObjectName(imageName); connect(imageColor, SIGNAL(imageChanged(QString,WebVfx::Image)), SLOT(onImageChanged(QString,WebVfx::Image))); // Set color here so signal fires imageColor->setImageColor(QColor::fromHsv(qrand() % 360, 200, 230)); imagesTable->setCellWidget(row, 1, imageColor); // Type name in column 2 QString typeName; switch (it.value()) { case WebVfx::Effects::SourceImageType: typeName = tr("Source"); break; case WebVfx::Effects::TargetImageType: typeName = tr("Target"); break; case WebVfx::Effects::ExtraImageType: typeName = tr("Extra"); break; } item = new QTableWidgetItem(typeName); item->setFlags(Qt::NoItemFlags); imagesTable->setItem(row, 2, item); row++; } } void Viewer::onImageChanged(const QString& name, WebVfx::Image image) { if (!content) return; content->setImage(name, &image); }
mltframework/webvfx
viewer/viewer.cpp
C++
bsd-3-clause
9,437
# -*- python -*- # stdlib imports --- import os import os.path as osp import textwrap # waf imports --- import waflib.Utils import waflib.Logs as msg from waflib.Configure import conf # _heptooldir = osp.dirname(osp.abspath(__file__)) def options(opt): opt.load('hwaf-base', tooldir=_heptooldir) opt.add_option( '--with-cmake', default=None, help="Look for CMake at the given path") return def configure(conf): conf.load('hwaf-base', tooldir=_heptooldir) return @conf def find_cmake(ctx, **kwargs): if not ctx.env.HWAF_FOUND_C_COMPILER: ctx.fatal('load a C compiler first') pass if not ctx.env.HWAF_FOUND_CXX_COMPILER: ctx.fatal('load a C++ compiler first') pass path_list = waflib.Utils.to_list(kwargs.get('path_list', [])) if getattr(ctx.options, 'with_cmake', None): topdir = ctx.options.with_cmake topdir = ctx.hwaf_subst_vars(topdir) path_list.append(osp.join(topdir, "bin")) pass kwargs['path_list'] = path_list ctx.find_program( "cmake", var="CMAKE", **kwargs) kwargs['mandatory'] = False ctx.find_program( "ccmake", var="CCMAKE", **kwargs) ctx.find_program( "cpack", var="CPACK", **kwargs) ctx.find_program( "ctest", var="CTEST", **kwargs) version="N/A" cmd = [ctx.env.CMAKE, "--version"] lines=ctx.cmd_and_log(cmd).splitlines() for l in lines: l = l.lower() if "version" in l: version=l[l.find("version")+len("version"):].strip() break pass ctx.start_msg("CMake version") ctx.end_msg(version) ctx.hwaf_declare_runtime_env('CMAKE') ctx.env.CMAKE_HOME = osp.dirname(osp.dirname(ctx.env.CMAKE)) ctx.env.CMAKE_VERSION = version ctx.env.HWAF_FOUND_CMAKE = 1 return ## EOF ##
hwaf/hwaf
py-hwaftools/find_cmake.py
Python
bsd-3-clause
1,951
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule RelayDefaultNetworkLayer * @typechecks * @flow */ 'use strict'; var Promise = require('Promise'); import type RelayMutationRequest from 'RelayMutationRequest'; import type RelayQueryRequest from 'RelayQueryRequest'; var fetchWithRetries = require('fetchWithRetries'); import type {InitWithRetries} from 'fetchWithRetries'; type GraphQLError = { message: string; locations: Array<GraphQLErrorLocation>; }; type GraphQLErrorLocation = { column: number; line: number; }; class RelayDefaultNetworkLayer { _uri: string; _init: $FlowIssue; // InitWithRetries constructor(uri: string, init?: ?InitWithRetries) { this._uri = uri; this._init = {...init}; // Bind instance methods to facilitate reuse when creating custom network // layers. var self: any = this; self.sendMutation = this.sendMutation.bind(this); self.sendQueries = this.sendQueries.bind(this); self.supports = this.supports.bind(this); } sendMutation(request: RelayMutationRequest): Promise { return this._sendMutation(request).then( result => result.json() ).then(payload => { if (payload.hasOwnProperty('errors')) { var error = new Error( 'Server request for mutation `' + request.getDebugName() + '` ' + 'failed for the following reasons:\n\n' + formatRequestErrors(request, payload.errors) ); (error: any).source = payload; request.reject(error); } else { request.resolve({response: payload.data}); } }).catch( error => request.reject(error) ); } sendQueries(requests: Array<RelayQueryRequest>): Promise { return Promise.all(requests.map(request => ( this._sendQuery(request).then( result => result.json() ).then(payload => { if (payload.hasOwnProperty('errors')) { var error = new Error( 'Server request for query `' + request.getDebugName() + '` ' + 'failed for the following reasons:\n\n' + formatRequestErrors(request, payload.errors) ); (error: any).source = payload; request.reject(error); } else if (!payload.hasOwnProperty('data')) { request.reject(new Error( 'Server response was missing for query `' + request.getDebugName() + '`.' )); } else { request.resolve({response: payload.data}); } }).catch( error => request.reject(error) ) ))); } supports(...options: Array<string>): boolean { // Does not support the only defined option, "defer". return false; } /** * Sends a POST request with optional files. */ _sendMutation(request: RelayMutationRequest): Promise { var init; var files = request.getFiles(); if (files) { if (!global.FormData) { throw new Error('Uploading files without `FormData` not supported.'); } var formData = new FormData(); formData.append('query', request.getQueryString()); formData.append('variables', JSON.stringify(request.getVariables())); for (var filename in files) { if (files.hasOwnProperty(filename)) { formData.append(filename, files[filename]); } } init = { ...this._init, body: formData, method: 'POST', }; } else { init = { ...this._init, body: JSON.stringify({ query: request.getQueryString(), variables: request.getVariables(), }), headers: { ...this._init.headers, 'Content-Type': 'application/json', }, method: 'POST', }; } return fetch(this._uri, init).then(throwOnServerError); } /** * Sends a POST request and retries if the request fails or times out. */ _sendQuery(request: RelayQueryRequest): Promise { return fetchWithRetries(this._uri, { ...this._init, body: JSON.stringify({ query: request.getQueryString(), variables: request.getVariables(), }), headers: { ...this._init.headers, 'Content-Type': 'application/json', }, method: 'POST', }); } } /** * Rejects HTTP responses with a status code that is not >= 200 and < 300. * This is done to follow the internal behavior of `fetchWithRetries`. */ function throwOnServerError(response: any): any { if (response.status >= 200 && response.status < 300) { return response; } else { throw response; } } /** * Formats an error response from GraphQL server request. */ function formatRequestErrors( request: RelayMutationRequest | RelayQueryRequest, errors: Array<GraphQLError> ): string { var CONTEXT_BEFORE = 20; var CONTEXT_LENGTH = 60; var queryLines = request.getQueryString().split('\n'); return errors.map(({locations, message}, ii) => { var prefix = (ii + 1) + '. '; var indent = ' '.repeat(prefix.length); //custom errors thrown in graphql-server may not have locations var locationMessage = locations ? ('\n' + locations.map(({column, line}) => { var queryLine = queryLines[line - 1]; var offset = Math.min(column - 1, CONTEXT_BEFORE); return [ queryLine.substr(column - 1 - offset, CONTEXT_LENGTH), ' '.repeat(offset) + '^^^' ].map(messageLine => indent + messageLine).join('\n'); }).join('\n')) : ''; return prefix + message + locationMessage; }).join('\n'); } module.exports = RelayDefaultNetworkLayer;
tmitchel2/relay
src/network-layer/default/RelayDefaultNetworkLayer.js
JavaScript
bsd-3-clause
5,878
/* * ColorRGB property file * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "Engine/Component/Component.h" #include "IO/FileSystem/File.h" namespace Fork { namespace Engine { Component::Property::Types Component::ColorRGBProperty::Type() const { return Types::ColorRGB; } void Component::ColorRGBProperty::WriteToFile(IO::File& file) const { file.Write<unsigned char>(value.r); file.Write<unsigned char>(value.g); file.Write<unsigned char>(value.b); } void Component::ColorRGBProperty::ReadFromFile(IO::File& file) { value.r = file.Read<unsigned char>(); value.g = file.Read<unsigned char>(); value.b = file.Read<unsigned char>(); } void Component::ColorRGBProperty::WriteToVariant(IO::Variant& variant) const { variant = value; } void Component::ColorRGBProperty::ReadFromVariant(const IO::Variant& variant) { value = variant.GetColorRGB(); } } // /namespace Engine } // /namespace Fork // ========================
LukasBanana/ForkENGINE
sources/Engine/Component/Property/ColorRGBProperty.cpp
C++
bsd-3-clause
1,063
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model backend\models\Etc */ $this->title = 'Create Etc'; $this->params['breadcrumbs'][] = ['label' => 'Etcs', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="etc-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
Sronsai/rm
backend/views/etc/create.php
PHP
bsd-3-clause
425
<?php return [ 'db' => require __DIR__ . '/db.php', 'templateManager' => ymaker\email\templates\components\TemplateManager::class, ];
yiimaker/yii2-email-templates
tests/_config/components.php
PHP
bsd-3-clause
143
# ---------------------------------------------------------------------------- # Copyright (c) 2008 Andrew D. Straw and Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # Based on pygxinput originally by Andrew D. Straw # http://code.astraw.com/projects/motmot/wiki/pygxinput import ctypes import pyglet from pyglet.window.xlib import xlib import lib_xinput as xi class XInputDevice: def __init__(self, display, device_info): self._x_display = display._display self._device_id = device_info.id self.name = device_info.name self._open_device = None # TODO: retrieve inputclassinfo from device_info and expose / save # for valuator axes etc. def open(self): if self._open_device: return self._open_device = xi.XOpenDevice(self._x_display, self._device_id) if not self._open_device: raise Exception('Cannot open device') def close(self): if not self._open_device: return xi.XCloseDevice(self._x_display, self._open_device) def attach(self, window): assert window._x_display == self._x_display return XInputDeviceInstance(self, window) class XInputDeviceInstance(pyglet.event.EventDispatcher): def __init__(self, device, window): """Create an opened instance of a device on the given window. :Parameters: `device` : XInputDevice Device to open `window` : Window Window to open device on """ assert device._x_display == window._x_display assert device._open_device self.device = device self.window = window self._events = list() try: dispatcher = window.__xinput_window_event_dispatcher except AttributeError: dispatcher = window.__xinput_window_event_dispatcher = \ XInputWindowEventDispatcher() dispatcher.add_instance(self) device = device._open_device.contents if not device.num_classes: return # Bind matching extended window events to bound instance methods # on this object. # # This is inspired by test.c of xinput package by Frederic # Lepied available at x.org. # # In C, this stuff is normally handled by the macro DeviceKeyPress and # friends. Since we don't have access to those macros here, we do it # this way. for i in range(device.num_classes): class_info = device.classes[i] if class_info.input_class == xi.KeyClass: self._add(class_info, xi._deviceKeyPress, dispatcher._event_xinput_key_press) self._add(class_info, xi._deviceKeyRelease, dispatcher._event_xinput_key_release) elif class_info.input_class == xi.ButtonClass: self._add(class_info, xi._deviceButtonPress, dispatcher._event_xinput_button_press) self._add(class_info, xi._deviceButtonRelease, dispatcher._event_xinput_button_release) elif class_info.input_class == xi.ValuatorClass: self._add(class_info, xi._deviceMotionNotify, dispatcher._event_xinput_motion) elif class_info.input_class == xi.ProximityClass: self._add(class_info, xi._proximityIn, dispatcher._event_xinput_proximity_in) self._add(class_info, xi._proximityOut, dispatcher._event_xinput_proximity_out) elif class_info.input_class == xi.FeedbackClass: pass elif class_info.input_class == xi.FocusClass: pass elif class_info.input_class == xi.OtherClass: pass array = (xi.XEventClass * len(self._events))(*self._events) xi.XSelectExtensionEvent(window._x_display, window._window, array, len(array)) def _add(self, class_info, event, handler): _type = class_info.event_type_base + event _class = self.device._device_id << 8 | _type self._events.append(_class) self.window._event_handlers[_type] = handler XInputDeviceInstance.register_event_type('on_button_press') XInputDeviceInstance.register_event_type('on_button_release') XInputDeviceInstance.register_event_type('on_motion') XInputDeviceInstance.register_event_type('on_proximity_in') XInputDeviceInstance.register_event_type('on_proximity_out') class XInputWindowEventDispatcher: def __init__(self): self._instances = dict() def add_instance(self, instance): self._instances[instance.device._device_id] = instance def remove_instance(self, instance): del self._instances[instance.device._device_id] def dispatch_instance_event(self, e, *args): try: instance = self._instances[e.deviceid] except KeyError: return instance.dispatch_event(*args) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_press(self, ev): raise NotImplementedError('TODO') @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_release(self, ev): raise NotImplementedError('TODO') @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents self.dispatch_instance_event(e, 'on_button_press', e.button) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents self.dispatch_instance_event(e, 'on_button_release', e.button) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_motion(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceMotionEvent)).contents axis_data = list() for i in range(e.axes_count): axis_data.append(e.axis_data[i]) self.dispatch_instance_event(e, 'on_motion', axis_data, e.x, e.y) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_proximity_in(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents self.dispatch_instance_event(e, 'on_proximity_in') @pyglet.window.xlib.XlibEventHandler(-1) def _event_xinput_proximity_out(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents self.dispatch_instance_event(e, 'on_proximity_out') def _check_extension(display): major_opcode = ctypes.c_int() first_event = ctypes.c_int() first_error = ctypes.c_int() xlib.XQueryExtension(display._display, 'XInputExtension', ctypes.byref(major_opcode), ctypes.byref(first_event), ctypes.byref(first_error)) if not major_opcode.value: raise Exception('XInput extension not available') def get_devices(display): _check_extension(display) devices = list() count = ctypes.c_int(0) device_list = xi.XListInputDevices(display._display, count) for i in range(count.value): device_info = device_list[i] devices.append(XInputDevice(display, device_info)) return devices
bitcraft/pyglet
contrib/experimental/input/xinput.py
Python
bsd-3-clause
9,260
# ----------------------------------------------------------------------------- # Generates necessary xml for a Column chart # # Author: Fernand # ----------------------------------------------------------------------------- module Ziya::Charts class Column < Base # Creates a column chart # <tt>:license</tt>:: the XML/SWF charts license # <tt>:chart_id</tt>:: the name of the chart style sheet. def initialize( license=nil, chart_id=nil ) super( license, chart_id ) @type = "column" end end end
ehedberg/travis
vendor/gems/ziya-2.1.7/lib/ziya/charts/column.rb
Ruby
bsd-3-clause
545
<?php defined('SYSPATH') or die('No direct script access.'); /** * Message is a class that lets you easily send messages * in your application (aka Flash Messages) * * @package Message * @author Dave Widmer * @see http://github.com/daveWid/message * @see http://www.davewidmer.net * @copyright 2010 © Dave Widmer */ class Message_Core { /** * Constants to use for the types of messages that can be set. */ const ERROR = 'error'; const NOTICE = 'notice'; const SUCCESS = 'success'; const WARN = 'warn'; /** * @var mixed The message to display. */ public $message; /** * @var string The type of message. */ public $type; /** * Creates a new Falcon_Message instance. * * @param string Type of message * @param mixed Message to display, either string or array */ public function __construct($type, $message) { $this->type = $type; $this->message = $message; } /** * Clears the message from the session * * @return void */ public static function clear() { Session::instance()->delete('flash_message'); } /** * Displays the message * * @return string Message to string */ public static function display() { $msg = self::get(); if( $msg ){ self::clear(); return View::factory('message/basic')->set('message', $msg)->render(); } else { return ''; } } /** * The same as display - used to mold to Kohana standards * * @return string HTML for message */ public static function render() { return self::display(); } /** * Gets the current message. * * @return mixed The message or FALSE */ public static function get() { return Session::instance()->get('flash_message', FALSE); } /** * Sets a message. * * @param string Type of message * @param mixed Array/String for the message * @return void */ public static function set($type, $message) { Session::instance()->set('flash_message', new Message($type, $message)); } }
ajaxray/Kohana-Twitter-Bootstrap-boilarplate
modules/message/classes/message/core.php
PHP
bsd-3-clause
1,955
package main import ( "fmt" "os" "os/signal" "syscall" ) func Print(format string, params ...interface{}) { fmt.Fprintf(os.Stderr, format+"\n", params...) } func Info(format string, params ...interface{}) { Print("Info: " + format, params...) } func Error(err error) { Print("Error: %s", err) } func Fatal(err error) { Print("Fatal: %s", err) os.Exit(1) } func main() { var config Config var err error if config, err = LoadConfig(); err != nil { Fatal(err) } if err = config.Verify(); err != nil { Fatal(err) } var svcmon ServiceMonitor if svcmon, err = NewServiceMonitor(&config); err != nil { Fatal(err) } cleanup := func() { svcmon.Close() } defer cleanup() sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, syscall.SIGINT) signal.Notify(sigchan, syscall.SIGTERM) quit := make(chan bool) go func() { <-sigchan cleanup() quit <- true }() go func() { if err = svcmon.Run(); err != nil { Fatal(err) } quit <- true }() <-quit }
WiFast/go-pagervisor
pagervisor/pagervisor.go
GO
bsd-3-clause
1,001
/* Author: Robert Gazdziak (gazdzia2) */ /* Collaborated with: Thomas Lesniak (tlesnia2) */ import java.util.Random; import java.util.ArrayList; public class QLearningAgent implements Agent { public QLearningAgent() { this.rand = new Random(); } public void initialize(int numOfStates, int numOfActions) { this.q = new double[numOfStates][numOfActions]; this.numOfStates = numOfStates; this.numOfActions = numOfActions; } //Returns best possible action (or random action of multiple best actions) private int bestUtility(int state) { double max = q[state][0]; //Array list that holds best actions ArrayList<Integer> bestActions = new ArrayList<Integer>(); bestActions.add(0); for(int i = 1; i<numOfActions; i++) { //if greater than max, clear list and put this action on if(q[state][i] > max) { max = q[state][i]; bestActions.clear(); bestActions.add(i); } //If equal, add on to the list else if(q[state][i] == max) { bestActions.add(i); } } //Choose random action from list of best actions int action = rand.nextInt(bestActions.size()); return bestActions.get(action); } //Returns best possible action or random action depending on epsilon public int chooseAction(int state) { //Random double for epsilon-greedy double greedy = rand.nextDouble(); int action = 0; //if smaller, choose (one of the possible) best option(s) if(greedy < (1.0-epsilon)) action = bestUtility(state); //If equal or larger choose random action else action = rand.nextInt(numOfActions); return action; } //update the policy of oldState+action public void updatePolicy(double reward, int action, int oldState, int newState) { q[oldState][action] = q[oldState][action] + rate*(reward+discount*(q[newState][chooseAction(newState)]-q[oldState][action])); } //Returns best policy for every state public Policy getPolicy() { int[] actions = new int[numOfStates]; //run through all states for(int i = 0; i<numOfStates; i++) { //for each state pick the best action actions[i] = bestUtility(i); } return new Policy(actions); } private static final double discount = 0.9; private static final double rate = 0.1; private static final double epsilon = 0.00; private Random rand; private int numOfStates; private int numOfActions; private double[][] q; }
linyufly/QLearningMP
AutoTest/Code/Machine Problem 1 (Part 1)_gazdzia2_attempt_2014-09-22-20-19-36_QLearningAgent.java
Java
bsd-3-clause
2,454
package jscheme; import java.io.PrintWriter; import jsint.Evaluator; import jsint.InputPort; import jsint.Pair; import jsint.Scheme; import jsint.Symbol; import jsint.U; /** JScheme - a simple interface to JScheme. <p> This class provides methods to perform common Scheme operations from java. Each instance of <code>JScheme</code> is an isolated Scheme environment. <p>For example, you can: <ul> <li> Create a new Scheme environment: <pre> JScheme js = new JScheme(); </pre> <li> Initialize an application by loading Scheme expressions from a file: <pre> js.load(new java.io.File("app.init")); </pre> <li> Run the Scheme procedure <tt>(describe)</tt> to describe the current object like this: <pre> js.call("describe", this); </pre> If you need to call a procedure with more than twenty arguments use apply(). <li>Evalute a string as an expression: <pre> String query = "(+ (expt (Math.sin 2.0) 2) (expt (Math.cos 2.0) 2))"; System.out.println(query + " = " + js.eval(query)); </pre> </ul> <p> Unit test: <pre> (import "jscheme.JScheme") (load "elf/util.scm") (define js (JScheme.forCurrentEvaluator)) (assert (equal? (+ 2 3) (.eval js '(+ 2 3)))) (assert (= (+ 2 3) (.eval js "(+ 2 3)"))) (assert (= (+ 2 3) (.call js "+" 2 3))) (assert (= (+ 2 3) (.call js + 2 3))) (assert (= (+ 2 3) (.apply js "+" (JScheme.list 2 3)))) (.load js "(define (f x) (+ x (g x))) (define (g x) (* x 3))") (assert (= (f 3) 12)) </pre> **/ public class JScheme implements java.io.Serializable { private Evaluator evaluator; /** * Creates a new, isolated Scheme environment. */ public JScheme() { evaluator = new Evaluator(); } /** * Creates a Scheme environment that shares an evaluation enironment. * Top-level bindings will be shared. */ public JScheme(Evaluator e) { evaluator = e; } /** * Returns the Scheme environment that is currently executing Scheme. Only * call this from Scheme (or from Java called from Scheme). */ public static JScheme forCurrentEvaluator() { return new JScheme(Scheme.currentEvaluator()); } /** * Returns this Scheme environment's evaluator. */ public Evaluator getEvaluator() { return evaluator; } /** * Enters this instance's evaluator. */ private void enter() { Scheme.pushEvaluator((Evaluator)evaluator); } /** * Exits an evaluator. This must be called for every call to * <code>enter</code>. */ private void exit() { Scheme.popEvaluator(); } /** Does the Symbol named s have a global value? **/ public boolean isDefined(String s) { enter(); try { return Symbol.intern(s).isDefined();} finally { exit(); } } /** Get the value of the global variable named s. **/ public Object getGlobalValue(String s) { enter(); try { return Symbol.intern(s).getGlobalValue(); } finally { exit(); } } /** Set the value of the global variable named s to v. **/ public void setGlobalValue(String s, Object v) { enter(); try { Symbol.intern(s).setGlobalValue(v); } finally { exit(); } } /** Returns the global procedure named s. **/ public SchemeProcedure getGlobalSchemeProcedure(String s) { enter(); try { return U.toProc(getGlobalValue(s)); } finally { exit(); } } /** Load Scheme expressions from a Reader, or String. **/ public Object load(java.io.Reader in) { enter(); try { return Scheme.load(new InputPort(in)); } finally { exit(); } } public Object load(String in) { return load(new java.io.StringReader(in)); } /** Eval or load a string. This is useful for handling command line arguments. If it starts with "(", it is evaled. If it doesn't start with "-", it is loaded. **/ public void evalOrLoad(String it) { if (it.startsWith("(")) { load(new java.io.StringReader(it)); } else if (! it.startsWith("-")) { enter(); try { Scheme.load(it); } finally { exit(); } } } /** Call a procedure with 0 to 20 arguments **/ public Object call(SchemeProcedure p) { enter(); try { return p.apply(list()); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1) { enter(); try { return p.apply(list(a1)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2) { enter(); try { return p.apply(list(a1, a2)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3) { enter(); try { return p.apply(list(a1, a2, a3)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4) { enter(); try { return p.apply(list(a1, a2, a3, a4)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)); } finally { exit(); } } public Object call(SchemeProcedure p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19, Object a20) { enter(); try { return p.apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)); } finally { exit(); } } /** Apply a procedure to a list of arguments. **/ public Object apply(SchemeProcedure p, SchemePair as) { enter(); try { return p.apply(as); } finally { exit(); } } public Object apply(SchemeProcedure p, Object[] args) { enter(); try { return p.apply(args); } finally { exit(); } } /** Call a procedure named p with from 0 to 20 arguments. **/ public Object call(String p) { enter(); try { return getGlobalSchemeProcedure(p).apply(list()); } finally { exit(); } } public Object call(String p, Object a1) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1)); } finally { exit(); } } public Object call(String p, Object a1, Object a2) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)); } finally { exit(); } } public Object call(String p, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19, Object a20) { enter(); try { return getGlobalSchemeProcedure(p).apply(list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)); } finally { exit(); } } /** Apply a procedure named p to a list of arguments. **/ public Object apply(String p, SchemePair as) { enter(); try { return getGlobalSchemeProcedure(p).apply(as); } finally { exit(); } } /** Evaluate the contents of a string as a Scheme expression. **/ public Object eval(String s) { Object it = read(s); return it == InputPort.EOF ? it : eval(it); } /** Evaluate an expression Object **/ public Object eval(Object it) { enter(); try { return Scheme.evalToplevel(it, jsint.Scheme.getInteractionEnvironment()); } finally { exit(); } } /** Read an expression from a String. **/ public Object read(String s) { enter(); try { return (new InputPort(new java.io.StringReader(s))).read(); } finally { exit(); } } /** Lists of length 0 to 20. **/ public static SchemePair list() { return Pair.EMPTY; } public static SchemePair list(Object a0) { return new Pair(a0, list()); } public static SchemePair list(Object a0, Object a1) { return new Pair(a0, list(a1)); } public static SchemePair list(Object a0, Object a1, Object a2) { return new Pair(a0, list(a1, a2)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3) { return new Pair(a0, list(a1, a2, a3)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4) { return new Pair(a0, list(a1, a2, a3, a4)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) { return new Pair(a0, list(a1, a2, a3, a4, a5)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)); } public static SchemePair list(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7, Object a8, Object a9, Object a10, Object a11, Object a12, Object a13, Object a14, Object a15, Object a16, Object a17, Object a18, Object a19, Object a20) { return new Pair(a0, list(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)); } public void write(Object x, PrintWriter port, boolean quoted) { enter(); try { U.write(x, port, quoted); } finally { exit(); } } public void write(Object x, PrintWriter port) { enter(); try { U.write(x, port, true); } finally { exit(); } } public void display(Object x, PrintWriter port) { enter(); try { U.write(x, port, false); } finally { exit(); } } public void readEvalPrintLoop() { enter(); try { Scheme.readEvalWriteLoop(">"); } finally { exit(); } } /** Convert from an Object to a primitive type. **/ public static boolean booleanValue(Object o) { return o != Boolean.FALSE; } public static byte byteValue(Object o) { return ((Number) o).byteValue(); } public static char charValue(Object o) { return (o instanceof Number) ? ((char)((Number) o).shortValue()) : ((Character) o).charValue(); } public static short shortValue(Object o) { return ((Number) o).shortValue(); } public static int intValue(Object o) { return ((Number) o).intValue(); } public static long longValue(Object o) { return ((Number) o).longValue(); } public static float floatValue(Object o) { return ((Number) o).floatValue(); } public static double doubleValue(Object o) { return ((Number) o).doubleValue(); } /** Convert from primitive type to Object. **/ public static Boolean toObject(boolean x) { return x ? Boolean.TRUE : Boolean.FALSE; } public static Object toObject(byte x) { return new Byte(x); } public static Object toObject(char x) { return new Character(x); } public static Object toObject(short x) { return new Short(x); } public static Object toObject(int x) { return U.toNum(x); } public static Object toObject(long x) { return new Long(x); } public static Object toObject(float x) { return new Float(x); } public static Object toObject(double x) { return new Double(x); } public static Object toObject(Object x) { return x; } // Completeness. }
sergv/jscheme
src/jscheme/JScheme.java
Java
bsd-3-clause
23,965
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import from wtforms import validators from ..forms import ModelForm from digits import utils class ImageModelForm(ModelForm): """ Defines the form used to create a new ImageModelJob """ crop_size = utils.forms.IntegerField( 'Crop Size', validators=[ validators.NumberRange(min=1), validators.Optional() ], tooltip=("If specified, during training a random square crop will be " "taken from the input image before using as input for the network.") ) use_mean = utils.forms.SelectField( 'Subtract Mean', choices=[ ('none', 'None'), ('image', 'Image'), ('pixel', 'Pixel'), ], default='image', tooltip="Subtract the mean file or mean pixel for this dataset from each image." ) aug_flip = utils.forms.SelectField( 'Flipping', choices=[ ('none', 'None'), ('fliplr', 'Horizontal'), ('flipud', 'Vertical'), ('fliplrud', 'Horizontal and/or Vertical'), ], default='none', tooltip="Randomly flips each image during batch preprocessing." ) aug_quad_rot = utils.forms.SelectField( 'Quadrilateral Rotation', choices=[ ('none', 'None'), ('rot90', '0, 90 or 270 degrees'), ('rot180', '0 or 180 degrees'), ('rotall', '0, 90, 180 or 270 degrees.'), ], default='none', tooltip="Randomly rotates (90 degree steps) each image during batch preprocessing." ) aug_rot = utils.forms.IntegerField( 'Rotation (+- deg)', default=0, validators=[ validators.NumberRange(min=0, max=180) ], tooltip="The uniform-random rotation angle that will be performed during batch preprocessing." ) aug_scale = utils.forms.FloatField( 'Rescale (stddev)', default=0, validators=[ validators.NumberRange(min=0, max=1) ], tooltip=("Retaining image size, the image is rescaled with a " "+-stddev of this parameter. Suggested value is 0.07.") ) aug_noise = utils.forms.FloatField( 'Noise (stddev)', default=0, validators=[ validators.NumberRange(min=0, max=1) ], tooltip=("Adds AWGN (Additive White Gaussian Noise) during batch " "preprocessing, assuming [0 1] pixel-value range. Suggested value is 0.03.") ) aug_hsv_use = utils.forms.BooleanField( 'HSV Shifting', default=False, tooltip=("Augmentation by normal-distributed random shifts in HSV " "color space, assuming [0 1] pixel-value range."), ) aug_hsv_h = utils.forms.FloatField( 'Hue', default=0.02, validators=[ validators.NumberRange(min=0, max=0.5) ], tooltip=("Standard deviation of a shift that will be performed during " "preprocessing, assuming [0 1] pixel-value range.") ) aug_hsv_s = utils.forms.FloatField( 'Saturation', default=0.04, validators=[ validators.NumberRange(min=0, max=0.5) ], tooltip=("Standard deviation of a shift that will be performed during " "preprocessing, assuming [0 1] pixel-value range.") ) aug_hsv_v = utils.forms.FloatField( 'Value', default=0.06, validators=[ validators.NumberRange(min=0, max=0.5) ], tooltip=("Standard deviation of a shift that will be performed during " "preprocessing, assuming [0 1] pixel-value range.") )
Deepomatic/DIGITS
digits/model/images/forms.py
Python
bsd-3-clause
3,851
$(document).ready(function(){ $('.service-wrapper img').hover( function(){ $(this).animate({'width':'100px'}); //$(this).next().css({'display':'none'}); }, function(){ $(this).animate({'width':'50px'}); //$(this).next().css({'display':'block'}); } ); /* $('.service-wrapper').hover(function () { $(this).css({'background':'red'}); })*/ }); /*$(document).ready(function(){ $('img').hover( function(){ $(this).animate({'width':'100px'}); //$(this).next().css({'display':'none'}); }, function(){ $(this).animate({'width':'50px'}); //$(this).next().css({'display':'block'}); } ); })*/
agent115/test2
web/js/js.js
JavaScript
bsd-3-clause
824
<?php use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use app\assets\AppAsset; use app\widgets\Alert; /* @var $this \yii\web\View */ /* @var $content string */ AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class="wrap"> <?php /* NavBar::begin([ 'brandLabel' => 'My Company', 'brandUrl' => Yii::$app->homeUrl, 'options' => [ 'class' => 'navbar-default navbar-fixed-top', ], ]); // everyone can see Home page $menuItems[] = ['label' => 'Home', 'url' => ['/site/index']]; // we do not need to display About and Contact pages to admins if (!Yii::$app->user->can('admin')) { $menuItems[] = ['label' => 'About', 'url' => ['/site/about']]; $menuItems[] = ['label' => 'Contact', 'url' => ['/site/contact']]; } // display Users to admin+ roles if (Yii::$app->user->can('admin')) { $menuItems[] = ['label' => 'Users', 'url' => ['/user/index']]; } // display Signup and Login pages to guests of the site if (Yii::$app->user->isGuest) { $menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']]; $menuItems[] = ['label' => 'Login', 'url' => ['/site/login']]; } // display Logout to all logged in users else { $menuItems[] = [ 'label' => 'Logout (' . Yii::$app->user->identity->username . ')', 'url' => ['/site/logout'], 'linkOptions' => ['data-method' => 'post'] ]; } echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-right'], 'items' => $menuItems, ]); NavBar::end(); */ ?> <div class="container"> <?= Breadcrumbs::widget([ 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ]) ?> <?= Alert::widget() ?> <?= $content ?> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-left">&copy; My Company <?= date('Y') ?></p> <p class="pull-right"><?= Yii::powered() ?></p> </div> </footer> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?>
inCodeSpace/zivkY2test1
_protected/views/layouts/main.php
PHP
bsd-3-clause
2,946
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\Country */ $this->title = Yii::t('app', 'Update {modelClass}: ', [ 'modelClass' => 'Country', ]) . $model->content->val; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Countries'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = Yii::t('app', 'Update'); ?> <div class="country-update"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
garytopor/test2
backend/views/country/update.php
PHP
bsd-3-clause
623
/* * Copyright (c) 2011 Alex Fort * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Schemin.Primitives.VectorOperations { using Schemin.Evaluate; using Schemin.AST; public class VectorFill : Primitive { public override IScheminType Execute(Environment env, Evaluator eval, ScheminPair args) { ScheminVector vec = (ScheminVector) args.Car; IScheminType fill = args.ListCdr().Car; for (int i = 0; i < vec.List.Count; i++) { vec.List[i] = fill; } return new ScheminPair(); } public override void CheckArguments(ScheminPair args) { IScheminType first = args.Car; if (args.Length != 2) { throw new BadArgumentsException("expected 2 arguments"); } if ((first as ScheminVector) == null) { throw new BadArgumentsException("first argument must be a vector"); } return; } } }
imphasing/schemin
src/Schemin/Schemin.Primitives/Schemin.Primitives.VectorOperations/VectorFill.cs
C#
bsd-3-clause
2,241
from setuptools import setup, find_packages import os # The version of the wrapped library is the starting point for the # version number of the python package. # In bugfix releases of the python package, add a '-' suffix and an # incrementing integer. # For example, a packaging bugfix release version 1.4.4 of the # js.jquery package would be version 1.4.4-1 . version = '0.9.7rt' def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() long_description = ( read('README.txt') + '\n' + read('js', 'chosen', 'test_chosen.txt') + '\n' + read('CHANGES.txt')) setup( name='js.chosen', version=version, description="Fanstatic packaging of Chosen", long_description=long_description, classifiers=[], keywords='', author='Fanstatic Developers', author_email='fanstatic@googlegroups.com', license='BSD', packages=find_packages(),namespace_packages=['js'], include_package_data=True, zip_safe=False, install_requires=[ 'fanstatic', 'js.jquery', 'setuptools', ], entry_points={ 'fanstatic.libraries': [ 'chosen = js.chosen:library', ], }, )
mmariani/js.chosen
setup.py
Python
bsd-3-clause
1,226
/* * Copyright (c) 2010-2013 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of dyn4j nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j.collision.broadphase; import java.util.List; import org.dyn4j.collision.Collidable; import org.dyn4j.collision.narrowphase.NarrowphaseDetector; import org.dyn4j.geometry.AABB; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.Ray; import org.dyn4j.geometry.Shape; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; /** * Represents a broad-phase collision detection algorithm. * <p> * A {@link BroadphaseDetector} should quickly determine the pairs of {@link Collidable}s that * possibly intersect. These algorithms are used to filter out collision pairs in the interest * of sending less pairs to the {@link NarrowphaseDetector}. * <p> * {@link BroadphaseDetector}s require that the collidables are updated via the {@link #update(Collidable)} * method when the collidables move, rotate, or are changed in anyway that changes their AABB. * <p> * {@link BroadphaseDetector}s use a expansion value to expand the AABB of a collidable. The {@link #getAABB(Collidable)} * returns the expanded {@link AABB}. This expansion is used to reduce the number of updates to the * broadphase. See the {@link #setAABBExpansion(double)} for more details on this value. * <p> * The {@link #detect()}, {@link #detect(AABB)}, {@link #raycast(Ray, double)} methods use the current state of * all the collidables that have been added. Make sure that all changes have been reflected to the broadphase * using the {@link #update(Collidable)} method before calling these methods. * <p> * The {@link #detect(Collidable, Collidable)} and {@link #detect(Convex, Transform, Convex, Transform)} methods do not * use the current state of the broadphase. * @author William Bittle * @version 3.1.0 * @since 1.0.0 * @param <E> the {@link Collidable} type */ public interface BroadphaseDetector<E extends Collidable> { /** The default {@link AABB} expansion value */ public static final double DEFAULT_AABB_EXPANSION = 0.2; /** * Adds a new {@link Collidable} to the broadphase. * @param collidable the {@link Collidable} * @since 3.0.0 */ public void add(E collidable); /** * Removes the given {@link Collidable} from the broadphase. * @param collidable the {@link Collidable} * @since 3.0.0 */ public void remove(E collidable); /** * Updates the given {@link Collidable}. * <p> * Used when the collidable has moved or rotated. * @param collidable the {@link Collidable} * @since 3.0.0 */ public void update(E collidable); /** * Clears all {@link Collidable}s from the broadphase. * @since 3.0.0 */ public void clear(); /** * Returns the expanded {@link AABB} for a given {@link Collidable}. * <p> * Returns null if the collidable has not been added to this * broadphase detector. * @param collidable the {@link Collidable} * @return {@link AABB} the {@link AABB} for the given {@link Collidable} */ public AABB getAABB(E collidable); /** * Performs collision detection on all {@link Collidable}s that have been added to * this {@link BroadphaseDetector}. * @return List&lt;{@link BroadphasePair}&gt; * @since 3.0.0 */ public List<BroadphasePair<E>> detect(); /** * Performs a broadphase collision test using the given {@link AABB}. * @param aabb the {@link AABB} to test * @return List list of all {@link AABB}s that overlap with the given {@link AABB} * @since 3.0.0 */ public List<E> detect(AABB aabb); /** * Performs a preliminary raycast over all the collidables in the broadphase to improve performance of the * narrowphase raycasts. * @param ray the {@link Ray} * @param length the length of the ray; 0.0 for infinite length * @return List the filtered list of possible collidables * @since 3.0.0 */ public abstract List<E> raycast(Ray ray, double length); /** * Performs a broadphase collision test on the given {@link Collidable}s and * returns true if they could possibly intersect. * @param a the first {@link Collidable} * @param b the second {@link Collidable} * @return boolean */ public abstract boolean detect(E a, E b); /** * Performs a broadphase collision test on the given {@link Convex} {@link Shape}s and * returns true if they could possibly intersect. * <p> * This method does not use the expansion value. * @param convex1 the first {@link Convex} {@link Shape} * @param transform1 the first {@link Convex} {@link Shape}'s {@link Transform} * @param convex2 the second {@link Convex} {@link Shape} * @param transform2 the second {@link Convex} {@link Shape}'s {@link Transform} * @return boolean */ public abstract boolean detect(Convex convex1, Transform transform1, Convex convex2, Transform transform2); /** * Returns the {@link AABB} expansion value used to improve performance of broadphase updates. * @return double */ public abstract double getAABBExpansion(); /** * Sets the {@link AABB} expansion value used to improve performance of broadphase updates. * <p> * Increasing this value will cause less updates to the broadphase but will cause more pairs * to be sent to the narrowphase. * @param expansion the expansion */ public abstract void setAABBExpansion(double expansion); /** * Translates all {@link Collidable} proxies to match the given coordinate shift. * @param shift the amount to shift along the x and y axes * @since 3.1.0 */ public abstract void shiftCoordinates(Vector2 shift); }
yuripourre/etyllica-physics
src/main/java/org/dyn4j/collision/broadphase/BroadphaseDetector.java
Java
bsd-3-clause
7,243
<?php namespace common\fixtures\helpers; interface FixtureTester { public function haveFixtures($fixtures); public function grabFixture($name, $index = null); public function seeRecord(string $class, array $array); /** * @param string $className * @param array $attributes * @return mixed */ public function haveRecord(string $className, array $attributes); }
edzima/VestraTele
common/fixtures/helpers/FixtureTester.php
PHP
bsd-3-clause
380
"""myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
greven/vagrant-django
project_name/urls.py
Python
bsd-3-clause
993
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Ldap * @subpackage Filter * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Filter.php 23775 2011-03-01 17:25:24Z ralph $ */ /** * @see Zend_Ldap_Filter_String */ // require_once 'Zend/Ldap/Filter/String.php'; /** * Zend_Ldap_Filter. * * @category Zend * @package Zend_Ldap * @subpackage Filter * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Ldap_Filter extends Zend_Ldap_Filter_String { const TYPE_EQUALS = '='; const TYPE_GREATER = '>'; const TYPE_GREATEROREQUAL = '>='; const TYPE_LESS = '<'; const TYPE_LESSOREQUAL = '<='; const TYPE_APPROX = '~='; /** * Creates an 'equals' filter. * (attr=value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function equals($attr, $value) { return new self($attr, $value, self::TYPE_EQUALS, null, null); } /** * Creates a 'begins with' filter. * (attr=value*) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function begins($attr, $value) { return new self($attr, $value, self::TYPE_EQUALS, null, '*'); } /** * Creates an 'ends with' filter. * (attr=*value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function ends($attr, $value) { return new self($attr, $value, self::TYPE_EQUALS, '*', null); } /** * Creates a 'contains' filter. * (attr=*value*) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function contains($attr, $value) { return new self($attr, $value, self::TYPE_EQUALS, '*', '*'); } /** * Creates a 'greater' filter. * (attr>value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function greater($attr, $value) { return new self($attr, $value, self::TYPE_GREATER, null, null); } /** * Creates a 'greater or equal' filter. * (attr>=value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function greaterOrEqual($attr, $value) { return new self($attr, $value, self::TYPE_GREATEROREQUAL, null, null); } /** * Creates a 'less' filter. * (attr<value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function less($attr, $value) { return new self($attr, $value, self::TYPE_LESS, null, null); } /** * Creates an 'less or equal' filter. * (attr<=value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function lessOrEqual($attr, $value) { return new self($attr, $value, self::TYPE_LESSOREQUAL, null, null); } /** * Creates an 'approx' filter. * (attr~=value) * * @param string $attr * @param string $value * @return Zend_Ldap_Filter */ public static function approx($attr, $value) { return new self($attr, $value, self::TYPE_APPROX, null, null); } /** * Creates an 'any' filter. * (attr=*) * * @param string $attr * @return Zend_Ldap_Filter */ public static function any($attr) { return new self($attr, '', self::TYPE_EQUALS, '*', null); } /** * Creates a simple custom string filter. * * @param string $filter * @return Zend_Ldap_Filter_String */ public static function string($filter) { return new Zend_Ldap_Filter_String($filter); } /** * Creates a simple string filter to be used with a mask. * * @param string $mask * @param string $value * @return Zend_Ldap_Filter_Mask */ public static function mask($mask, $value) { /** * Zend_Ldap_Filter_Mask */ // require_once 'Zend/Ldap/Filter/Mask.php'; return new Zend_Ldap_Filter_Mask($mask, $value); } /** * Creates an 'and' filter. * * @param Zend_Ldap_Filter_Abstract $filter,... * @return Zend_Ldap_Filter_And */ public static function andFilter($filter) { /** * Zend_Ldap_Filter_And */ // require_once 'Zend/Ldap/Filter/And.php'; return new Zend_Ldap_Filter_And(func_get_args()); } /** * Creates an 'or' filter. * * @param Zend_Ldap_Filter_Abstract $filter,... * @return Zend_Ldap_Filter_Or */ public static function orFilter($filter) { /** * Zend_Ldap_Filter_Or */ // require_once 'Zend/Ldap/Filter/Or.php'; return new Zend_Ldap_Filter_Or(func_get_args()); } /** * Create a filter string. * * @param string $attr * @param string $value * @param string $filtertype * @param string $prepend * @param string $append * @return string */ private static function _createFilterString($attr, $value, $filtertype, $prepend = null, $append = null) { $str = $attr . $filtertype; if ($prepend !== null) $str .= $prepend; $str .= self::escapeValue($value); if ($append !== null) $str .= $append; return $str; } /** * Creates a new Zend_Ldap_Filter. * * @param string $attr * @param string $value * @param string $filtertype * @param string $prepend * @param string $append */ public function __construct($attr, $value, $filtertype, $prepend = null, $append = null) { $filter = self::_createFilterString($attr, $value, $filtertype, $prepend, $append); parent::__construct($filter); } }
Chatventure/zf1
library/Zend/Ldap/Filter.php
PHP
bsd-3-clause
6,747
package com.groupon.lex.metrics; import java.util.Collection; import static java.util.Collections.singleton; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; public abstract class SynchronousGroupGenerator implements GroupGenerator { protected abstract Collection<? extends MetricGroup> getGroups(CompletableFuture<TimeoutObject> timeout); @Override public final Collection<CompletableFuture<? extends Collection<? extends MetricGroup>>> getGroups(Executor threadpool, CompletableFuture<TimeoutObject> timeout) throws Exception { CompletableFuture<Collection<? extends MetricGroup>> result = CompletableFuture.supplyAsync(() -> getGroups(timeout), threadpool); timeout.thenAccept(timeoutObject -> { result.cancel(true); }); return singleton(result); } }
groupon/monsoon
intf/src/main/java/com/groupon/lex/metrics/SynchronousGroupGenerator.java
Java
bsd-3-clause
853
package drum import ( "fmt" "os" ) // DecodeFile decodes the drum machine file found at the provided path // and returns a pointer to a parsed pattern which is the entry point to the // rest of the data. func DecodeFile(path string) (*Pattern, error) { f, err := os.Open(path) if err != nil { return nil, err } var p *Pattern if p, err = decode(f); err != nil { return nil, err } return p, f.Close() } // Pattern is the high level representation of the // drum pattern contained in a .splice file. type Pattern struct { Version string Tempo float32 Tracks []Track } func (p Pattern) String() string { s := fmt.Sprintln("Saved with HW Version:", p.Version) // s += fmt.Sprintln("Len:", p.Len) s += fmt.Sprintln("Tempo:", p.Tempo) for _, t := range p.Tracks { s += fmt.Sprint(t) } return s }
GoChallenge/GCSolutions
march15/normal/henry-bubert/decoder.go
GO
bsd-3-clause
823
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; using System.ComponentModel; using System.IO; namespace UrlTouch.CommandLineParsing { /// <summary> /// Converter that can convert from a string to a FileInfo. /// </summary> public class FileInfoConverter : TypeConverter { /// <summary> /// Converts from a string to a FileInfo. /// </summary> /// <param name="context">Context.</param> /// <param name="culture">Culture.</param> /// <param name="value">Value to convert.</param> /// <returns>FileInfo, or null if value was null or non-string.</returns> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string && value != null) { return new FileInfo((string)value); } else { return null; } } /// <summary> /// Returns whether this converter can convert an object of the given type to a FileInfo. /// </summary> /// <param name="context">An ITypeDescriptorContext that provides a format context.</param> /// <param name="sourceType">A Type that represents the type you want to convert from.</param> /// <returns>True if this converter can perform the conversion; otherwise, False.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return (sourceType == typeof(string)); } /// <summary> /// Converts from a FileInfo to a string. /// </summary> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (value is FileInfo && destinationType == typeof(string)) { return ((FileInfo)value).FullName; } else { return null; } } /// <summary> /// Returns whether this converter can convert a FileInfo object to the specified type. /// </summary> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType == typeof(string)); } } }
slav/UrlTouch
src/UrlTouch/CommandLineParsing/FileInfoConverter.cs
C#
bsd-3-clause
2,655
Spree::UsersController.class_eval do include Spree::MailChimpSync::Sync end
coupling/spree_mailchimp
app/controllers/spree/users_controller_decorator.rb
Ruby
bsd-3-clause
77
<?php /* @var $this yii\web\View */ /* @var $user common\models\User */ $resetLink = Yii::$app->urlManager->createAbsoluteUrl(['/user/reset-password/process', 'token' => $user->password_reset_token]); ?> Hello <?= $user->username ?>, Follow the link below to reset your password: <?= $resetLink ?>
nicovicz/portalctv
mail/passwordResetToken-text.php
PHP
bsd-3-clause
300
__author__ = 'Cedric Da Costa Faro' from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(405) def method_not_allowed(e): return render_template('405.html'), 405 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500
cdcf/time_tracker
app/main/errors.py
Python
bsd-3-clause
392
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 28.08.2015 */ use yii\db\Schema; use yii\db\Migration; class m150923_133220_create_table__cms_tree_image extends Migration { public function safeUp() { $tableExist = $this->db->getTableSchema("{{%cms_tree_image}}", true); if ($tableExist) { return true; } $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'; } $this->createTable("{{%cms_tree_image}}", [ 'id' => $this->primaryKey(), 'created_by' => $this->integer(), 'updated_by' => $this->integer(), 'created_at' => $this->integer(), 'updated_at' => $this->integer(), 'storage_file_id' => $this->integer()->notNull(), 'tree_id' => $this->integer()->notNull(), 'priority' => $this->integer()->notNull()->defaultValue(100), ], $tableOptions); $this->createIndex('updated_by', '{{%cms_tree_image}}', 'updated_by'); $this->createIndex('created_by', '{{%cms_tree_image}}', 'created_by'); $this->createIndex('created_at', '{{%cms_tree_image}}', 'created_at'); $this->createIndex('updated_at', '{{%cms_tree_image}}', 'updated_at'); $this->createIndex('storage_file_id', '{{%cms_tree_image}}', 'storage_file_id'); $this->createIndex('tree_id', '{{%cms_tree_image}}', 'tree_id'); $this->createIndex('priority', '{{%cms_tree_image}}', 'priority'); $this->createIndex('storage_file_id__tree_id', '{{%cms_tree_image}}', ['storage_file_id', 'tree_id'], true); $this->execute("ALTER TABLE {{%cms_tree_image}} COMMENT = 'Связь разделов и файлов изображений';"); $this->addForeignKey( 'cms_tree_image_created_by', "{{%cms_tree_image}}", 'created_by', '{{%cms_user}}', 'id', 'SET NULL', 'SET NULL' ); $this->addForeignKey( 'cms_tree_image_updated_by', "{{%cms_tree_image}}", 'updated_by', '{{%cms_user}}', 'id', 'SET NULL', 'SET NULL' ); $this->addForeignKey( 'cms_tree_image__storage_file_id', "{{%cms_tree_image}}", 'storage_file_id', '{{%cms_storage_file}}', 'id', 'CASCADE', 'CASCADE' ); $this->addForeignKey( 'cms_tree_image__tree_id', "{{%cms_tree_image}}", 'tree_id', '{{%cms_tree}}', 'id', 'CASCADE', 'CASCADE' ); } public function safeDown() { $this->dropForeignKey("cms_tree_image_updated_by", "{{%cms_tree_image}}"); $this->dropForeignKey("cms_tree_image_updated_by", "{{%cms_tree_image}}"); $this->dropForeignKey("cms_tree_image__storage_file_id", "{{%cms_tree_image}}"); $this->dropForeignKey("cms_tree_image__tree_id", "{{%cms_tree_image}}"); $this->dropTable("{{%cms_tree_image}}"); } }
skeeks-cms/cms
src/migrations/v3/m150923_133220_create_table__cms_tree_image.php
PHP
bsd-3-clause
3,191
<?php /* Copyright (c) 2012, Silvercore Dev. (www.silvercoredev.com) Todos os direitos reservados. Ver o arquivo licenca.txt na raiz do BlackbirdIS para mais detalhes. */ // Carrega as configurações include("settings.php"); // Se não existir usuário e senha no arquivo settings.php, redirecionar para install.php if (!isset($user) || !isset($password)) { header("Location: install.php"); die(); } // Impede o acesso caso o arquivo install.php exista if (file_exists("install.php")) { die("<!DOCTYPE html><html><head><title>BlackbirdIS</title><meta charset=\"utf-8\" /></head><body>É necessário deletar o arquivo install.php antes de continuar.</body></html>"); } // Se o usuário já estiver logado, redirecionar para a página de administração session_start(); if (isset($_SESSION["bis"])) { if ($_SESSION["bis"] == 1) { header("Location: admin.php"); die(); } } // Impede o acesso caso a opção "Desativar painel de administração após três tentativas de login consecutivas" esteja ativada // e o número máximo de tentativas de login excedido. if ($dof == "on" && $lcounter == 3) { die("<!DOCTYPE html><html><head><title>BlackbirdIS</title><meta charset=\"utf-8\" /></head><body>Número máximo de tentativas de login excedido. O painel de administração foi desativado. Para reativar, altere o valor da variável \$lcounter no arquivo settings.php para 0. Em caso de dúvidas, consulte a <a href='http://www.silvercoredev.com/blackbird/documentacao/'>documentação</a>.</body></html>"); } // Se o usuário e senha estiverem corretos, reinicia o contador de tentativas de login e continua para admin.php // Caso contrário, aumenta o contador de tentativas de login e coloca mensagem de erro na variável $errormsg if (isset($_POST['tuser']) && isset($_POST['tpassword'])) { $tuser = $_POST['tuser']; $tpassword = $_POST['tpassword']; if (sha1($tuser) == $user && sha1($tpassword) == $password) { session_regenerate_id(TRUE); $_SESSION["bis"] = 1; $new_lcounter = 0; $settings = file_get_contents("settings.php"); $settings = str_replace("\$lcounter = " . $lcounter, "\$lcounter = " . $new_lcounter, $settings); file_put_contents("settings.php", $settings); header("Location: admin.php"); } else { $errormsg = "Erro: usuário ou senha incorretos."; $new_lcounter = $lcounter + 1; $settings = file_get_contents("settings.php"); $settings = str_replace("\$lcounter = " . $lcounter, "\$lcounter = " . $new_lcounter, $settings); file_put_contents("settings.php", $settings); if ($new_lcounter == 3) { header("Location: index.php"); } } } ?> <!DOCTYPE html> <html> <head> <title>BlackbirdIS</title> <meta charset="utf-8" /> <link href="../css/style.css" rel="stylesheet" type="text/css"> <link href="css/style.css" rel="stylesheet" type="text/css"> </head> <body> <div id="bar"> Administração </div> <div id="main" style="text-align:center"> <?php // Se a variável $errormsg existir, mostra a mensagem de erro if (isset($errormsg)) { echo($errormsg); } ?> <form action="index.php" method="post"> Login<br /> <input type="text" name="tuser" class="seinput" /><br /><br /> Senha<br /> <input type="password" name="tpassword" class="seinput" /><br /><br /> <input type="submit" value="Continuar" class="b1" /> </form> </div> </body> </html>
silvercoredev/BlackbirdIS
1.0/src/BlackbirdIS/admin/index.php
PHP
bsd-3-clause
3,696
(function () { 'use strict'; var directives = angular.module('data-services.directives', []), relationshipFormatter = function(cellValue, options, rowObject) { var i, result = '', field; for (i = 0; i < rowObject.fields.length; i += 1) { if (rowObject.fields[i].name === options.colModel.name) { field = rowObject.fields[i]; break; } } if (field && field.displayValue) { if (typeof(field.displayValue) === 'string' || field.displayValue instanceof String) { result = field.displayValue; } else { angular.forEach(field.displayValue, function (value, key) { if (key) { result = result.concat(value, ", "); } }, result); if (result) { result = result.slice(0, -2); } } } return result; }, textFormatter = function (cellValue, options, rowObject) { var val = cellValue, TEXT_LENGTH_LIMIT = 40; //limit of characters for display in jqgrid instances if field type is textarea if (cellValue !== null && cellValue !== undefined && cellValue.length > TEXT_LENGTH_LIMIT) { val = cellValue.substring(0, TEXT_LENGTH_LIMIT); val = val + '...'; } return val; }, idFormatter = function (cellValue, options, rowObject) { var val = cellValue; if (cellValue !== undefined && !isNaN(cellValue) && parseInt(cellValue, 10) < 0) { val = ''; } return val; }, stringEscapeFormatter = function (cellValue, options, rowObject) { var val = ''; val = _.escape(cellValue); return val; }, mapFormatter = function (cellValue, options, rowObject) { var result = '', val = cellValue, STRING_LENGTH_LIMIT = 20; //limit of characters for display in jqgrid instances if field type is map angular.forEach(cellValue, function (value, key) { if (key) { if (key.length > STRING_LENGTH_LIMIT) { key = key.substring(0, STRING_LENGTH_LIMIT); key = key + '...'; } if (value && value.length > STRING_LENGTH_LIMIT) { value = value.substring(0, STRING_LENGTH_LIMIT); value = value + '...'; } result = result.concat(key, ' : ', value,'\n'); } }, result); return result; }; function findCurrentScope(startScope, functionName) { var parent = startScope; while (!parent[functionName]) { parent = parent.$parent; } return parent; } /* * This function checks if the field name is reserved for jqgrid (subgrid, cb, rn) * and if true temporarily changes that name. */ function changeIfReservedFieldName(fieldName) { if (fieldName === 'cb' || fieldName === 'rn' || fieldName === 'subgrid') { return fieldName + '___'; } else { return fieldName; } } /* * This function checks if the field name was changed * and if true changes this name to the original. */ function backToReservedFieldName(fieldName) { if (fieldName === 'cb___' || fieldName === 'rn___' || fieldName === 'subgrid___') { var fieldNameLength = fieldName.length; return fieldName.substring(0, fieldNameLength - 3); } else { return fieldName; } } /* * This function calculates width parameters * for fit jqGrid on the screen. */ function resizeGridWidth(gridId) { var intervalWidthResize, tableWidth; clearInterval(intervalWidthResize); intervalWidthResize = setInterval( function () { tableWidth = $('#gbox_' + gridId).parent().width(); $('#' + gridId).jqGrid("setGridWidth", tableWidth); clearInterval(intervalWidthResize); }, 200); } /* * This function calculates height parameters * for fit jqGrid on the screen. */ function resizeGridHeight(gridId) { var intervalHeightResize, gap, tableHeight; clearInterval(intervalHeightResize); intervalHeightResize = setInterval( function () { if ($('.overrideJqgridTable').offset() !== undefined) { gap = 1 + $('.overrideJqgridTable').offset().top - $('.inner-center .ui-layout-content').offset().top; tableHeight = Math.floor($('.inner-center .ui-layout-content').height() - gap - $('.ui-jqgrid-pager').outerHeight() - $('.ui-jqgrid-hdiv').outerHeight()); $('#' + gridId).jqGrid("setGridHeight", tableHeight); resizeGridWidth(gridId); } clearInterval(intervalHeightResize); }, 250); } /* * This function checks grid width * and increase this width if possible. */ function resizeIfNarrow(gridId) { var intervalIfNarrowResize; setTimeout(function() { clearInterval(intervalIfNarrowResize); }, 950); intervalIfNarrowResize = setInterval( function () { if (($('#' + gridId).jqGrid('getGridParam', 'width') - 20) > $('#gbox_' + gridId + ' .ui-jqgrid-btable').width()) { $('#' + gridId).jqGrid('setGridWidth', ($('#' + gridId).jqGrid('getGridParam', 'width') - 4), true); $('#' + gridId).jqGrid('setGridWidth', $('#inner-center.inner-center').width() - 2, false); } }, 550); } /* * This function checks the name of field * whether is selected for display in the jqGrid */ function isSelectedField(name, selectedFields) { var i; if (selectedFields) { for (i = 0; i < selectedFields.length; i += 1) { if (name === selectedFields[i].basic.name) { return true; } } } return false; } function handleGridPagination(pgButton, pager, scope) { var newPage = 1, last, newSize; if ("user" === pgButton) { //Handle changing page by the page input newPage = parseInt(pager.find('input:text').val(), 10); // get new page number last = parseInt($(this).getGridParam("lastpage"), 10); // get last page number if (newPage > last || newPage === 0) { // check range - if we cross range then stop return 'stop'; } } else if ("records" === pgButton) { //Page size change, we must update scope value to avoid wrong page size in the trash screen newSize = parseInt(pager.find('select')[0].value, 10); scope.entityAdvanced.userPreferences.gridRowsNumber = newSize; } } function buildGridColModel(colModel, fields, scope, removeVersionField, ignoreHideFields) { var i, j, cmd, field, skip = false, widthTable; widthTable = scope.getColumnsWidth(); for (i = 0; i < fields.length; i += 1) { field = fields[i]; skip = false; // for history and trash we don't generate version field if (removeVersionField && field.metadata !== undefined && field.metadata.length > 0) { for (j = 0; j < field.metadata.length; j += 1) { if (field.metadata[j].key === "version.field" && field.metadata[j].value === "true") { skip = true; break; } } } if (!skip && !field.nonDisplayable) { //if name is reserved for jqgrid need to change field name field.basic.name = changeIfReservedFieldName(field.basic.name); cmd = { label: field.basic.displayName, name: field.basic.name, index: field.basic.name, jsonmap: "fields." + i + ".value", width: widthTable[field.basic.name]? widthTable[field.basic.name] : 220, hidden: ignoreHideFields? false : !isSelectedField(field.basic.name, scope.selectedFields) }; cmd.formatter = stringEscapeFormatter; if (scope.isDateField(field)) { cmd.formatter = 'date'; cmd.formatoptions = { newformat: 'Y-m-d'}; } if (scope.isRelationshipField(field)) { // append a formatter for relationships cmd.formatter = relationshipFormatter; cmd.sortable = false; } if (field.basic.name === 'id') { cmd.formatter = idFormatter; } if (scope.isTextArea(field.settings)) { cmd.formatter = textFormatter; cmd.classes = 'text'; } if (scope.isMapField(field)) { cmd.formatter = mapFormatter; cmd.sortable = false; } if (scope.isComboboxField(field)) { cmd.jsonmap = "fields." + i + ".displayValue"; if (scope.isMultiSelectCombobox(field)) { cmd.sortable = false; } } colModel.push(cmd); } } } /* * This function checks if the next column is last of the jqgrid. */ function isLastNextColumn(colModel, index) { var result; $.each(colModel, function (i, val) { if ((index + 1) < i) { if (colModel[i].hidden !== false) { result = true; } else { result = false; } } return (result); }); return result; } function handleColumnResize(tableName, gridId, index, width, scope) { var tableWidth, widthNew, widthOrg, colModel = $('#' + gridId).jqGrid('getGridParam','colModel'); if (colModel.length - 1 === index + 1 || (colModel[index + 1] !== undefined && isLastNextColumn(colModel, index))) { widthOrg = colModel[index].widthOrg; if (Math.floor(width) > Math.floor(widthOrg)) { widthNew = colModel[index + 1].width + Math.floor(width - widthOrg); colModel[index + 1].width = widthNew; scope.saveColumnWidth(colModel[index + 1].index, widthNew); $('.ui-jqgrid-labels > th:eq('+(index + 1)+')').css('width', widthNew); $('#' + gridId + ' .jqgfirstrow > td:eq('+(index + 1)+')').css('width', widthNew); } colModel[index].widthOrg = width; } scope.saveColumnWidth(colModel[index].index, width); tableWidth = $(tableName).width(); $('#' + gridId).jqGrid("setGridWidth", tableWidth); } /* * This function expand input field if string length is long and when the cursor is focused on the text box, * and go back to default size when move out cursor */ directives.directive('extendInput', function($timeout) { return { restrict : 'A', link : function(scope, element, attr) { var elem = angular.element(element), width = 210, duration = 300, extraWidth = 550, height = 22, elemValue, lines, eventTimer; function extendInput(elemInput, event) { elemValue = elemInput[0].value; lines = elemValue.split("\n"); if (20 <= elemValue.length || lines.length > 1 || event.keyCode === 13) { //if more than 20 characters or more than 1 line duration = (event.type !== "keyup") ? 300 : 30; if (lines.length < 10) { height = 34; } else { height = 24; } elemInput.animate({ width: extraWidth, height: height * lines.length, overflow: 'auto' }, duration); } } elem.on({ 'focusout': function (e) { clearTimeout(eventTimer); eventTimer = setTimeout( function() { elem.animate({ width: width, height: 34, overflow: 'hidden' }, duration); }, 100); }, 'focus': function (e) { clearTimeout(eventTimer); extendInput($(this), e); }, 'keyup': function (e) { extendInput($(this), e); } }); } }; }); /** * Bring focus on input-box while opening the new entity box */ directives.directive('focusmodal', function() { return { restrict : 'A', link : function(scope, element, attr) { var elem = angular.element(element); elem.on({ 'shown.bs.modal': function () { elem.find('#inputEntityName').focus(); } }); } }; }); /** * Show/hide details about a field by clicking on caret icon in the first column in * the field table. */ directives.directive('mdsExpandAccordion', function () { return { restrict: 'A', link: function (scope, element) { var target = angular.element($('#entityFieldsLists')); target.on('show.bs.collapse', function (e) { $(e.target).siblings('.panel-heading').find('i.fa-caret-right') .removeClass('fa-caret-right') .addClass('fa-caret-down'); }); target.on('hide.bs.collapse', function (e) { $(e.target).siblings('.panel-heading').find('i.fa-caret-down') .removeClass('fa-caret-down') .addClass('fa-caret-right'); }); } }; }); directives.directive('mdsHeaderAccordion', function () { return { restrict: 'A', link: function (scope, element) { var elem = angular.element(element), target = elem.find(".panel-collapse"); target.on({ 'show.bs.collapse': function () { elem.find('.panel-icon') .removeClass('fa-caret-right') .addClass('fa-caret-down'); }, 'hide.bs.collapse': function () { elem.find('.panel-icon') .removeClass('fa-caret-down') .addClass('fa-caret-right'); } }); } }; }); /** * Ensure that if no field name has been entered it should be filled in by generating a camel * case name from the field display name. If you pass a 'new' value to this directive then it * will be check name of new field. Otherwise you have to pass a index to find a existing field. */ directives.directive('mdsCamelCase', function (MDSUtils) { return { restrict: 'A', link: function (scope, element, attrs) { angular.element(element).focusout(function () { var attrValue = attrs.mdsCamelCase, field; if (_.isEqual(attrValue, 'new')) { field = scope.newField; } else if (_.isNumber(+attrValue)) { field = scope.fields && scope.fields[+attrValue]; } if (field && field.basic && isBlank(field.basic.name)) { scope.safeApply(function () { field.basic.name = MDSUtils.camelCase(field.basic.displayName); }); } }); } }; }); /** * Add ability to change model property mode on UI from read to write and vice versa. For this * to work there should be two tags next to each other. First tag (span, div) should present * property in the read mode. Second tag (input) should present property in the write mode. By * default property should be presented in the read mode and the second tag should be hidden. */ directives.directive('mdsEditable', function () { return { restrict: 'A', link: function (scope, element) { var elem = angular.element(element), read = elem.find('span'), write = elem.find('input'); elem.click(function (e) { e.stopPropagation(); read.hide(); write.show(); write.focus(); }); write.click(function (e) { e.stopPropagation(); }); write.focusout(function () { write.hide(); read.show(); }); } }; }); directives.directive("fileread", function () { return { scope: { fileread: "=" }, link: function (scope, element, attributes) { element.bind("change", function (changeEvent) { var reader = new FileReader(); reader.onload = function (loadEvent) { scope.$apply(function () { scope.fileread = loadEvent.target.result; }); }; if(changeEvent.target.files[0] !== undefined) { reader.readAsDataURL(changeEvent.target.files[0]); } }); } }; }); /** * Add a datetime picker to an element. */ directives.directive('mdsDatetimePicker', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var isReadOnly = scope.$eval(attr.ngReadonly); if(!isReadOnly) { angular.element(element).datetimepicker({ showTimezone: true, changeYear: true, useLocalTimezone: true, dateFormat: 'yy-mm-dd', timeFormat: 'HH:mm z', onSelect: function (dateTex) { scope.safeApply(function () { ngModel.$setViewValue(dateTex); }); }, onClose: function (year, month, inst) { var viewValue = $(this).val(); scope.safeApply(function () { ngModel.$setViewValue(viewValue); }); }, onChangeMonthYear: function (year, month, inst) { var curDate = $(this).datepicker("getDate"); if (curDate === null) { return; } if (curDate.getFullYear() !== year || curDate.getMonth() !== month - 1) { curDate.setYear(year); curDate.setMonth(month - 1); $(this).datepicker("setDate", curDate); } } }); } } }; }); /** * Add a date picker to an element. */ directives.directive('mdsDatePicker', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var isReadOnly = scope.$eval(attr.ngReadonly); if(!isReadOnly) { angular.element(element).datepicker({ changeYear: true, showButtonPanel: true, dateFormat: 'yy-mm-dd', onSelect: function (dateTex) { scope.safeApply(function () { ngModel.$setViewValue(dateTex); }); }, onClose: function (year, month, inst) { var viewValue = $(this).val(); scope.safeApply(function () { ngModel.$setViewValue(viewValue); }); }, onChangeMonthYear: function (year, month, inst) { var curDate = $(this).datepicker("getDate"); if (curDate === null) { return; } if (curDate.getFullYear() !== year || curDate.getMonth() !== month - 1) { curDate.setYear(year); curDate.setMonth(month - 1); $(this).datepicker("setDate", curDate); } } }); } } }; }); /** * Add "Item" functionality of "Connected Lists" control to the element. "Connected Lists Group" * is passed as a value of the attribute. If item is selected '.connected-list-item-selected-{group} * class is added. */ directives.directive('connectedListTargetItem', function () { return { restrict: 'A', link: function (scope, element) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), condition = jQelem.attr('condition'); if (typeof condition !== 'undefined' && condition !== false) { if (!scope.$eval(condition)){ return; } } jQelem.attr('draggable','true'); jQelem.addClass(connectWith); jQelem.addClass("target-item"); jQelem.click(function() { $(this).toggleClass("selected"); scope.$apply(); }); jQelem.dblclick(function() { var e = $(this), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], index = parseInt(e.attr('item-index'), 10), item = target[index]; e.removeClass("selected"); scope.$apply(function() { source.push(item); target.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('dragstart', function(e) { var item = $(this); item.addClass('selected'); item.fadeTo(100, 0.4); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('origin', 'target'); e.dataTransfer.setData('index', item.attr('item-index')); return false; }, false); elem.addEventListener('dragend', function(e) { var item = $(this); item.removeClass('selected'); item.fadeTo(100, 1.0); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), thisIndex = parseInt($(this).attr('item-index'), 10), source, target, item; $(this).removeClass('over'); $(this.parentNode).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'target') { // movement inside one container item = target[index]; if(thisIndex > index) { thisIndex += 1; } scope.$apply(function() { target[index] = 'null'; target.splice(thisIndex, 0, item); target.splice(target.indexOf('null'), 1); targetContainer.trigger('contentChange', [target]); }); } else if (itemOriginContainer === 'source') { item = source[index]; scope.$apply(function() { target.splice(thisIndex, 0, item); source.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); } }; }); directives.directive('connectedListSourceItem', function () { return { restrict: 'A', link: function (scope, element) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), condition = jQelem.attr('condition'); if (typeof condition !== 'undefined' && condition !== false) { if (!scope.$eval(condition)){ return; } } jQelem.attr('draggable','true'); jQelem.addClass(connectWith); jQelem.addClass("source-item"); jQelem.click(function() { $(this).toggleClass("selected"); scope.$apply(); }); jQelem.dblclick(function() { var e = $(this), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], index = parseInt(e.attr('item-index'), 10), item = source[index]; e.removeClass("selected"); scope.$apply(function() { target.push(item); source.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); return false; }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('dragstart', function(e) { var item = $(this); item.addClass('selected'); item.fadeTo(100, 0.4); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('origin', 'source'); e.dataTransfer.setData('index', item.attr('item-index')); return false; }, false); elem.addEventListener('dragend', function(e) { var item = $(this); item.removeClass('selected'); item.fadeTo(100, 1.0); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), thisIndex = parseInt($(this).attr('item-index'), 10), source, target, item; $(this).removeClass('over'); $(this.parentNode).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'source') { // movement inside one container item = source[index]; if(thisIndex > index) { thisIndex += 1; } scope.$apply(function() { source[index] = 'null'; source.splice(thisIndex, 0, item); source.splice(source.indexOf('null'), 1); sourceContainer.trigger('contentChange', [source]); }); } else if (itemOriginContainer === 'target') { item = target[index]; scope.$apply(function() { source.splice(thisIndex, 0, item); target.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); } }; }); /** * Add "Source List" functionality of "Connected Lists" control to the element (container). * "Connected Lists Group" is passed as a value of the attribute. "onItemsAdd", "onItemsRemove" * and "onItemMove" callback functions are registered to handle items adding/removing/sorting. */ directives.directive('connectedListSource', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), onContentChange = jQelem.attr('on-content-change'); jQelem.addClass('connected-list-source'); jQelem.addClass(connectWith); if(typeof scope[onContentChange] === typeof Function) { jQelem.on('contentChange', function(e, content) { scope[onContentChange](content); }); } elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); return false; }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), source, target, item; $(this).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'source') { // movement inside one container item = source[index]; scope.$apply(function() { source.splice(index, 1); source.push(item); sourceContainer.trigger('contentChange', [source]); }); } else if (itemOriginContainer === 'target') { item = target[index]; scope.$apply(function() { source.push(item); target.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); jQelem.keyup(function(event) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = sourceContainer.children('.selected'), selectedIndices = [], selectedItems = [], array = []; if(event.which === 13) { selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = source[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { source.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { target.push(item); }); angular.forEach(target, function (item) { array.push(item.id); }); viewScope.draft({ edit: true, values: { path: attr.mdsPath, advanced: true, value: [array] } }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } }); } }; }); /** * Add "Target List" functionality of "Connected Lists" control to the element (container). * "Connected Lists Group" is passed as a value of the attribute. "onItemsAdd", "onItemsRemove" * and "onItemMove" callback functions are registered to handle items adding/removing/sorting. */ directives.directive('connectedListTarget', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), onContentChange = jQelem.attr('on-content-change'); jQelem.addClass('connected-list-target'); jQelem.addClass(connectWith); if(typeof scope[onContentChange] === typeof Function) { jQelem.on('contentChange', function(e, content) { scope[onContentChange](content); }); } elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); return false; }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), source, target, item; $(this).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'target') { // movement inside one container item = target[index]; scope.$apply(function() { target.splice(index, 1); target.push(item); targetContainer.trigger('contentChange', [target]); }); } else if (itemOriginContainer === 'source') { item = source[index]; scope.$apply(function() { target.push(item); source.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); jQelem.keyup(function(event) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = targetContainer.children('.selected'), selectedIndices = [], selectedItems = [], array = []; if(event.which === 13) { selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = target[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { target.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { source.push(item); }); angular.forEach(target, function (item) { array.push(item.id); }); viewScope.draft({ edit: true, values: { path: attr.mdsPath, advanced: true, value: [array] } }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } }); } }; }); /** * Add "Move selected to target" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnTo', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = sourceContainer.children('.selected'), selectedIndices = [], selectedItems = []; selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = source[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { source.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { target.push(item); }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); angular.element(element).disableSelection(); } }; }); /** * Add "Move all to target" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnToAll', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedItems = sourceContainer.children(), viewScope = findCurrentScope(scope, 'draft'); scope.safeApply(function () { angular.forEach(source, function(item) { target.push(item); }); source.length = 0; sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); } }; }); /** * Add "Move selected to source" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnFrom', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = targetContainer.children('.selected'), selectedIndices = [], selectedItems = []; selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = target[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { target.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { source.push(item); }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); } }; }); /** * Add "Move all to source" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnFromAll', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], viewScope = findCurrentScope(scope, 'draft'), selectedItems = targetContainer.children(); scope.safeApply(function () { angular.forEach(target, function(item) { source.push(item); }); target.length = 0; sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); } }; }); /** * Initializes filterable checkbox and sets a watch in the filterable scope to track changes * in "advancedSettings.browsing.filterableFields". */ directives.directive('initFilterable', function () { return { restrict: 'A', link: function (scope) { scope.$watch('advancedSettings.browsing.filterableFields', function() { if (!scope.advancedSettings.browsing) { scope.checked = false; } else { scope.checked = (scope.advancedSettings.browsing.filterableFields.indexOf(scope.field.id) >= 0); } }); } }; }); /** * Filtering entity by selected filter. */ directives.directive('clickfilter', function () { return { restrict: 'A', link: function (scope, element, attrs) { var elm = angular.element(element), singleSelect = (attrs.singleselect === "true"); scope.wasAllSelected = function () { var i; for (i = 0; i < elm.parent().children().children.length; i += 1) { if ($(elm.parent().children()[i]).children().context.lastChild.data.trim() === "ALL") { if ($(elm.parent().children()[i]).hasClass('active')) { return true; } else { return false; } } } return false; }; elm.click(function (e) { if (elm.children().hasClass("fa-check-square-o")) { if (elm.text().trim() !== 'ALL') { if (scope.wasAllSelected()) { elm.parent().children().each(function(i) { $(elm.parent().children()[i]).children().removeClass('fa-check-square-o'); $(elm.parent().children()[i]).children().addClass("fa-square-o"); $(elm.parent().children()[i]).removeClass('active'); }); $(this).children().addClass('fa-check-square-o').removeClass('fa-square-o'); $(this).addClass('active'); } else { $(this).children().removeClass("fa-check-square-o").addClass("fa-square-o"); $(this).removeClass("active"); } } } else { if (elm.text().trim() === 'ALL') { elm.parent().children().each(function(i) { $(elm.parent().children()[i]).children().removeClass('fa-square-o').addClass("fa-check-square-o"); $(elm.parent().children()[i]).addClass('active'); }); } else { if (singleSelect === true) { elm.parent().children().each(function(i) { $(elm.parent().children()[i]).children().removeClass('fa-check-square-o'); $(elm.parent().children()[i]).children().addClass("fa-square-o"); $(elm.parent().children()[i]).removeClass('active'); }); } $(this).children().addClass("fa-check-square-o").removeClass("fa-square-o"); $(this).addClass("active"); } } }); } }; }); /** * Displays entity instances data using jqGrid */ directives.directive('entityInstancesGrid', function ($rootScope, $timeout) { return { restrict: 'A', link: function (scope, element, attrs) { var elem = angular.element(element), eventResize, eventChange, gridId = attrs.id, firstLoad = true; $.ajax({ type: "GET", url: "../mds/entities/" + scope.selectedEntity.id + "/entityFields", dataType: "json", success: function (result) { var colModel = [], i, noSelectedFields = true, spanText, noSelectedFieldsText = scope.msg('mds.dataBrowsing.noSelectedFieldsInfo'); buildGridColModel(colModel, result, scope, false, false); elem.jqGrid({ url: "../mds/entities/" + scope.selectedEntity.id + "/instances", headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "POST", postData: { fields: JSON.stringify(scope.lookupBy) }, rowNum: scope.entityAdvanced.userPreferences.gridRowsNumber, onPaging: function (pgButton) { handleGridPagination(pgButton, $(this.p.pager), scope); }, jsonReader: { repeatitems: false }, prmNames: { sort: 'sortColumn', order: 'sortDirection' }, onSelectRow: function (id) { firstLoad = true; scope.editInstance(id, scope.selectedEntity.module, scope.selectedEntity.name); }, resizeStop: function (width, index) { handleColumnResize('#entityInstancesTable', gridId, index, width, scope); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.entityInstancesGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { scope.setDataRetrievalError(false); spanText = $('<span>').addClass('ui-jqgrid-status-label ui-jqgrid ui-widget hidden'); spanText.append(noSelectedFieldsText).css({padding: '3px 15px'}); $('#entityInstancesTable .ui-paging-info').append(spanText); $('.ui-jqgrid-status-label').addClass('hidden'); $('#pageInstancesTable_center').addClass('page_instancesTable_center'); if (scope.selectedFields !== undefined && scope.selectedFields.length > 0) { noSelectedFields = false; } else { noSelectedFields = true; $('#pageInstancesTable_center').hide(); $('#entityInstancesTable .ui-jqgrid-status-label').removeClass('hidden'); } if ($('#instancesTable').getGridParam('records') > 0) { $('#pageInstancesTable_center').show(); $('#entityInstancesTable .ui-jqgrid-hdiv').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { if (noSelectedFields) { $('#pageInstancesTable_center').hide(); $('#entityInstancesTable .ui-jqgrid-hdiv').hide(); } $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } $('#entityInstancesTable .ui-jqgrid-hdiv').addClass("table-lightblue"); $('#entityInstancesTable .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 550); if (firstLoad) { resizeIfNarrow(gridId); firstLoad = false; } }, loadError: function(e) { scope.setDataRetrievalError(true, e.responseText); } }); scope.$watch("lookupRefresh", function () { $('#' + attrs.id).jqGrid('setGridParam', { page: 1, postData: { fields: JSON.stringify(scope.lookupBy), lookup: (scope.selectedLookup) ? scope.selectedLookup.lookupName : "", filter: (scope.filterBy) ? JSON.stringify(scope.filterBy) : "" } }).trigger('reloadGrid'); }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); resizeGridHeight(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 200); }); } }); } }; }); /** * Displays related instances data using jqGrid */ directives.directive('entityInstancesBrowserGrid', function ($timeout, $http, LoadingModal) { return { restrict: 'A', link: function (scope, element, attrs) { var tableWidth, relatedEntityId, relatedClass, selectedEntityNested, elem = angular.element(element), gridId = attrs.id, showGrid = function () { $.ajax({ type: "GET", url: "../mds/entities/" + relatedEntityId + "/entityFields", dataType: "json", success: function (result) { var colMd, colModel = [], i, spanText; buildGridColModel(colModel, result, scope, false, true); elem.jqGrid({ url: "../mds/entities/" + relatedEntityId + "/instances", headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "POST", postData: { fields: JSON.stringify(scope.lookupBy), filter: (scope.filterBy) ? JSON.stringify(scope.filterBy) : "" }, jsonReader: { repeatitems: false }, prmNames: { sort: 'sortColumn', order: 'sortDirection' }, onSelectRow: function (id) { if (scope.relatedMode.isNested) { scope.addRelatedInstance(id, selectedEntityNested, scope.editedField); } else { scope.addRelatedInstance(id, scope.selectedEntity, scope.editedField); } }, resizeStop: function (width, index) { var widthNew, widthOrg, colModel = $('#' + gridId).jqGrid('getGridParam','colModel'); if (colModel.length - 1 === index + 1 || (colModel[index + 1] !== undefined && isLastNextColumn(colModel, index))) { widthOrg = colModel[index].widthOrg; if (Math.floor(width) > Math.floor(widthOrg)) { widthNew = colModel[index + 1].width + Math.floor(width - widthOrg); colModel[index + 1].width = widthNew; $('.ui-jqgrid-labels > th:eq('+(index + 1)+')').css('width', widthNew); $('#' + gridId + ' .jqgfirstrow > td:eq('+(index + 1)+')').css('width', widthNew); } colModel[index].widthOrg = width; } tableWidth = $('#instanceBrowserTable').width(); $('#gview_' + gridId + ' .ui-jqgrid-htable').width(tableWidth); $('#gview_' + gridId + ' .ui-jqgrid-btable').width(tableWidth); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.entityInstancesBrowserGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { $('#' + attrs.entityInstancesBrowserGrid + '_center').addClass('page_instancesTable_center'); if ($('#' + gridId).getGridParam('records') > 0) { $('#' + attrs.entityInstancesBrowserGrid + '_center').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } tableWidth = $('#instanceBrowserTable').width(); $('#gbox_' + gridId).css('width','100%'); $('#gview_' + gridId).css('width','100%'); $('#gview_' + gridId + ' .ui-jqgrid-htable').addClass("table-lightblue"); $('#gview_' + gridId + ' .ui-jqgrid-btable').addClass("table-lightblue"); $('#gview_' + gridId + ' .ui-jqgrid-htable').width(tableWidth); $('#gview_' + gridId + ' .ui-jqgrid-btable').width(tableWidth); $('#gview_' + gridId + ' .ui-jqgrid-bdiv').width('100%'); $('#gview_' + gridId + ' .ui-jqgrid-hdiv').width('100%').show(); $('#gview_' + gridId + ' .ui-jqgrid-view').width('100%'); $('#gbox_' + gridId + ' .ui-jqgrid-pager').width('100%'); } }); } }); }; if (scope.relatedEntity !== undefined && scope.relatedMode.isNested !== true) { relatedEntityId = scope.relatedEntity.id; showGrid(); } else if (scope.relatedMode.isNested) { relatedClass = scope.getRelatedClass(scope.field); if (relatedClass !== undefined && scope.relatedMode.isNested) { LoadingModal.open(); $http.get('../mds/entities/getEntityByClassName?entityClassName=' + relatedClass).success(function (data) { relatedEntityId = data.id; LoadingModal.close(); showGrid(); if (scope.currentRelationRecord !== undefined) { selectedEntityNested = {id: scope.currentRelationRecord.entitySchemaId}; } }); } } scope.$watch("instanceBrowserRefresh", function () { elem.jqGrid('setGridParam', { page: 1, postData: { fields: JSON.stringify(scope.lookupBy), lookup: (scope.selectedLookup) ? scope.selectedLookup.lookupName : "", filter: (scope.filterBy) ? JSON.stringify(scope.filterBy) : "" } }).trigger('reloadGrid'); }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); } }; }); /** * Displays related instances data using jqGrid */ directives.directive('entityRelationsGrid', function ($timeout, $http, MDSUtils, ModalFactory, LoadingModal) { return { restrict: 'A', link: function (scope, element, attrs) { var tableWidth, isHiddenGrid, eventResize, eventChange, relatedClass, relatedEntityId, updatePostData, postdata, filter = {removedIds: [], addedIds: [], addedNewRecords: []}, elem = angular.element(element), gridId = attrs.id, gridRecords = 0, fieldId = attrs.fieldId, gridHide = attrs.gridHide, pagerHide = attrs.pagerHide, selectedEntityId = scope.selectedEntity.id, selectedInstance = (scope.selectedInstance !== undefined && angular.isNumber(parseInt(scope.selectedInstance, 10)))? parseInt(scope.selectedInstance, 10) : undefined; relatedClass = scope.getRelatedClass(scope.field); LoadingModal.open(); $http.get('../mds/entities/getEntityByClassName?entityClassName=' + relatedClass).success(function (data) { scope.relatedEntity = data; relatedEntityId = data.id; LoadingModal.close(); $.ajax({ type: "GET", url: "../mds/entities/" + scope.relatedEntity.id + "/entityFields", dataType: "json", success: function (result) { var colModel = [], i, spanText; if (scope.relatedMode.isNested) { selectedInstance = scope.editedInstanceId; if (scope.currentRelationRecord !== undefined) { selectedEntityId = scope.currentRelationRecord.entitySchemaId; } } else { colModel.push({ name: scope.msg('mds.form.label.action').toUpperCase(), width: 150, align: 'center', title: false, frozen: true, hidden: scope.field.nonEditable, formatter: function (array, options, data) { return "<button class='btn btn-default btn-xs btn-danger-hover removeRelatedInstance' " + " title='" + scope.msg('mds.dataBrowsing.removeRelatedInstance') + "'><i class='fa fa-fw fa-trash-o'></i>" + scope.msg('mds.dataBrowsing.remove') + "</button>"; }, sortable: false }); selectedEntityId = scope.selectedEntity.id; } buildGridColModel(colModel, result, scope, false, true); elem.jqGrid({ url: "../mds/instances/" + selectedEntityId + "/instance/" + ((selectedInstance !== undefined)? selectedInstance : "new") + "/" + scope.field.name, headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "POST", postData: { filters: (filter.removedIds !== null) ? JSON.stringify(filter) : "" }, jsonReader: { repeatitems: false }, onSelectRow: function (id, status, e) { if (!scope.field.nonEditable && e.target.getAttribute('class') !== null && (e.target.getAttribute('class').indexOf('removeRelatedInstance') >= 0 || (e.target.tagName ==='I' && e.target.parentElement.getAttribute('class').indexOf('removeRelatedInstance') >= 0))) { scope.relatedData.removeNewAdded(scope.field, parseInt(id, 10)); } else if (!scope.field.nonEditable && e.target.tagName !=='I' && e.target.tagName !== 'BUTTON' && e.target.tagName ==='TD' && !(e.target.children[0] !== undefined && e.target.children[0].getAttribute('class').indexOf('removeRelatedInstance') >= 0) && scope.newRelatedFields === null && !scope.relatedMode.isNested) { selectedInstance = parseInt(id, 10); scope.currentRelationRecord = {entitySchemaId: relatedEntityId}; if (scope.field.type.defaultName !== "manyToManyRelationship" && scope.field.type.defaultName !== "oneToManyRelationship" && scope.field.type.defaultName !== "oneToOneRelationship" && selectedInstance > 0) { scope.editRelatedInstanceOfEntity(scope.relatedData.getRelatedId(scope.field), undefined, scope.field); } else if (scope.field.type.defaultName !== "manyToManyRelationship" && scope.field.type.defaultName !== "oneToManyRelationship" && selectedInstance < 0) { scope.editRelatedInstanceOfEntity(selectedInstance, undefined, scope.field); } else { scope.editRelatedInstanceOfEntity(selectedInstance, relatedEntityId, scope.field); } } }, ondblClickRow : function(id,iRow,iCol,e) { }, resizeStop: function (width, index) { var widthNew, widthOrg, colModel = $('#' + gridId).jqGrid('getGridParam','colModel'); if (colModel.length - 1 === index + 1 || (colModel[index + 1] !== undefined && isLastNextColumn(colModel, index))) { widthOrg = colModel[index].widthOrg; widthNew = colModel[index + 1].width + Math.abs(widthOrg - width); colModel[index + 1].width = widthNew; colModel[index].width = width; $('.ui-jqgrid-labels > th:eq('+(index + 1)+')').css('width', widthNew); $('#' + gridId + ' .jqgfirstrow > td:eq('+(index + 1)+')').css('width', widthNew); } tableWidth = $('#instance_' + gridId).width(); $('#' + gridId).jqGrid("setGridWidth", tableWidth); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.entityRelationsGrid, viewrecords: true, autowidth: true, loadui: 'disable', shrinkToFit: false, gridComplete: function () { $('#' + attrs.entityRelationsGrid + '_center').addClass('page_' + gridId + '_center'); gridRecords = $('#' + gridId).getGridParam('records'); if (gridRecords > 0) { if (gridHide !== undefined && gridHide === "true") { $('body #instance_' + gridId).removeClass('hiddengrid'); } $('#relationsTableTotalRecords_' + fieldId).text(gridRecords + ' ' + scope.msg('mds.field.items')); $('#' + attrs.entityRelationsGrid + '_center').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css("height","0"); } else { $('#relationsTableTotalRecords_' + fieldId).text('0 ' + scope.msg('mds.field.items')); $('#' + attrs.entityRelationsGrid + '_center').hide(); $('#gbox_' + gridId + ' .jqgfirstrow').css("height","1px"); if (gridHide !== undefined && gridHide === "true") { $('body #instance_' + gridId).addClass('hiddengrid'); } } $('#gview_' + gridId + ' .ui-jqgrid-hdiv').show(); $('#gview_' + gridId + ' .ui-jqgrid-hdiv').addClass("table-lightblue"); $('#gview_' + gridId + ' .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridWidth(gridId); }, 250); } }).jqGrid('setFrozenColumns'); if (pagerHide === "true") { $('#' + attrs.entityRelationsGrid).addClass('hidden'); } if (gridHide !== undefined && gridHide === "true") { $('body #instance_' + gridId).addClass('hiddengrid'); } } }); }).error(function (response) { LoadingModal.close(); ModalFactory.showErrorAlertWithResponse('mds.error.cannotAddRelatedInstance', 'mds.error', response); }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); updatePostData = function (filter, postdata) { $('#' + attrs.id).jqGrid('setGridParam', { postData: { filters: ''} }); postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); $.extend(postdata, { filters: angular.toJson(filter) }); $('#' + attrs.id).jqGrid('setGridParam', { search: true, postData: postdata }); $timeout(function() { $('#' + attrs.id).jqGrid().trigger("reloadGrid"); }, 300); }; scope.$watch('field.value.removedIds', function (newValue) { postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); if (postdata !== undefined) { if (postdata.filters !== undefined) { filter = JSON.parse(postdata.filters); } if (newValue !== null) { filter.removedIds = newValue; } updatePostData(filter, postdata); } }, true); scope.$watch('field.value.addedIds', function (newValue) { postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); if (postdata !== undefined) { if (postdata.filters !== undefined) { filter = JSON.parse(postdata.filters); } if (newValue !== null) { filter.addedIds = newValue; } updatePostData(filter, postdata); } }, true); scope.$watch('field.value.addedNewRecords', function (newValue) { postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); if (postdata !== undefined) { if (postdata.filters !== undefined) { filter = JSON.parse(postdata.filters); } if (newValue !== null) { filter.addedNewRecords = newValue; } updatePostData(filter, postdata); } }, true); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridWidth(gridId); }, 200); }); } }; }); directives.directive('relatedfieldsform', function () { return { restrict: 'A', scope: false, require: 'ngModel', replace: true, link: function (scope, element, attrs, ngModel) { scope.$parent.$watch(attrs.ngModel, function (newValue, oldValue, scope) { scope.fields = newValue; if (scope.newRelatedFields !== undefined && scope.newRelatedFields !== null) { scope.fields = scope.newRelatedFields; } }); }, templateUrl: '../mds/resources/partials/widgets/entityInstanceFieldsRelated.html' }; }); directives.directive('editrelatedfieldsform', function () { return { restrict: 'A', scope: false, require: 'ngModel', replace: true, link: function(scope, element, attrs, ngModel) { scope.$parent.$watch(attrs.ngModel, function () { scope.fields = scope.editRelatedFields; if (scope.editRelatedFields !== undefined && scope.editRelatedFields !== null) { scope.fields = scope.editRelatedFields; } }); }, templateUrl: '../mds/resources/partials/widgets/entityInstanceFieldsRelated.html' }; }); directives.directive('showRelationsGrid', function () { return { restrict: 'A', link: function (scope, element, attrs) { var isHiddenGrid, elem = angular.element(element), gridId = attrs.showRelationsGrid, gridHide = attrs.gridHide, setHiddenGrid = function () { elem.children().removeClass('fa-angle-double-up'); elem.children().addClass('fa-angle-double-down'); $('#' + gridId).jqGrid('setGridState','hidden'); $('body #instance_' + gridId).addClass('hiddengrid'); }, setVisibleGrid = function () { elem.children().removeClass('fa-angle-double-down'); elem.children().addClass('fa-angle-double-up'); $('#' + gridId).jqGrid('setGridState','visible'); $('body #instance_' + gridId).removeClass('hiddengrid').delay(500).fadeIn("slow"); }; elem.on('click', function () { isHiddenGrid = $('#' + gridId).jqGrid('getGridParam','hiddengrid'); $('#' + gridId).jqGrid('setGridParam', { hiddengrid: !isHiddenGrid }); if (isHiddenGrid) { setVisibleGrid(); } else { setHiddenGrid(); } }); } }; }); directives.directive('multiselectDropdown', function () { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs) { var selectAll = scope.msg('mds.btn.selectAll'), target = attrs.targetTable, noSelectedFields = true; if (!target) { target = 'instancesTable'; } element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group" />', maxHeight : false, buttonText : function() { return scope.msg('mds.btn.fields'); }, selectAllText: selectAll, selectAllValue: 'multiselect-all', includeSelectAllOption: true, onChange: function (optionElement, checked) { if (optionElement) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } } element.change(); if (optionElement) { var name = scope.getFieldName(optionElement.text()); // don't act for fields show automatically in trash and history if (scope.autoDisplayFields.indexOf(name) === -1) { scope.addFieldForDataBrowser(name, checked); } } else { scope.addFieldsForDataBrowser(checked); } noSelectedFields = true; angular.forEach(element[0], function(field) { var name = scope.getFieldName(field.label); if (name) { // Change this name if it is reserved for jqgrid. name = changeIfReservedFieldName(name); if (field.selected){ $("#" + target).jqGrid('showCol', name); noSelectedFields = false; } else { $("#" + target).jqGrid('hideCol', name); } } }); if (noSelectedFields) { $('.page_' + target + '_center').hide(); $('.ui-jqgrid-status-label').removeClass('hidden'); $('.ui-jqgrid-hdiv').hide(); } else { $('.page_' + target + '_center').show(); $('.ui-jqgrid-status-label').addClass('hidden'); $('.ui-jqgrid-hdiv').show(); } }, onDropdownHide: function(event) { $("#" + target).trigger("resize"); } }); scope.$watch(function () { return element[0].length; }, function () { element.multiselect('rebuild'); }); $(element).parent().on("click", function () { element.multiselect('rebuild'); }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); } }; }); /** * Displays instance history data using jqGrid */ directives.directive('instanceHistoryGrid', function($compile, $http, $templateCache, $timeout) { return { restrict: 'A', link: function(scope, element, attrs) { var elem = angular.element(element), eventResize, eventChange, gridId = attrs.id, firstLoad = true; $.ajax({ type: "GET", url: "../mds/entities/" + scope.selectedEntity.id + "/entityFields", dataType: "json", success: function(result) { var colModel = [], i, noSelectedFields = true, spanText, noSelectedFieldsText = scope.msg('mds.dataBrowsing.noSelectedFieldsInfo'); colModel.push({ name: "", width: 28, formatter: function () { return "<a><i class='fa fa-lg fa-refresh'></i></a>"; }, sortable: false }); buildGridColModel(colModel, result, scope, true, false); elem.jqGrid({ url: "../mds/instances/" + scope.selectedEntity.id + "/" + scope.instanceId + "/history", datatype: 'json', jsonReader:{ repeatitems:false }, onSelectRow: function (id) { var myGrid = $('#historyTable'), cellValue = myGrid.jqGrid ('getCell', id, 'Changes'); if (cellValue === "Is Active") { scope.backToInstance(); } else { scope.historyInstance(id); } }, rowNum: scope.entityAdvanced.userPreferences.gridRowsNumber, onPaging: function (pgButton) { handleGridPagination(pgButton, $(this.p.pager), scope); }, resizeStop: function (width, index) { handleColumnResize('#instanceHistoryTable', gridId, index, width, scope); }, headertitles: true, colModel: colModel, pager: '#' + attrs.instanceHistoryGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { spanText = $('<span>').addClass('ui-jqgrid-status-label ui-jqgrid ui-widget hidden'); spanText.append(noSelectedFieldsText).css({padding: '3px 15px'}); $('#instanceHistoryTable .ui-paging-info').append(spanText); $('.ui-jqgrid-status-label').addClass('hidden'); $('#pageInstanceHistoryTable_center').addClass('page_historyTable_center'); if (scope.selectedFields !== undefined && scope.selectedFields.length > 0) { noSelectedFields = false; } else { noSelectedFields = true; $('#pageInstanceHistoryTable_center').hide(); $('#instanceHistoryTable .ui-jqgrid-status-label').removeClass('hidden'); } if ($('#historyTable').getGridParam('records') > 0) { $('#pageInstanceHistoryTable_center').show(); $('#instanceHistoryTable .ui-jqgrid-hdiv').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { if (noSelectedFields) { $('#pageInstanceHistoryTable_center').hide(); $('#instanceHistoryTable .ui-jqgrid-hdiv').hide(); } $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } $('#instanceHistoryTable .ui-jqgrid-hdiv').addClass('table-lightblue'); $('#instanceHistoryTable .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 550); if (firstLoad) { resizeIfNarrow(gridId); firstLoad = false; } } }); elem.on('jqGridSortCol', function (e, fieldName) { e.target.p.sortname = backToReservedFieldName(fieldName); }); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); resizeGridHeight(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 200); }); } }); } }; }); /** * Displays entity instance trash data using jqGrid */ directives.directive('instanceTrashGrid', function ($timeout) { return { restrict: 'A', link: function (scope, element, attrs) { var elem = angular.element(element), eventResize, eventChange, gridId = attrs.id, firstLoad = true; $.ajax({ type: "GET", url: "../mds/entities/" + scope.selectedEntity.id + "/entityFields", dataType: "json", success: function (result) { var colModel = [], i, noSelectedFields = true, spanText, noSelectedFieldsText = scope.msg('mds.dataBrowsing.noSelectedFieldsInfo'); buildGridColModel(colModel, result, scope, true, false); elem.jqGrid({ url: "../mds/entities/" + scope.selectedEntity.id + "/trash", headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "GET", postData: { fields: JSON.stringify(scope.lookupBy) }, jsonReader: { repeatitems: false }, rowNum: scope.entityAdvanced.userPreferences.gridRowsNumber, onPaging: function (pgButton) { handleGridPagination(pgButton, $(this.p.pager), scope); }, onSelectRow: function (id) { firstLoad = true; scope.trashInstance(id); }, resizeStop: function (width, index) { handleColumnResize('#instanceTrashTable', gridId, index, width, scope); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.instanceTrashGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { spanText = $('<span>').addClass('ui-jqgrid-status-label ui-jqgrid ui-widget hidden'); spanText.append(noSelectedFieldsText).css({padding: '3px 15px'}); $('#instanceTrashTable .ui-paging-info').append(spanText); $('.ui-jqgrid-status-label').addClass('hidden'); $('#pageInstanceTrashTable_center').addClass('page_trashTable_center'); if (scope.selectedFields !== undefined && scope.selectedFields.length > 0) { noSelectedFields = false; } else { noSelectedFields = true; $('#pageInstanceTrashTable_center').hide(); $('#instanceTrashTable .ui-jqgrid-status-label').removeClass('hidden'); } if ($('#trashTable').getGridParam('records') > 0) { $('#pageInstanceTrashTable_center').show(); $('#instanceTrashTable .ui-jqgrid-hdiv').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { if (noSelectedFields) { $('#pageInstanceTrashTable_center').hide(); $('#instanceTrashTable .ui-jqgrid-hdiv').hide(); } $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } $('#instanceTrashTable .ui-jqgrid-hdiv').addClass("table-lightblue"); $('#instanceTrashTable .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 550); if (firstLoad) { resizeIfNarrow(gridId); firstLoad = false; } } }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); resizeGridHeight(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 200); }); } }); } }; }); directives.directive('droppable', function () { return { scope: { drop: '&' }, link: function (scope, element) { var el = element[0]; el.addEventListener('dragover', function (e) { e.dataTransfer.dropEffect = 'move'; if (e.preventDefault) { e.preventDefault(); } this.classList.add('over'); return false; }, false); el.addEventListener('dragenter', function () { this.classList.add('over'); return false; }, false); el.addEventListener('dragleave', function () { this.classList.remove('over'); return false; }, false); el.addEventListener('drop', function (e) { var fieldId = e.dataTransfer.getData('Text'), containerId = this.id; if (e.stopPropagation) { e.stopPropagation(); } scope.$apply(function (scope) { var fn = scope.drop(); if (_.isFunction(fn)) { fn(fieldId, containerId); } }); return false; }, false); } }; }); /** * Add auto saving for field properties. */ directives.directive('mdsAutoSaveFieldChange', function (Entities) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var func = attr.mdsAutoSaveFieldChange || 'focusout'; angular.element(element).on(func, function () { var viewScope = findCurrentScope(scope, 'draft'), fieldPath = attr.mdsPath, fieldId = attr.mdsFieldId, entity, value; if (fieldPath === undefined) { fieldPath = attr.ngModel; fieldPath = fieldPath.substring(fieldPath.indexOf('.') + 1); } value = ngModel.$modelValue; viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); }); } }; }); /* * Add auto saving for field properties. */ directives.directive('mdsAutoSaveAdvancedChange', function (Entities) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var func = attr.mdsAutoSaveAdvancedChange || 'focusout'; angular.element(element).on(func, function () { var viewScope = findCurrentScope(scope, 'draft'), advancedPath = attr.mdsPath, entity, value; if (advancedPath === undefined) { advancedPath = attr.ngModel; advancedPath = advancedPath.substring(advancedPath.indexOf('.') + 1); } value = _.isBoolean(ngModel.$modelValue) ? !ngModel.$modelValue : ngModel.$modelValue; viewScope.draft({ edit: true, values: { path: advancedPath, advanced: true, value: [value] } }); }); } }; }); /** * Add auto saving for field properties. */ directives.directive('mdsAutoSaveBtnSelectChange', function (Entities) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fieldId = attrs.mdsFieldId, criterionId = attrs.mdsCriterionId, entity, value; elm.children('ul').on('click', function () { value = scope.selectedRegexPattern; if ((value !== null && value.length === 0) || value === null) { value = ""; } viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); }); } }; }); /** * Sets a callback function to select2 on('change') event. */ directives.directive('select2NgChange', function () { return { restrict: 'A', link: function (scope, element, attrs) { var elem = angular.element(element), callback = elem.attr('select2-ng-change'); elem.on('change', scope[callback]); } }; }); directives.directive('multiselectList', function () { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs) { var fieldSettings = scope.field.settings, comboboxValues = scope.getComboboxValues(fieldSettings), typeField = attrs.multiselectList; element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group" />', maxHeight : false, numberDisplayed: 3, buttonText : function(options) { if (options.length === 0) { return scope.msg('mds.form.label.select'); } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + scope.msg('mds.form.label.selected'); } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); selected = selected.substr(0, selected.length - 2); return (selected === '') ? scope.msg('mds.form.label.select'): selected; } } }, onChange: function (optionElement, checked) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } element.change(); } }); $("#saveoption" + scope.field.id).on("click", function () { element.multiselect('rebuild'); }); scope.$watch(function () { return element[0].length; }, function () { if (typeField === 'owner') { element.multiselect('rebuild'); } else { var comboboxValues = scope.getComboboxValues(scope.field.settings); if (comboboxValues !== null && comboboxValues !== undefined) { if (comboboxValues.length > 0 && comboboxValues[0] !== '') { element.multiselect('enable'); } else { element.multiselect('disable'); } element.multiselect('rebuild'); } } }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); } }; }); directives.directive('defaultMultiselectList', function (Entities) { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs, ngModel) { var entity, value, resetDefaultValue, checkIfNeedReset, viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fieldId = attrs.mdsFieldId, typeField = attrs.defaultMultiselectList; element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group" />', maxHeight : false, numberDisplayed: 3, buttonText : function(options) { if (options.length === 0) { return scope.msg('mds.form.label.select'); } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + scope.msg('mds.form.label.selected'); } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); selected = selected.substr(0, selected.length - 2); return (selected === '') ? scope.msg('mds.form.label.select') : selected; } } }, onChange: function (optionElement, checked) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } if (fieldPath === undefined) { fieldPath = attrs.ngModel; fieldPath = fieldPath.substring(fieldPath.indexOf('.') + 1); } value = ngModel.$modelValue; if ((value !== null && value.length === 0) || value === null) { value = ""; } viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); element.change(); } }); scope.$watch("field.settings[0].value", function( newValue, oldValue ) { if (newValue !== oldValue) { var includeSelectedValues = function (newList, selectedValues) { var result, valueOnList = function (theList, val) { if (_.contains(theList, val)) { result = true; } else { result = false; } return (result); }; if(selectedValues !== null && selectedValues !== undefined && $.isArray(selectedValues) && selectedValues.length > 0) { $.each(selectedValues, function (i, val) { return (valueOnList(newList, val)); }); } else if ($.isArray(newList) && selectedValues !== null && selectedValues !== undefined && selectedValues.length > 0) { return (valueOnList(newList, selectedValues)); } else { result = true; } return result; }; if (!includeSelectedValues(newValue, ngModel.$viewValue)) { resetDefaultValue(); } if (scope.field.settings[0].value !== null && (scope.field.settings[0].value.length > 0 && scope.field.settings[0].value[0].toString().trim().length > 0)) { element.multiselect('enable'); } else { element.multiselect('disable'); } } }, true); resetDefaultValue = function () { fieldId = attrs.mdsFieldId; value = ''; viewScope.draft({ edit: true, values: { path: "basic.defaultValue", fieldId: fieldId, value: [value] } }); scope.field.basic.defaultValue = ''; $('#reset-default-value-combobox' + scope.field.id).fadeIn("slow"); setTimeout(function () { $('#reset-default-value-combobox' + scope.field.id).fadeOut("slow"); }, 8000); element.multiselect('updateButtonText'); element.children('option').each(function() { $(this).prop('selected', false); }); element.multiselect('refresh'); }; checkIfNeedReset = function () { return scope.field.basic.defaultValue !== null && scope.field.basic.defaultValue.length > 0 && scope.field.basic.defaultValue !== ''; }; scope.$watch(function () { return element[0].length; }, function () { element.multiselect('rebuild'); }); element.siblings('div').on('click', function () { element.multiselect('rebuild'); }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); $("#mdsfieldsettings_" + scope.field.id + '_1').on("click", function () { if (checkIfNeedReset()) { resetDefaultValue(); } }); $("#mdsfieldsettings_" + scope.field.id + '_2').on("click", function () { if (checkIfNeedReset()) { resetDefaultValue(); } }); } }; }); directives.directive('securityList', function () { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs, ngModel) { element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group pull-left" />', maxHeight : false, numberDisplayed: 3, buttonText : function(options) { if (options.length === 0) { return scope.msg('mds.form.label.select'); } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + scope.msg('mds.form.label.selected'); } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); return selected.substr(0, selected.length - 2); } } }, onChange: function (optionElement, checked) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } element.change(); } }); scope.$watch(function () { return element[0].length; }, function () { element.multiselect('rebuild'); }); element.siblings('div').on('click', function () { element.multiselect('rebuild'); }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); } }; }); directives.directive('integerValidity', function() { var INTEGER_REGEXP = new RegExp('^([-][1-9])?(\\d)*$'), TWOZERO_REGEXP = new RegExp('^(0+\\d+)$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || INTEGER_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('integer', true); originalValue = viewValue; viewValue = parseInt(viewValue, 10); if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('integer', false); return viewValue; } }); } }; }); directives.directive('shortValidity', function() { var INTEGER_REGEXP = new RegExp('^([-][1-9])?(\\d)*$'), TWOZERO_REGEXP = new RegExp('^(0+\\d+)$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || INTEGER_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('short', true); originalValue = viewValue; viewValue = parseInt(viewValue, 10); if (viewValue >= 32767 || viewValue <= -32768) { ctrl.$setValidity('short', false); } if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('short', false); return viewValue; } }); } }; }); directives.directive('decimalValidity', function() { var DECIMAL_REGEXP = new RegExp('^[-]?\\d+(\\.\\d+)?$'), TWOZERO_REGEXP = new RegExp('^[-]?0+\\d+(\\.\\d+)?$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || DECIMAL_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('decimal', true); originalValue = viewValue; viewValue = parseFloat(viewValue); if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('decimal', false); return viewValue; } }); } }; }); directives.directive('floatValidity', function() { var FLOAT_REGEXP = new RegExp('^[-]?\\d+(\\.\\d+)?$'), TWOZERO_REGEXP = new RegExp('^[-]?0+\\d+(\\.\\d+)?$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || FLOAT_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('float', true); originalValue = viewValue; viewValue = parseFloat(viewValue); if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('float', false); return viewValue; } }); } }; }); directives.directive('charValidity', function() { var CHAR_REGEXP = new RegExp('^.$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if(viewValue === '' || CHAR_REGEXP.test(viewValue)) { ctrl.$setValidity('char', true); originalValue = viewValue; return viewValue; } else { ctrl.$setValidity('char', false); return viewValue; } }); } }; }); directives.directive('uuidValidity', function() { var UUID_REGEXP = new RegExp('^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if(viewValue === '' || UUID_REGEXP.test(viewValue)) { ctrl.$setValidity('uuid', true); return viewValue; } else { ctrl.$setValidity('uuid', false); return viewValue; } }); } }; }); directives.directive('insetValidity', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var inset = '', checkInset = function (inset, viewValue) { var result, insetParameters = inset.split(' '); if($.isArray(insetParameters)) { $.each(insetParameters, function (i, val) { if (parseFloat(val) === parseFloat(viewValue)) { result = true; } else { result = false; } return (!result); }); } else { result = false; } return result; }; if (scope.field.validation.criteria[attrs.insetValidity] !== undefined && scope.field.validation.criteria[attrs.insetValidity].enabled) { inset = scope.field.validation.criteria[attrs.insetValidity].value; } if (ctrl.$viewValue === '' || inset === '' || checkInset(inset, ctrl.$viewValue)) { ctrl.$setValidity('insetNum', true); return viewValue; } else { ctrl.$setValidity('insetNum', false); return viewValue; } }); } }; }); directives.directive('outsetValidity', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var outset = '', checkOutset = function (outset, viewValue) { var result, outsetParameters = outset.split(' '); if($.isArray(outsetParameters)) { $.each(outsetParameters, function (i, val) { if (parseFloat(val) === parseFloat(viewValue)) { result = true; } else { result = false; } return (!result); }); } else { result = false; } return result; }; if (scope.field.validation.criteria[attrs.outsetValidity] !== undefined && scope.field.validation.criteria[attrs.outsetValidity].enabled) { outset = scope.field.validation.criteria[attrs.outsetValidity].value; } if (ctrl.$viewValue === '' || outset === '' || !checkOutset(outset, ctrl.$viewValue)) { ctrl.$setValidity('outsetNum', true); return viewValue; } else { ctrl.$setValidity('outsetNum', false); return viewValue; } }); } }; }); directives.directive('maxValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var max = ''; if (scope.field.validation.criteria[attrs.maxValidity] !== undefined && scope.field.validation.criteria[attrs.maxValidity].enabled) { max = scope.field.validation.criteria[attrs.maxValidity].value; } if (ctrl.$viewValue === '' || max === '' || parseFloat(ctrl.$viewValue) <= parseFloat(max)) { ctrl.$setValidity('max', true); return viewValue; } else { ctrl.$setValidity('max', false); return viewValue; } }); } }; }); directives.directive('minValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var min = ''; if (scope.field.validation.criteria[attrs.minValidity] !== undefined && scope.field.validation.criteria[attrs.minValidity].enabled) { min = scope.field.validation.criteria[attrs.minValidity].value; } if (ctrl.$viewValue === '' || min === '' || parseFloat(ctrl.$viewValue) >= parseFloat(min)) { ctrl.$setValidity('min', true); return viewValue; } else { ctrl.$setValidity('min', false); return viewValue; } }); } }; }); directives.directive('illegalValueValidity', function() { var RESERVED_WORDS = [ 'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const*', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extends', 'false', 'final', 'finally', 'float', 'for', 'goto*', 'if', 'int', 'interface', 'instanceof', 'implements', 'import', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'strictfp', 'super', 'synchronized', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'void', 'volatile', 'while' ], LEGAL_REGEXP = /^[\w]+$/; return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var validateReservedWords; validateReservedWords = function (viewValue) { if (ctrl.$viewValue === '' || attrs.illegalValueValidity === 'true' || (LEGAL_REGEXP.test(ctrl.$viewValue) && $.inArray(ctrl.$viewValue, RESERVED_WORDS) === -1) ) { // it is valid ctrl.$setValidity('illegalvalue', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('illegalvalue', false); return ''; } }; ctrl.$parsers.unshift(validateReservedWords); scope.$watch("field.settings[1].value", function(newValue, oldValue) { if (newValue !== oldValue) { ctrl.$setViewValue(ctrl.$viewValue); } }); } }; }); directives.directive('showAddOptionInput', function() { return { restrict: 'A', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), showAddOptionInput = elm.siblings('span'); elm.on('click', function () { showAddOptionInput.removeClass('hidden'); showAddOptionInput.children('input').val(''); }); } }; }); directives.directive('addOptionCombobox', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var distinct, elm = angular.element(element), fieldSettings = scope.field.settings, modelValueArray = scope.getComboboxValues(fieldSettings), parent = elm.parent(); distinct = function(mvArray, inputValue) { var result; if ($.inArray(inputValue, mvArray) !== -1 && inputValue !== null) { result = false; } else { result = true; } return result; }; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || distinct(modelValueArray, viewValue)) { ctrl.$setValidity('uniqueValue', true); return viewValue; } else { ctrl.$setValidity('uniqueValue', false); return undefined; } }); elm.siblings('a').on('click', function () { scope.fieldValue = []; if (scope.field !== null && scope.newOptionValue !== undefined && scope.newOptionValue !== '') { if (scope.field.settings[2].value) { //if multiselect if (scope.field.value !== null) { if (!$.isArray(scope.field.value)) { scope.fieldValue = $.makeArray(scope.field.value); } else { angular.forEach(scope.field.value, function(val) { scope.fieldValue.push(val); }); } } else { scope.fieldValue = []; } scope.fieldValue.push(scope.newOptionValue); scope.field.value = scope.fieldValue; } else { scope.field.value = scope.newOptionValue; } scope.field.settings[0].value.push(scope.newOptionValue); scope.newOptionValue = ''; parent.addClass('hidden'); elm.resetForm(); } }); } }; }); directives.directive('mdsBasicUpdateMap', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldMapModel = attrs.mdsPath, fieldPath = fieldMapModel, fPath = fieldPath.substring(fieldPath.indexOf('.') + 1), fieldId = attrs.mdsFieldId, fieldMaps, value, entity, keyIndex; scope.$watch(attrs.ngModel, function (viewValue) { fieldMaps = scope.getMap(fieldId); value = scope.mapToString(fieldMaps.fieldMap); keyIndex = parseInt(attrs.mdsBasicUpdateMap, 10); var distinct = function(inputValue, mvArray) { var result; if ($.inArray(inputValue, mvArray) !== -1 && inputValue !== null) { result = false; } else { result = true; } return result; }, keysList = function () { var resultKeysList = []; angular.forEach(fieldMaps.fieldMap, function (map, index) { if (map !== null && map.key !== undefined && map.key.toString() !== '') { if (index !== keyIndex) { resultKeysList.push(map.key.toString()); } } }, resultKeysList); return resultKeysList; }; if ((!elm.parent().parent().find('.has-error').length && elm.hasClass('map-value')) || (viewValue === '' && elm.hasClass('map-key')) || (distinct(viewValue, keysList()) && elm.hasClass('map-key'))) { if ((value !== null && value.length === 0) || value === null) { value = ""; } if (scope.field.basic.defaultValue !== value) { scope.field.basic.defaultValue = value; viewScope.draft({ edit: true, values: { path: fPath, fieldId: fieldId, value: [value] } }); } } }); } }; }); directives.directive('mdsBasicDeleteMap', function () { return { link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fPath = fieldPath.substring(fieldPath.indexOf('.') + 1), fieldId = attrs.mdsFieldId, fieldMaps, value, entity, keyIndex; elm.on('click', function (viewValue) { keyIndex = parseInt(attrs.mdsBasicDeleteMap, 10); scope.deleteElementMap(fieldId, keyIndex); fieldMaps = scope.getMap(fieldId); value = scope.mapToString(fieldMaps.fieldMap); if ((value !== null && value.length === 0) || value === null) { value = ""; } scope.safeApply(function () { scope.field.basic.defaultValue = value; }); viewScope.draft({ edit: true, values: { path: fPath, fieldId: fieldId, value: [value] } }); }); } }; }); directives.directive('mdsUpdateMap', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), fieldId = attrs.mdsFieldId, fieldMaps, value, keyIndex, keysList, distinct; scope.$watch(attrs.ngModel, function (viewValue) { keyIndex = parseInt(attrs.mdsUpdateMap, 10); fieldMaps = scope.getMap(fieldId); value = scope.mapToMapObject(fieldMaps.fieldMap); var distinct = function(inputValue, mvArray) { var result; if ($.inArray(inputValue, mvArray) !== -1 && inputValue !== null) { result = false; } else { result = true; } return result; }, keysList = function () { var resultKeysList = []; angular.forEach(fieldMaps.fieldMap, function (map, index) { if (map !== null && map.key !== undefined && map.key.toString() !== '') { if (index !== keyIndex) { resultKeysList.push(map.key.toString()); } } }, resultKeysList); return resultKeysList; }; if ((elm.parent().parent().find('.has-error').length < 1 && elm.hasClass('map-value')) || (viewValue === '' && elm.hasClass('map-key')) || (distinct(viewValue, keysList()) && elm.hasClass('map-key'))) { if ((value !== null && value.length === 0) || value === null) { value = ""; } scope.field.value = value; } }); elm.siblings('a').on('click', function () { if (elm.hasClass('map-key')) { keyIndex = parseInt(attrs.mdsUpdateMap, 10); scope.deleteElementMap(fieldId, keyIndex); fieldMaps = scope.getMap(fieldId); value = scope.mapToMapObject(fieldMaps.fieldMap); if ((value !== null && value.length === 0) || value === null) { value = ""; } scope.safeApply(function () { scope.field.value = value; }); } }); } }; }); directives.directive('mapValidation', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var required = attrs.mapValidation; scope.$watch(attrs.ngModel, function (viewValue) { if (required.toString() === 'true') { if (viewValue !== '' || viewValue.toString().trim().length > 0) { ctrl.$setValidity('required', true); return viewValue; } else { ctrl.$setValidity('required', false); return viewValue; } } else { ctrl.$setValidity('required', true); return viewValue; } }); } }; }); directives.directive('patternValidity', function() { var PATTERN_REGEXP; return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { if (attrs.patternValidity !== undefined && scope.field.validation.criteria[attrs.patternValidity].enabled) { PATTERN_REGEXP = new RegExp(scope.field.validation.criteria[attrs.patternValidity].value); } else { PATTERN_REGEXP = new RegExp(''); } if (ctrl.$viewValue === '' || PATTERN_REGEXP.test(ctrl.$viewValue)) { // it is valid ctrl.$setValidity('pattern', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('pattern', false); return undefined; } }); } }; }); directives.directive('dateTimeValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), valueDate, valueTime; ctrl.$parsers.unshift(function(viewValue) { valueDate = ctrl.$viewValue.slice(0, 16); if (ctrl.$viewValue.length > 10) { valueTime = ctrl.$viewValue.slice(11, ctrl.$viewValue.length); } if (ctrl.$viewValue === '' || (moment(valueDate,'').isValid() && ($.datepicker.parseTime('HH:mm z', valueTime, '') !== false))) { // it is valid ctrl.$setValidity('datetime', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('datetime', false); return undefined; } }); } }; }); directives.directive('dateValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element); ctrl.$parsers.unshift(function(viewValue) { if (ctrl.$viewValue === '' || moment(ctrl.$viewValue,'').isValid()) { // it is valid ctrl.$setValidity('date', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('date', false); return undefined; } }); } }; }); directives.directive('timeValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), valueTime; ctrl.$parsers.unshift(function(viewValue) { valueTime = ctrl.$viewValue; if (ctrl.$viewValue === '' || $.datepicker.parseTime('HH:mm', valueTime, '') !== false) { // it is valid ctrl.$setValidity('time', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('time', false); return undefined; } }); } }; }); directives.directive('mdsBasicDeleteListValue', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = elm.parent().parent().attr('mds-path'), fieldId = attrs.mdsFieldId, value, keyIndex; elm.on('click', function (e) { keyIndex = parseInt(attrs.mdsBasicDeleteListValue, 10); value = scope.deleteElementList(ctrl.$viewValue, keyIndex); viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); }); } }; }); directives.directive('defaultFieldNameValid', function() { return { link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), fieldName = attrs.defaultFieldNameValid; scope.defaultValueValid.push({ name: fieldName, valid: true }); scope.$watch(function () { return element[0].classList.length; }, function () { var fieldName = attrs.defaultFieldNameValid; if (element.hasClass('has-error') || element.hasClass('ng-invalid')) { scope.setBasicDefaultValueValid(false, fieldName); } else { scope.setBasicDefaultValueValid(true, fieldName); } }); } }; }); directives.directive('mdsUpdateCriterion', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fieldId = attrs.mdsFieldId, criterionId = attrs.mdsCriterionId, criterionName = attrs.mdsUpdateCriterion, value; scope.$watch(attrs.ngModel, function (viewValue) { if ((!elm.parent().parent().find('.has-error').length || viewValue === '') && (criterionName === 'mds.field.validation.cannotBeInSet' || criterionName === 'mds.field.validation.mustBeInSet')) { value = scope.getCriterionValues(fieldId, criterionName); if ((value !== null && value.length === 0) || value === null) { value = ""; } if (scope.field.validation.criteria[criterionId].value !== value) { scope.field.validation.criteria[criterionId].value = value; viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); } } }); elm.siblings('a').on('click', function () { value = scope.deleteValueList(fieldId, criterionName, parseInt(attrs.mdsValueIndex, 10)); if (scope.field.validation.criteria[criterionId].value !== value) { scope.safeApply(function () { scope.field.validation.criteria[criterionId].value = value; }); viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); } }); } }; }); directives.directive('mdsContentTooltip', function () { return { restrict: 'A', link: function (scope, element, attrs) { var elm = angular.element(element), fieldId = attrs.mdsFieldId, fieldType = attrs.mdsContentTooltip; $(element).popover({ placement: 'bottom', trigger: 'hover', html: true, title: scope.msg('mds.info.' + fieldType), content: function () { return $('#content' + fieldId).html(); } }); } }; }); directives.directive('mdsIndeterminate', function() { return { restrict: 'A', link: function(scope, element, attributes) { scope.$watch(attributes.mdsIndeterminate, function (value) { element.prop('indeterminate', !!value); }); } }; }); directives.directive('mdsVisitedInput', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ctrl) { var elm = angular.element(element), fieldId = attrs.mdsFieldId, fieldName = attrs.mdsFieldName, typingTimer, ngFormNameAttrSuffix = "form"; elm.on('keyup', function () { scope.$apply(function () { elm.siblings('#visited-hint-' + fieldId).addClass('hidden'); if (scope[fieldName + ngFormNameAttrSuffix] !== undefined) { scope[fieldName + ngFormNameAttrSuffix].$dirty = false; } }); clearTimeout(typingTimer); typingTimer = setTimeout( function() { elm.siblings('#visited-hint-' + fieldId).removeClass('hidden'); scope.$apply(function () { if (scope[fieldName + ngFormNameAttrSuffix] !== undefined) { scope[fieldName + ngFormNameAttrSuffix].$dirty = true; } }); }, 1500); }); elm.on("blur", function() { scope.$apply(function () { elm.siblings('#visited-hint-' + fieldId).removeClass('hidden'); if (scope[fieldName + ngFormNameAttrSuffix] !== undefined) { scope[fieldName + ngFormNameAttrSuffix].$dirty = true; } }); }); } }; }); directives.directive('mdsFileChanged', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('change', function(e){ scope.$apply(function(){ scope[attrs.mdsFileChanged](e.target.files[0]); }); }); } }; }); directives.directive('tabLayoutWithMdsGrid', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) { return function(scope, element, attrs) { $http.get('../mds/resources/partials/tabLayoutWithMdsGrid.html', { cache: $templateCache }).success(function(response) { var contents = element.html(response).contents(); element.replaceWith($compile(contents)(scope)); }); }; }]); directives.directive('embeddedMdsFilters', function($http, $templateCache, $compile) { return function(scope, element, attrs) { $http.get('../mds/resources/partials/embeddedMdsFilters.html', { cache: $templateCache }).success(function(response) { var contents = element.html(response).contents(); $compile(contents)(scope); }); }; }); directives.directive('preventNameConflicts', function($compile) { return { restrict: 'A', priority: 10000, terminal: true, link: function(scope, element, attrs) { attrs.$set('name', attrs.name + 'form'); attrs.$set('preventNameConflicts', null); $compile(element)(scope); } }; }); }());
koshalt/motech
platform/mds/mds-web/src/main/resources/webapp/js/directives.js
JavaScript
bsd-3-clause
161,992
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/chromeos/platform_video_frame_pool.h" #include <utility> #include "base/logging.h" #include "base/optional.h" #include "base/task/post_task.h" #include "media/gpu/chromeos/gpu_buffer_layout.h" #include "media/gpu/chromeos/platform_video_frame_utils.h" #include "media/gpu/macros.h" namespace media { namespace { // The default method to create frames. scoped_refptr<VideoFrame> DefaultCreateFrame( gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, VideoPixelFormat format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp) { return CreatePlatformVideoFrame(gpu_memory_buffer_factory, format, coded_size, visible_rect, natural_size, timestamp, gfx::BufferUsage::SCANOUT_VDA_WRITE); } } // namespace PlatformVideoFramePool::PlatformVideoFramePool( gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory) : create_frame_cb_(base::BindRepeating(&DefaultCreateFrame)), gpu_memory_buffer_factory_(gpu_memory_buffer_factory) { DVLOGF(4); weak_this_ = weak_this_factory_.GetWeakPtr(); } PlatformVideoFramePool::~PlatformVideoFramePool() { if (parent_task_runner_) DCHECK(parent_task_runner_->RunsTasksInCurrentSequence()); DVLOGF(4); base::AutoLock auto_lock(lock_); frames_in_use_.clear(); free_frames_.clear(); weak_this_factory_.InvalidateWeakPtrs(); } scoped_refptr<VideoFrame> PlatformVideoFramePool::GetFrame() { DCHECK(parent_task_runner_->RunsTasksInCurrentSequence()); DVLOGF(4); base::AutoLock auto_lock(lock_); if (!frame_layout_) { VLOGF(1) << "Please call Initialize() first."; return nullptr; } VideoPixelFormat format = frame_layout_->fourcc().ToVideoPixelFormat(); const gfx::Size& coded_size = frame_layout_->size(); if (free_frames_.empty()) { if (GetTotalNumFrames_Locked() >= max_num_frames_) return nullptr; // VideoFrame::WrapVideoFrame() will check whether the updated visible_rect // is sub rect of the original visible_rect. Therefore we set visible_rect // as large as coded_size to guarantee this condition. scoped_refptr<VideoFrame> new_frame = create_frame_cb_.Run( gpu_memory_buffer_factory_, format, coded_size, gfx::Rect(coded_size), coded_size, base::TimeDelta()); if (!new_frame) return nullptr; InsertFreeFrame_Locked(std::move(new_frame)); } DCHECK(!free_frames_.empty()); scoped_refptr<VideoFrame> origin_frame = std::move(free_frames_.back()); free_frames_.pop_back(); DCHECK_EQ(origin_frame->format(), format); DCHECK_EQ(origin_frame->coded_size(), coded_size); scoped_refptr<VideoFrame> wrapped_frame = VideoFrame::WrapVideoFrame( origin_frame, format, visible_rect_, natural_size_); DCHECK(wrapped_frame); frames_in_use_.emplace(GetDmabufId(*wrapped_frame), origin_frame.get()); wrapped_frame->AddDestructionObserver( base::BindOnce(&PlatformVideoFramePool::OnFrameReleasedThunk, weak_this_, parent_task_runner_, std::move(origin_frame))); // Clear all metadata before returning to client, in case origin frame has any // unrelated metadata. wrapped_frame->metadata()->Clear(); return wrapped_frame; } base::Optional<GpuBufferLayout> PlatformVideoFramePool::Initialize( const Fourcc& fourcc, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, size_t max_num_frames) { DVLOGF(4); base::AutoLock auto_lock(lock_); visible_rect_ = visible_rect; natural_size_ = natural_size; max_num_frames_ = max_num_frames; // Only support the Fourcc that could map to VideoPixelFormat. VideoPixelFormat format = fourcc.ToVideoPixelFormat(); if (format == PIXEL_FORMAT_UNKNOWN) { VLOGF(1) << "Unsupported fourcc: " << fourcc.ToString(); return base::nullopt; } // If the frame layout changed we need to allocate new frames so we will clear // the pool here. If only the visible or natural size changed we don't need to // allocate new frames, but will just update the properties of wrapped frames // returned by GetFrame(). // NOTE: It is assumed layout is determined by |format| and |coded_size|. if (!IsSameFormat_Locked(format, coded_size)) { DVLOGF(4) << "The video frame format is changed. Clearing the pool."; free_frames_.clear(); // Create a temporary frame in order to know VideoFrameLayout that // VideoFrame that will be allocated in GetFrame() has. auto frame = create_frame_cb_.Run(gpu_memory_buffer_factory_, format, coded_size, visible_rect_, natural_size_, base::TimeDelta()); if (!frame) { VLOGF(1) << "Failed to create video frame"; return base::nullopt; } frame_layout_ = GpuBufferLayout::Create(fourcc, frame->coded_size(), frame->layout().planes()); } // The pool might become available because of |max_num_frames_| increased. // Notify the client if so. if (frame_available_cb_ && !IsExhausted_Locked()) std::move(frame_available_cb_).Run(); return frame_layout_; } bool PlatformVideoFramePool::IsExhausted() { DVLOGF(4); base::AutoLock auto_lock(lock_); return IsExhausted_Locked(); } bool PlatformVideoFramePool::IsExhausted_Locked() { DVLOGF(4); lock_.AssertAcquired(); return free_frames_.empty() && GetTotalNumFrames_Locked() >= max_num_frames_; } VideoFrame* PlatformVideoFramePool::UnwrapFrame( const VideoFrame& wrapped_frame) { DVLOGF(4); base::AutoLock auto_lock(lock_); auto it = frames_in_use_.find(GetDmabufId(wrapped_frame)); return (it == frames_in_use_.end()) ? nullptr : it->second; } void PlatformVideoFramePool::NotifyWhenFrameAvailable(base::OnceClosure cb) { DVLOGF(4); base::AutoLock auto_lock(lock_); if (!IsExhausted_Locked()) { parent_task_runner_->PostTask(FROM_HERE, std::move(cb)); return; } frame_available_cb_ = std::move(cb); } // static void PlatformVideoFramePool::OnFrameReleasedThunk( base::Optional<base::WeakPtr<PlatformVideoFramePool>> pool, scoped_refptr<base::SequencedTaskRunner> task_runner, scoped_refptr<VideoFrame> origin_frame) { DCHECK(pool); DVLOGF(4); task_runner->PostTask( FROM_HERE, base::BindOnce(&PlatformVideoFramePool::OnFrameReleased, *pool, std::move(origin_frame))); } void PlatformVideoFramePool::OnFrameReleased( scoped_refptr<VideoFrame> origin_frame) { DCHECK(parent_task_runner_->RunsTasksInCurrentSequence()); DVLOGF(4); base::AutoLock auto_lock(lock_); DmabufId frame_id = GetDmabufId(*origin_frame); auto it = frames_in_use_.find(frame_id); DCHECK(it != frames_in_use_.end()); frames_in_use_.erase(it); if (IsSameFormat_Locked(origin_frame->format(), origin_frame->coded_size())) InsertFreeFrame_Locked(std::move(origin_frame)); if (frame_available_cb_ && !IsExhausted_Locked()) std::move(frame_available_cb_).Run(); } void PlatformVideoFramePool::InsertFreeFrame_Locked( scoped_refptr<VideoFrame> frame) { DCHECK(frame); DVLOGF(4); lock_.AssertAcquired(); if (GetTotalNumFrames_Locked() < max_num_frames_) free_frames_.push_back(std::move(frame)); } size_t PlatformVideoFramePool::GetTotalNumFrames_Locked() const { DVLOGF(4); lock_.AssertAcquired(); return free_frames_.size() + frames_in_use_.size(); } bool PlatformVideoFramePool::IsSameFormat_Locked( VideoPixelFormat format, const gfx::Size& coded_size) const { DVLOGF(4); lock_.AssertAcquired(); return frame_layout_ && frame_layout_->fourcc().ToVideoPixelFormat() == format && frame_layout_->size() == coded_size; } size_t PlatformVideoFramePool::GetPoolSizeForTesting() { DVLOGF(4); base::AutoLock auto_lock(lock_); return free_frames_.size(); } } // namespace media
endlessm/chromium-browser
media/gpu/chromeos/platform_video_frame_pool.cc
C++
bsd-3-clause
8,134
""" PostgreSQL Session API ====================== The Session classes wrap the Queries :py:class:`Session <queries.Session>` and :py:class:`TornadoSession <queries.tornado_session.TornadoSession>` classes providing environment variable based configuration. Environment variables should be set using the ``PGSQL[_DBNAME]`` format where the value is a PostgreSQL URI. For PostgreSQL URI format, see: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING As example, given the environment variable: .. code:: python PGSQL_FOO = 'postgresql://bar:baz@foohost:6000/foo' and code for creating a :py:class:`Session` instance for the database name ``foo``: .. code:: python session = sprockets.postgresql.Session('foo') A :py:class:`queries.Session` object will be created that connects to Postgres running on ``foohost``, port ``6000`` using the username ``bar`` and the password ``baz``, connecting to the ``foo`` database. """ version_info = (2, 0, 1) __version__ = '.'.join(str(v) for v in version_info) import logging import os from queries import pool import queries from queries import tornado_session _ARGUMENTS = ['host', 'port', 'dbname', 'user', 'password'] LOGGER = logging.getLogger(__name__) # For ease of access to different cursor types from queries import DictCursor from queries import NamedTupleCursor from queries import RealDictCursor from queries import LoggingCursor from queries import MinTimeLoggingCursor # Expose exceptions so clients do not need to import queries as well from queries import DataError from queries import DatabaseError from queries import IntegrityError from queries import InterfaceError from queries import InternalError from queries import NotSupportedError from queries import OperationalError from queries import ProgrammingError from queries import QueryCanceledError from queries import TransactionRollbackError def _get_uri(dbname): """Return the URI for the specified database name from an environment variable. If dbname is blank, the ``PGSQL`` environment variable is used, otherwise the database name is cast to upper case and concatenated to ``PGSQL_`` and the URI is retrieved from ``PGSQL_DBNAME``. For example, if the value ``foo`` is passed in, the environment variable used would be ``PGSQL_FOO``. :param str dbname: The database name to construct the URI for :return: str :raises: KeyError """ if not dbname: return os.environ['PGSQL'] return os.environ['PGSQL_{0}'.format(dbname).upper()] class Session(queries.Session): """Extends queries.Session using configuration data that is stored in environment variables. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :param str dbname: PostgreSQL database name :param queries.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param str db_url: Optional database connection URL. Use this when you need to connect to a database that is only known at runtime. """ def __init__(self, dbname, cursor_factory=queries.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=pool.DEFAULT_MAX_SIZE, db_url=None): if db_url is None: db_url = _get_uri(dbname) super(Session, self).__init__(db_url, cursor_factory, pool_idle_ttl, pool_max_size) class TornadoSession(tornado_session.TornadoSession): """Extends queries.TornadoSession using configuration data that is stored in environment variables. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`query <queries.tornado_session.TornadoSession.query>` and :py:meth:`callproc <queries.tornado_session.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str dbname: PostgreSQL database name :param queries.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop ioloop: Pass in the instance of the tornado IOLoop you would like to use. Defaults to the global instance. :param str db_url: Optional database connection URL. Use this when you need to connect to a database that is only known at runtime. """ def __init__(self, dbname, cursor_factory=queries.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=tornado_session.DEFAULT_MAX_POOL_SIZE, io_loop=None, db_url=None): if db_url is None: db_url = _get_uri(dbname) super(TornadoSession, self).__init__(db_url, cursor_factory, pool_idle_ttl, pool_max_size, io_loop)
sprockets/sprockets.clients.postgresql
sprockets/clients/postgresql/__init__.py
Python
bsd-3-clause
5,585
import { Component, Input } from '@angular/core'; import { Router } from '@angular/router'; import { IInputButtons } from './toolbar'; @Component({ selector: 'app-toolbar', templateUrl: './toolbar.component.html', styleUrls: ['./toolbar.component.scss'] }) export class ToolbarComponent { @Input() buttons: IInputButtons; constructor( private router: Router ) { } logout() { localStorage.removeItem('token'); this.router.navigate(['/login']); } }
gios/diploma-nets
src/app/shared/toolbar/toolbar.component.ts
TypeScript
bsd-3-clause
479
/* line 1 "./ragel/tsdp_parser_header_M.jrl" */ /* * Copyright (C) 2012-2018 Doubango Telecom <http://www.doubango.org> * License: BSD * This file is part of Open Source sipML5 solution <http://www.sipml5.org> */ tsdp_header_M.prototype = Object.create(tsdp_header.prototype); /* line 49 "./ragel/tsdp_parser_header_M.jrl" */ /* line 17 "./src/headers/tsdp_header_M.js" */ _tsdp_machine_parser_header_M_actions = [ 0, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4 ]; _tsdp_machine_parser_header_M_key_offsets = [ 0, 0, 1, 3, 18, 33, 35, 39, 53, 54, 68, 70, 73, 88, 88, 103 ]; _tsdp_machine_parser_header_M_trans_keys = [ 109, 32, 61, 32, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 32, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 48, 57, 32, 47, 48, 57, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 10, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 48, 57, 32, 48, 57, 13, 32, 33, 37, 39, 47, 126, 42, 43, 45, 57, 65, 90, 95, 122, 13, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 13, 32, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 0 ]; _tsdp_machine_parser_header_M_single_lengths = [ 0, 1, 2, 5, 5, 0, 2, 4, 1, 4, 0, 1, 7, 0, 5, 6 ]; _tsdp_machine_parser_header_M_range_lengths = [ 0, 0, 0, 5, 5, 1, 1, 5, 0, 5, 1, 1, 4, 0, 5, 5 ]; _tsdp_machine_parser_header_M_index_offsets = [ 0, 0, 2, 5, 16, 27, 29, 33, 43, 45, 55, 57, 60, 72, 73, 84 ]; _tsdp_machine_parser_header_M_indicies = [ 0, 1, 0, 2, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 6, 1, 7, 8, 9, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 11, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 1, 13, 1, 7, 14, 1, 15, 16, 12, 12, 12, 17, 12, 12, 12, 12, 12, 1, 1, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 1, 20, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 1, 0 ]; _tsdp_machine_parser_header_M_trans_targs = [ 2, 0, 3, 4, 5, 4, 6, 7, 10, 6, 12, 13, 12, 11, 11, 8, 14, 9, 8, 15, 8, 14, 15 ]; _tsdp_machine_parser_header_M_trans_actions = [ 0, 0, 0, 1, 3, 0, 1, 5, 5, 0, 1, 0, 0, 1, 0, 7, 7, 0, 0, 1, 9, 9, 0 ]; _tsdp_machine_parser_header_M_eof_actions = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 9 ]; tsdp_machine_parser_header_M_start = 1; tsdp_machine_parser_header_M_first_final = 12; tsdp_machine_parser_header_M_error = 0; tsdp_machine_parser_header_M_en_main = 1; /* line 53 "./ragel/tsdp_parser_header_M.jrl" */ function tsdp_header_M(s_media, i_port, s_proto){ tsdp_header.call(this, tsdp_header_type_e.M); this.s_media = s_media; this.i_port = i_port; this.i_nports = 0; // number of ports this.s_proto = s_proto; this.as_fmt = new Array(); this.o_hdr_I = null; this.o_hdr_C = null; this.ao_hdr_B = new Array(); this.o_hdr_K = null; this.ao_hdr_A = new Array(); this.ao_hdr_Dummy = new Array(); } tsdp_header_M.prototype.toString = function(s_endline){ if(!s_endline){ s_endline = "\r\n"; } /* IMPORTANT: Keep the order. m= (media name and transport address) i=* (media title) c=* (connection information -- optional if included at session level) b=* (zero or more bandwidth information lines) k=* (encryption key) a=* (zero or more media attribute lines) */ var s_str = tsk_string_format("{0} {1}{2}{3} {4}", this.s_media, this.i_port, this.i_nports ? "/" : "", this.i_nports ? this.i_nports : "", this.s_proto); // FMTs for(var i = 0; i < this.as_fmt.length; ++i){ s_str += " " + this.as_fmt[i]; } var b_single_line = !this.o_hdr_I && !this.o_hdr_C && this.ao_hdr_B.length==0 && !this.o_hdr_K && this.ao_hdr_A.length.length==0; if(b_single_line){ return s_str; } // close the "m=" line s_str += s_endline; // i=* (media title) if(this.o_hdr_I){ s_str += this.o_hdr_I.tostring_full(false, s_endline); } // c=* (connection information -- optional if included at session level) if(this.o_hdr_C){ s_str += this.o_hdr_C.tostring_full(false, s_endline); } // b=* (zero or more bandwidth information lines) for(var i = 0; i < this.ao_hdr_B.length; ++i){ s_str += this.ao_hdr_B[i].tostring_full(false, s_endline); } // k=* (encryption key) if(this.o_hdr_K){ s_str += this.o_hdr_K.tostring_full(false, s_endline); } // a=* (zero or more media attribute lines) for(var i = 0; i < this.ao_hdr_A.length; ++i){ s_str += this.ao_hdr_A[i].tostring_full(false, s_endline); } // dummies for(var i = 0; i < this.ao_hdr_Dummy.length; ++i){ s_str += this.ao_hdr_Dummy[i].tostring_full(false, s_endline); } return s_str.substring(0, s_str.length - s_endline.length); } // for A headers, use "tsdp_header_A_removeAll_by_field()" tsdp_header_M.prototype.remove_header = function(e_type){ switch(e_type){ case tsdp_header_type_e.I: { this.o_hdr_I = null; break; } case tsdp_header_type_e.C: { this.o_hdr_C = null; break; } case tsdp_header_type_e.B: { this.ao_hdr_B.splice(0, this.ao_hdr_B.length); break; } case tsdp_header_type_e.K: { this.o_hdr_K = null; break; } } return 0; } tsdp_header_M.prototype.add_header = function(o_header){ if(!o_header){ tsk_utils_log_error("Invalid argument"); return -1; } switch(o_header.e_type){ case tsdp_header_type_e.I: { this.o_hdr_I = o_header; break; } case tsdp_header_type_e.C: { this.o_hdr_C = o_header; break; } case tsdp_header_type_e.B: { this.ao_hdr_B.push(o_header); break; } case tsdp_header_type_e.K: { this.o_hdr_K = o_header; break; } case tsdp_header_type_e.A: { this.ao_hdr_A.push(o_header); break; } } return 0; } tsdp_header_M.prototype.add_fmt = function(s_fmt){ if(s_fmt){ this.as_fmt.push(s_fmt); } } // add_headers(...) tsdp_header_M.prototype.add_headers = function(){ for(var i = 0; i < arguments.length; ++i){ if(arguments[i]){ this.add_header(arguments[i]); } } } tsdp_header_M.prototype.find_a_at = function(s_field, i_index) { if(!s_field || i_index < 0){ tsk_utils_log_error("Invalid argument"); return null; } var i_pos = 0; for(var i = 0; i < this.ao_hdr_A.length; ++i){ if(this.ao_hdr_A[i].s_field == s_field){ if(i_pos++ >= i_index){ return this.ao_hdr_A[i]; } } } return null; } tsdp_header_M.prototype.find_a = function(s_field) { return this.find_a_at(s_field, 0); } tsdp_header_M.prototype.get_rtpmap = function(s_fmt){ var i_fmt_len = s_fmt ? s_fmt.length : 0; if(i_fmt_len <= 0 || i_fmt_len > 3/*'0-255' or '*'*/){ tsk_utils_log_error("Invalid argument"); return null; } var s_rtpmap = null; /* e.g. AMR-WB/16000 */ var i_A_len, i_index = 0; var i_indexof; var o_hdr_A; /* find "a=rtpmap" */ while((o_hdr_A = this.find_a_at(i_index++))){ /* A->value would be: "98 AMR-WB/16000" */ if((i_A_len = o_hdr_A.s_value ? o_hdr_A.s_value.length : 0) < (i_fmt_len + 1/*space*/)){ continue; } if((i_indexof = tsk_string_index_of(o_hdr_A.s_value, i_A_len, s_fmt)) == 0 && (o_hdr_A.s_value[i_fmt_len] == ' ')){ s_rtpmap = o_hdr_A.s_value.substring(i_fmt_len+1, A_len); break; } } return s_rtpmap; } tsdp_header_M.prototype.get_fmtp = function(s_fmt){ var i_fmt_len = s_fmt ? s_fmt.length : 0; if(i_fmt_len <= 0 || i_fmt_len > 3/*'0-255' or '*'*/){ tsk_utils_log_error("Invalid argument"); return null; } var s_fmtp= null; /* e.g. octet-align=1 */ var i_A_len, i_index = 0; var i_indexof; var o_hdr_A; /* find "a=rtpmap" */ while((o_hdr_A = this.find_a_at(i_index++))){ /* A->value would be: "98 octet-align=1" */ if((i_A_len = o_hdr_A.s_value ? o_hdr_A.s_value.length : 0) < (i_fmt_len + 1/*space*/)){ continue; } if((i_indexof = tsk_string_index_of(o_hdr_A.s_value, i_A_len, s_fmt)) == 0 && (o_hdr_A.s_value[i_fmt_len] == ' ')){ s_fmtp = o_hdr_A.s_value.substring(i_fmt_len+1, A_len); break; } } return s_fmtp; } /* as per 3GPP TS 34.610 */ tsdp_header_M.prototype.hold = function(b_local){ var o_hdr_A; if((o_hdr_A = this.find_a(b_local ? "recvonly" : "sendonly"))){ // an "inactive" SDP attribute if the stream was previously set to "recvonly" media stream o_hdr_A.s_field = b_local ? "inactive" : "recvonly"; } else if((o_hdr_A = this.find_a("sendrecv"))){ // a "sendonly" SDP attribute if the stream was previously set to "sendrecv" media stream o_hdr_A.s_field = b_local ? "sendonly" : "recvonly"; } else{ // default value is sendrecv. hold on default --> sendonly if(!(o_hdr_A = this.find_a(b_local ? "sendonly" : "recvonly")) && !(o_hdr_A = this.find_a("inactive"))){ var o_hdr_newA; if((o_hdr_newA = new tsdp_header_A(b_local ? "sendonly" : "recvonly", null))){ this.add_header(o_hdr_newA); } } } return 0; } /* as per 3GPP TS 34.610 */ tsdp_header_M.prototype.set_holdresume_att = function(b_lo_held, b_ro_held){ var o_hdr_A; var hold_resume_atts = [["sendrecv", "recvonly"],["sendonly", "inactive"]]; if((o_hdr_A = this.find_a("sendrecv")) || (o_hdr_A = this.find_a("sendonly")) || (o_hdr_A = this.find_a("recvonly")) || (o_hdr_A = this.find_a("inactive"))){ o_hdr_A.s_field = hold_resume_atts[b_lo_held ? 1 : 0][b_ro_held ? 1 : 0]; } else{ var o_hdr_newA; if((o_hdr_newA = new tsdp_header_A(hold_resume_atts[b_lo_held ? 1 : 0][b_ro_held ? 1 : 0], null))){ this.add_headers(o_hdr_newA); } } return 0; } tsdp_header_M.prototype.is_held = function(b_local){ /* both cases */ if(this.find_a("inactive")){ return true; } if(b_local){ return this.find_a("recvonly") ? true : false; } else{ return this.find_a("sendonly") ? true : false; } } /* as per 3GPP TS 34.610 */ tsdp_header_M.prototype.resume = function(b_local){ var o_hdr_A; if((o_hdr_A = this.find_a("inactive"))){ // a "recvonly" SDP attribute if the stream was previously an inactive media stream o_hdr_A.s_field = b_local ? "recvonly" : "sendonly"; } else if((o_hdr_A = this.find_a(b_local ? "sendonly" : "recvonly"))){ // a "sendrecv" SDP attribute if the stream was previously a sendonly media stream, or the attribute may be omitted, since sendrecv is the default o_hdr_A.s_field = sendrecv; } return 0; } tsdp_header_M.prototype.Parse = function(s_str){ var cs = 0; var p = 0; var pe = s_str.length; var eof = pe; var data = tsk_buff_str2ib(s_str); var i_tag_start; var hdr_M = new tsdp_header_M(null, 0, null); /* line 419 "./src/headers/tsdp_header_M.js" */ { cs = tsdp_machine_parser_header_M_start; } /* JSCodeGen::writeInit */ /* line 370 "./ragel/tsdp_parser_header_M.jrl" */ /* line 426 "./src/headers/tsdp_header_M.js" */ { var _klen, _trans, _keys, _ps, _widec, _acts, _nacts; var _goto_level, _resume, _eof_trans, _again, _test_eof; var _out; _klen = _trans = _keys = _acts = _nacts = null; _goto_level = 0; _resume = 10; _eof_trans = 15; _again = 20; _test_eof = 30; _out = 40; while (true) { _trigger_goto = false; if (_goto_level <= 0) { if (p == pe) { _goto_level = _test_eof; continue; } if (cs == 0) { _goto_level = _out; continue; } } if (_goto_level <= _resume) { _keys = _tsdp_machine_parser_header_M_key_offsets[cs]; _trans = _tsdp_machine_parser_header_M_index_offsets[cs]; _klen = _tsdp_machine_parser_header_M_single_lengths[cs]; _break_match = false; do { if (_klen > 0) { _lower = _keys; _upper = _keys + _klen - 1; while (true) { if (_upper < _lower) { break; } _mid = _lower + ( (_upper - _lower) >> 1 ); if (data[p] < _tsdp_machine_parser_header_M_trans_keys[_mid]) { _upper = _mid - 1; } else if (data[p] > _tsdp_machine_parser_header_M_trans_keys[_mid]) { _lower = _mid + 1; } else { _trans += (_mid - _keys); _break_match = true; break; }; } /* while */ if (_break_match) { break; } _keys += _klen; _trans += _klen; } _klen = _tsdp_machine_parser_header_M_range_lengths[cs]; if (_klen > 0) { _lower = _keys; _upper = _keys + (_klen << 1) - 2; while (true) { if (_upper < _lower) { break; } _mid = _lower + (((_upper-_lower) >> 1) & ~1); if (data[p] < _tsdp_machine_parser_header_M_trans_keys[_mid]) { _upper = _mid - 2; } else if (data[p] > _tsdp_machine_parser_header_M_trans_keys[_mid+1]) { _lower = _mid + 2; } else { _trans += ((_mid - _keys) >> 1); _break_match = true; break; } } /* while */ if (_break_match) { break; } _trans += _klen } } while (false); _trans = _tsdp_machine_parser_header_M_indicies[_trans]; cs = _tsdp_machine_parser_header_M_trans_targs[_trans]; if (_tsdp_machine_parser_header_M_trans_actions[_trans] != 0) { _acts = _tsdp_machine_parser_header_M_trans_actions[_trans]; _nacts = _tsdp_machine_parser_header_M_actions[_acts]; _acts += 1; while (_nacts > 0) { _nacts -= 1; _acts += 1; switch (_tsdp_machine_parser_header_M_actions[_acts - 1]) { case 0: /* line 14 "./ragel/tsdp_parser_header_M.jrl" */ i_tag_start = p; break; case 1: /* line 18 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.s_media = tsk_ragel_parser_get_string(s_str, p, i_tag_start); break; case 2: /* line 22 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.i_port= tsk_ragel_parser_get_int(s_str, p, i_tag_start); break; case 3: /* line 30 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.s_proto = tsk_ragel_parser_get_string(s_str, p, i_tag_start); break; case 4: /* line 34 "./ragel/tsdp_parser_header_M.jrl" */ tsk_ragel_parser_add_string(s_str, p, i_tag_start, hdr_M.as_fmt); break; /* line 535 "./src/headers/tsdp_header_M.js" */ } /* action switch */ } } if (_trigger_goto) { continue; } } if (_goto_level <= _again) { if (cs == 0) { _goto_level = _out; continue; } p += 1; if (p != pe) { _goto_level = _resume; continue; } } if (_goto_level <= _test_eof) { if (p == eof) { __acts = _tsdp_machine_parser_header_M_eof_actions[cs]; __nacts = _tsdp_machine_parser_header_M_actions[__acts]; __acts += 1; while (__nacts > 0) { __nacts -= 1; __acts += 1; switch (_tsdp_machine_parser_header_M_actions[__acts - 1]) { case 3: /* line 30 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.s_proto = tsk_ragel_parser_get_string(s_str, p, i_tag_start); break; case 4: /* line 34 "./ragel/tsdp_parser_header_M.jrl" */ tsk_ragel_parser_add_string(s_str, p, i_tag_start, hdr_M.as_fmt); break; /* line 573 "./src/headers/tsdp_header_M.js" */ } /* eof action switch */ } if (_trigger_goto) { continue; } } } if (_goto_level <= _out) { break; } } } /* line 371 "./ragel/tsdp_parser_header_M.jrl" */ if( cs < /* line 590 "./src/headers/tsdp_header_M.js" */ 12 /* line 372 "./ragel/tsdp_parser_header_M.jrl" */ ){ tsk_utils_log_error("Failed to parse \"m=\" header: " + s_str); return null; } return hdr_M; }
DoubangoTelecom/sipml5
src/tinySDP/src/headers/tsdp_header_M.js
JavaScript
bsd-3-clause
15,015
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. namespace VsChromium.Server.Threads { public interface ITaskQueueFactory { ITaskQueue CreateQueue(string description); } }
chromium/vs-chromium
src/Server/Threads/ITaskQueueFactory.cs
C#
bsd-3-clause
309
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace Adteam\Core\Authorization\Repository; /** * Description of OauthUsersRepository * * @author dev */ use Doctrine\ORM\EntityRepository; class OauthUsersRepository extends EntityRepository { /** * * @param type $username * @return type */ public function hasEnabledUser($username) { $currentRepo = $this; return $this->_em->transactional(function () use($currentRepo, $username) { //Get Core User $user = $currentRepo ->createQueryBuilder('U') ->where('U.username LIKE :username') ->setParameter('username', $username, \Doctrine\DBAL\Types\Type::STRING) ->andWhere('U.enabled = :enabled') ->setParameter('enabled', 1) ->andWhere('U.deletedAt is NULL') ->getQuery() ->getOneOrNullResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY); return $user; }); } /** * * @param type $username * @return type */ public function fetchByOne($username) { return $this ->createQueryBuilder('U')->select('R.role,U.id') ->join('U.role', 'R') ->where('U.username = :username')->setParameter('username', $username) ->getQuery()->getSingleResult(); } }
CookieShop/core-authorization
src/Repository/OauthUsersRepository.php
PHP
bsd-3-clause
1,614
<?php class m131006_014701_p3pages_authItems extends CDbMigration { public function up() { $this->insert( "AuthItem", array( "name" => "P3pages.P3Page.Create", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3Page.View", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3Page.Update", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3Page.Delete", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); // Data for table 'AuthItemChild' $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3Page.Create", ) ); $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3Page.View", ) ); $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3Page.Update", ) ); $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3Page.Delete", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3PageTranslation.Create", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3PageTranslation.View", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3PageTranslation.Update", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); $this->insert( "AuthItem", array( "name" => "P3pages.P3PageTranslation.Delete", "type" => "0", "description" => null, "bizrule" => null, "data" => "N;", ) ); // Data for table 'AuthItemChild' $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3PageTranslation.Create", ) ); $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3PageTranslation.View", ) ); $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3PageTranslation.Update", ) ); $this->insert( "AuthItemChild", array( "parent" => "Editor", "child" => "P3pages.P3PageTranslation.Delete", ) ); } public function down() { } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }
motin/giic-gtc-hybrid-template-demo
app/migrations/rights/m131006_014701_p3pages_authItems.php
PHP
bsd-3-clause
4,506
<?php namespace frontend\controllers; use Yii; use app\models\BantuanPenganjuranKejohanan; use frontend\models\BantuanPenganjuranKejohananSearch; use app\models\BantuanPenganjuranKejohananKewangan; use frontend\models\BantuanPenganjuranKejohananKewanganSearch; use app\models\BantuanPenganjuranKejohananBayaran; use frontend\models\BantuanPenganjuranKejohananBayaranSearch; use app\models\BantuanPenganjuranKejohananElemen; use frontend\models\BantuanPenganjuranKejohananElemenSearch; use app\models\BantuanPenganjuranKejohananDianjurkan; use frontend\models\BantuanPenganjuranKejohananDianjurkanSearch; use app\models\BantuanPenganjuranKejohananOlehMsn; use frontend\models\BantuanPenganjuranKejohananOlehMsnSearch; use app\models\MsnLaporan; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\web\UploadedFile; use yii\helpers\BaseUrl; use app\models\general\Upload; use app\models\general\GeneralVariable; use app\models\general\GeneralLabel; use common\models\general\GeneralFunction; // table reference use app\models\RefSukan; use app\models\RefBandar; use app\models\RefNegeri; use app\models\RefBank; use app\models\RefPeringkatBantuanPenganjuranKejohanan; use app\models\ProfilBadanSukan; use app\models\RefStatusBantuanPenganjuranKejohanan; use common\models\User; /** * BantuanPenganjuranKejohananController implements the CRUD actions for BantuanPenganjuranKejohanan model. */ class BantuanPenganjuranKejohananController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all BantuanPenganjuranKejohanan models. * @return mixed */ public function actionIndex() { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $queryParams = Yii::$app->request->queryParams; if(isset(Yii::$app->user->identity->peranan_akses['MSN']['bantuan-penganjuran-kejohanan']['data-sendiri'])){ $queryParams['BantuanPenganjuranKejohananSearch']['created_by'] = Yii::$app->user->identity->id; } if(isset(Yii::$app->user->identity->peranan_akses['MSN']['bantuan-penganjuran-kejohanan']['kelulusan'])) { $queryParams['BantuanPenganjuranKejohananSearch']['hantar_flag'] = 1; } $searchModel = new BantuanPenganjuranKejohananSearch(); $dataProvider = $searchModel->search($queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single BantuanPenganjuranKejohanan model. * @param integer $id * @return mixed */ public function actionView($id) { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = $this->findModel($id); $ref = RefSukan::findOne(['id' => $model->sukan]); $model->sukan = $ref['desc']; $ref = RefBandar::findOne(['id' => $model->alamat_bandar]); $model->alamat_bandar = $ref['desc']; $ref = RefNegeri::findOne(['id' => $model->alamat_negeri]); $model->alamat_negeri = $ref['desc']; $ref = RefBank::findOne(['id' => $model->nama_bank]); $model->nama_bank = $ref['desc']; $ref = RefPeringkatBantuanPenganjuranKejohanan::findOne(['id' => $model->peringkat]); $model->peringkat = $ref['desc']; $ref = ProfilBadanSukan::findOne(['profil_badan_sukan' => $model->badan_sukan]); $model->badan_sukan = $ref['nama_badan_sukan']; $model->status_permohonan_id = $model->status_permohonan; $ref = RefStatusBantuanPenganjuranKejohanan::findOne(['id' => $model->status_permohonan]); $model->status_permohonan = $ref['desc']; $model->selesai = GeneralLabel::getYesNoLabel($model->selesai); if($model->tarikh_mula != "") {$model->tarikh_mula = GeneralFunction::convert($model->tarikh_mula, GeneralFunction::TYPE_DATE);} if($model->tarikh_tamat != "") {$model->tarikh_tamat = GeneralFunction::convert($model->tarikh_tamat, GeneralFunction::TYPE_DATE);} if($model->tarikh_permohonan != "") {$model->tarikh_permohonan = GeneralFunction::convert($model->tarikh_permohonan, GeneralFunction::TYPE_DATETIME);} if($model->tarikh_jkb != "") {$model->tarikh_jkb = GeneralFunction::convert($model->tarikh_jkb, GeneralFunction::TYPE_DATE);} $queryPar = null; $queryPar['BantuanPenganjuranKejohananKewanganSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananBayaranSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananElemenSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananDianjurkanSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananOlehMsnSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $searchModelBantuanPenganjuranKejohananKewangan = new BantuanPenganjuranKejohananKewanganSearch(); $dataProviderBantuanPenganjuranKejohananKewangan = $searchModelBantuanPenganjuranKejohananKewangan->search($queryPar); $searchModelBantuanPenganjuranKejohananBayaran = new BantuanPenganjuranKejohananBayaranSearch(); $dataProviderBantuanPenganjuranKejohananBayaran = $searchModelBantuanPenganjuranKejohananBayaran->search($queryPar); $searchModelBantuanPenganjuranKejohananElemen = new BantuanPenganjuranKejohananElemenSearch(); $dataProviderBantuanPenganjuranKejohananElemen = $searchModelBantuanPenganjuranKejohananElemen->search($queryPar); $searchModelBantuanPenganjuranKejohananDianjurkan = new BantuanPenganjuranKejohananDianjurkanSearch(); $dataProviderBantuanPenganjuranKejohananDianjurkan = $searchModelBantuanPenganjuranKejohananDianjurkan->search($queryPar); $searchModelBantuanPenganjuranKejohananOlehMsn = new BantuanPenganjuranKejohananOlehMsnSearch(); $dataProviderBantuanPenganjuranKejohananOlehMsn = $searchModelBantuanPenganjuranKejohananOlehMsn->search($queryPar); return $this->render('view', [ 'model' => $model, 'searchModelBantuanPenganjuranKejohananKewangan' => $searchModelBantuanPenganjuranKejohananKewangan, 'dataProviderBantuanPenganjuranKejohananKewangan' => $dataProviderBantuanPenganjuranKejohananKewangan, 'searchModelBantuanPenganjuranKejohananBayaran' => $searchModelBantuanPenganjuranKejohananBayaran, 'dataProviderBantuanPenganjuranKejohananBayaran' => $dataProviderBantuanPenganjuranKejohananBayaran, 'searchModelBantuanPenganjuranKejohananElemen' => $searchModelBantuanPenganjuranKejohananElemen, 'dataProviderBantuanPenganjuranKejohananElemen' => $dataProviderBantuanPenganjuranKejohananElemen, 'searchModelBantuanPenganjuranKejohananDianjurkan' => $searchModelBantuanPenganjuranKejohananDianjurkan, 'dataProviderBantuanPenganjuranKejohananDianjurkan' => $dataProviderBantuanPenganjuranKejohananDianjurkan, 'searchModelBantuanPenganjuranKejohananOlehMsn' => $searchModelBantuanPenganjuranKejohananOlehMsn, 'dataProviderBantuanPenganjuranKejohananOlehMsn' => $dataProviderBantuanPenganjuranKejohananOlehMsn, 'readonly' => true, ]); } /** * Creates a new BantuanPenganjuranKejohanan model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = new BantuanPenganjuranKejohanan(); if(Yii::$app->user->identity->profil_badan_sukan){ $model->badan_sukan = Yii::$app->user->identity->profil_badan_sukan; } $queryPar = null; Yii::$app->session->open(); if(isset(Yii::$app->session->id)){ $queryPar['BantuanPenganjuranKejohananKewanganSearch']['session_id'] = Yii::$app->session->id; $queryPar['BantuanPenganjuranKejohananBayaranSearch']['session_id'] = Yii::$app->session->id; $queryPar['BantuanPenganjuranKejohananElemenSearch']['session_id'] = Yii::$app->session->id; $queryPar['BantuanPenganjuranKejohananDianjurkanSearch']['session_id'] = Yii::$app->session->id; $queryPar['BantuanPenganjuranKejohananOlehMsnSearch']['session_id'] = Yii::$app->session->id; } $searchModelBantuanPenganjuranKejohananKewangan = new BantuanPenganjuranKejohananKewanganSearch(); $dataProviderBantuanPenganjuranKejohananKewangan = $searchModelBantuanPenganjuranKejohananKewangan->search($queryPar); $searchModelBantuanPenganjuranKejohananBayaran = new BantuanPenganjuranKejohananBayaranSearch(); $dataProviderBantuanPenganjuranKejohananBayaran = $searchModelBantuanPenganjuranKejohananBayaran->search($queryPar); $searchModelBantuanPenganjuranKejohananElemen = new BantuanPenganjuranKejohananElemenSearch(); $dataProviderBantuanPenganjuranKejohananElemen = $searchModelBantuanPenganjuranKejohananElemen->search($queryPar); $searchModelBantuanPenganjuranKejohananDianjurkan = new BantuanPenganjuranKejohananDianjurkanSearch(); $dataProviderBantuanPenganjuranKejohananDianjurkan = $searchModelBantuanPenganjuranKejohananDianjurkan->search($queryPar); $searchModelBantuanPenganjuranKejohananOlehMsn = new BantuanPenganjuranKejohananOlehMsnSearch(); $dataProviderBantuanPenganjuranKejohananOlehMsn = $searchModelBantuanPenganjuranKejohananOlehMsn->search($queryPar); if ($model->load(Yii::$app->request->post()) && $model->save()) { $file = UploadedFile::getInstance($model, 'kertas_kerja'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-kertas_kerja"; if($file){ $model->kertas_kerja = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'surat_rasmi_badan_sukan_ms_negeri'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-surat_rasmi_badan_sukan_ms_negeri"; if($file){ $model->surat_rasmi_badan_sukan_ms_negeri = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'permohonan_rasmi_dari_ahli_gabungan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-permohonan_rasmi_dari_ahli_gabungan"; if($file){ $model->permohonan_rasmi_dari_ahli_gabungan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'maklumat_lain_sokongan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-maklumat_lain_sokongan"; if($file){ $model->maklumat_lain_sokongan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'surat_kelulusan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-surat_kelulusan"; if($file){ $model->surat_kelulusan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } if(isset(Yii::$app->session->id)){ BantuanPenganjuranKejohananKewangan::updateAll(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id], 'session_id = "'.Yii::$app->session->id.'"'); BantuanPenganjuranKejohananKewangan::updateAll(['session_id' => ''], 'bantuan_penganjuran_kejohanan_id = "'.$model->bantuan_penganjuran_kejohanan_id.'"'); BantuanPenganjuranKejohananBayaran::updateAll(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id], 'session_id = "'.Yii::$app->session->id.'"'); BantuanPenganjuranKejohananBayaran::updateAll(['session_id' => ''], 'bantuan_penganjuran_kejohanan_id = "'.$model->bantuan_penganjuran_kejohanan_id.'"'); BantuanPenganjuranKejohananElemen::updateAll(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id], 'session_id = "'.Yii::$app->session->id.'"'); BantuanPenganjuranKejohananElemen::updateAll(['session_id' => ''], 'bantuan_penganjuran_kejohanan_id = "'.$model->bantuan_penganjuran_kejohanan_id.'"'); BantuanPenganjuranKejohananDianjurkan::updateAll(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id], 'session_id = "'.Yii::$app->session->id.'"'); BantuanPenganjuranKejohananDianjurkan::updateAll(['session_id' => ''], 'bantuan_penganjuran_kejohanan_id = "'.$model->bantuan_penganjuran_kejohanan_id.'"'); BantuanPenganjuranKejohananOlehMsn::updateAll(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id], 'session_id = "'.Yii::$app->session->id.'"'); BantuanPenganjuranKejohananOlehMsn::updateAll(['session_id' => ''], 'bantuan_penganjuran_kejohanan_id = "'.$model->bantuan_penganjuran_kejohanan_id.'"'); } if($model->save()){ return $this->redirect(['view', 'id' => $model->bantuan_penganjuran_kejohanan_id]); } } return $this->render('create', [ 'model' => $model, 'searchModelBantuanPenganjuranKejohananKewangan' => $searchModelBantuanPenganjuranKejohananKewangan, 'dataProviderBantuanPenganjuranKejohananKewangan' => $dataProviderBantuanPenganjuranKejohananKewangan, 'searchModelBantuanPenganjuranKejohananBayaran' => $searchModelBantuanPenganjuranKejohananBayaran, 'dataProviderBantuanPenganjuranKejohananBayaran' => $dataProviderBantuanPenganjuranKejohananBayaran, 'searchModelBantuanPenganjuranKejohananElemen' => $searchModelBantuanPenganjuranKejohananElemen, 'dataProviderBantuanPenganjuranKejohananElemen' => $dataProviderBantuanPenganjuranKejohananElemen, 'searchModelBantuanPenganjuranKejohananDianjurkan' => $searchModelBantuanPenganjuranKejohananDianjurkan, 'dataProviderBantuanPenganjuranKejohananDianjurkan' => $dataProviderBantuanPenganjuranKejohananDianjurkan, 'searchModelBantuanPenganjuranKejohananOlehMsn' => $searchModelBantuanPenganjuranKejohananOlehMsn, 'dataProviderBantuanPenganjuranKejohananOlehMsn' => $dataProviderBantuanPenganjuranKejohananOlehMsn, 'readonly' => false, ]); } /** * Updates an existing BantuanPenganjuranKejohanan model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = $this->findModel($id); $existingKertasKerja = $model->kertas_kerja; $existingSuratRasmiBadanSukanzMsNegeri = $model->surat_rasmi_badan_sukan_ms_negeri; $model->status_permohonan_id = $model->status_permohonan; if($model->load(Yii::$app->request->post())){ $file = UploadedFile::getInstance($model, 'kertas_kerja'); if($file){ //valid file to upload //upload file to server // delete upload file /*if($existingKertasKerja != ""){ self::actionDeleteupload($id, 'kertas_kerja'); } $filename = $model->bantuan_penganjuran_kejohanan_id . "-kertas_kerja"; $model->kertas_kerja = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename);*/ } else { //invalid file to upload //remain existing file $model->kertas_kerja = $existingKertasKerja; } $file = UploadedFile::getInstance($model, 'surat_rasmi_badan_sukan_ms_negeri'); if($file){ //valid file to upload //upload file to server // delete upload file /*if($existingSuratRasmiBadanSukanzMsNegeri != ""){ self::actionDeleteupload($id, 'surat_rasmi_badan_sukan_ms_negeri'); } $filename = $model->bantuan_penganjuran_kejohanan_id . "-surat_rasmi_badan_sukan_ms_negeri"; $model->surat_rasmi_badan_sukan_ms_negeri = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename);*/ } else { //invalid file to upload //remain existing file $model->surat_rasmi_badan_sukan_ms_negeri = $existingSuratRasmiBadanSukanzMsNegeri; } /*$file = UploadedFile::getInstance($model, 'permohonan_rasmi_dari_ahli_gabungan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-permohonan_rasmi_dari_ahli_gabungan"; if($file){ $model->permohonan_rasmi_dari_ahli_gabungan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'maklumat_lain_sokongan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-maklumat_lain_sokongan"; if($file){ $model->maklumat_lain_sokongan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'surat_kelulusan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-surat_kelulusan"; if($file){ $model->surat_kelulusan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); }*/ } $queryPar = null; $queryPar['BantuanPenganjuranKejohananKewanganSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananBayaranSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananElemenSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananDianjurkanSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $queryPar['BantuanPenganjuranKejohananOlehMsnSearch']['bantuan_penganjuran_kejohanan_id'] = $id; $searchModelBantuanPenganjuranKejohananKewangan = new BantuanPenganjuranKejohananKewanganSearch(); $dataProviderBantuanPenganjuranKejohananKewangan = $searchModelBantuanPenganjuranKejohananKewangan->search($queryPar); $searchModelBantuanPenganjuranKejohananBayaran = new BantuanPenganjuranKejohananBayaranSearch(); $dataProviderBantuanPenganjuranKejohananBayaran = $searchModelBantuanPenganjuranKejohananBayaran->search($queryPar); $searchModelBantuanPenganjuranKejohananElemen = new BantuanPenganjuranKejohananElemenSearch(); $dataProviderBantuanPenganjuranKejohananElemen = $searchModelBantuanPenganjuranKejohananElemen->search($queryPar); $searchModelBantuanPenganjuranKejohananDianjurkan = new BantuanPenganjuranKejohananDianjurkanSearch(); $dataProviderBantuanPenganjuranKejohananDianjurkan = $searchModelBantuanPenganjuranKejohananDianjurkan->search($queryPar); $searchModelBantuanPenganjuranKejohananOlehMsn = new BantuanPenganjuranKejohananOlehMsnSearch(); $dataProviderBantuanPenganjuranKejohananOlehMsn = $searchModelBantuanPenganjuranKejohananOlehMsn->search($queryPar); if (Yii::$app->request->post() && $model->save()) { $file = UploadedFile::getInstance($model, 'kertas_kerja'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-kertas_kerja"; if($file){ $model->kertas_kerja = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'surat_rasmi_badan_sukan_ms_negeri'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-surat_rasmi_badan_sukan_ms_negeri"; if($file){ $model->surat_rasmi_badan_sukan_ms_negeri = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'permohonan_rasmi_dari_ahli_gabungan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-permohonan_rasmi_dari_ahli_gabungan"; if($file){ $model->permohonan_rasmi_dari_ahli_gabungan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'maklumat_lain_sokongan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-maklumat_lain_sokongan"; if($file){ $model->maklumat_lain_sokongan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } $file = UploadedFile::getInstance($model, 'surat_kelulusan'); $filename = $model->bantuan_penganjuran_kejohanan_id . "-surat_kelulusan"; if($file){ $model->surat_kelulusan = Upload::uploadFile($file, Upload::bantuanPenganjuranKejohananFolder, $filename); } if($model->save()){ return $this->redirect(['view', 'id' => $model->bantuan_penganjuran_kejohanan_id]); } } return $this->render('update', [ 'model' => $model, 'searchModelBantuanPenganjuranKejohananKewangan' => $searchModelBantuanPenganjuranKejohananKewangan, 'dataProviderBantuanPenganjuranKejohananKewangan' => $dataProviderBantuanPenganjuranKejohananKewangan, 'searchModelBantuanPenganjuranKejohananBayaran' => $searchModelBantuanPenganjuranKejohananBayaran, 'dataProviderBantuanPenganjuranKejohananBayaran' => $dataProviderBantuanPenganjuranKejohananBayaran, 'searchModelBantuanPenganjuranKejohananElemen' => $searchModelBantuanPenganjuranKejohananElemen, 'dataProviderBantuanPenganjuranKejohananElemen' => $dataProviderBantuanPenganjuranKejohananElemen, 'searchModelBantuanPenganjuranKejohananDianjurkan' => $searchModelBantuanPenganjuranKejohananDianjurkan, 'dataProviderBantuanPenganjuranKejohananDianjurkan' => $dataProviderBantuanPenganjuranKejohananDianjurkan, 'searchModelBantuanPenganjuranKejohananOlehMsn' => $searchModelBantuanPenganjuranKejohananOlehMsn, 'dataProviderBantuanPenganjuranKejohananOlehMsn' => $dataProviderBantuanPenganjuranKejohananOlehMsn, 'readonly' => false, ]); } /** * Deletes an existing BantuanPenganjuranKejohanan model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } // delete upload file self::actionDeleteupload($id, 'kertas_kerja'); self::actionDeleteupload($id, 'surat_rasmi_badan_sukan_ms_negeri'); self::actionDeleteupload($id, 'permohonan_rasmi_dari_ahli_gabungan'); self::actionDeleteupload($id, 'maklumat_lain_sokongan'); $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Updates an existing BantuanPenganjuranKejohanan model. * If approved is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionHantar($id) { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = $this->findModel($id); $model->hantar_flag = 1; // set approved $model->tarikh_hantar = GeneralFunction::getCurrentTimestamp(); // set date capture $model->tarikh_permohonan = GeneralFunction::getCurrentTimestamp(); $model->status_permohonan = RefStatusBantuanPenganjuranKejohanan::SEDANG_DIPROSES; $model->selesai = 0; // set approved $model->save(); if (($modelUsers = User::find()->joinWith('refUserPeranan')->andFilterWhere(['like', 'tbl_user_peranan.peranan_akses', 'pemberitahuan_emel_bantuan-penganjuran-kejohanan'])->groupBy('id')->all()) !== null) { $refProfilBadanSukan = ProfilBadanSukan::findOne(['profil_badan_sukan' => $model->badan_sukan]); foreach($modelUsers as $modelUser){ if($modelUser->email && $modelUser->email != ""){ //echo "E-mail: " . $modelUser->email . "\n"; Yii::$app->mailer->compose() ->setTo($modelUser->email) ->setFrom('noreply@spsb.com') ->setSubject('Pemberitahuan - Permohonan Baru: Bantuan Penganjuran Kejohanan') ->setHtmlBody('Assalamualaikum dan Salam Sejahtera, <br><br> Terdapat permohonan baru yang diterima: <br>Badan Sukan: ' . $refProfilBadanSukan['nama_badan_sukan'] . ' <br>Nama Kejohanan / Pertandingan: ' . $model->nama_kejohanan_pertandingan . ' <br>Tempat: ' . $model->tempat . ' <br>Tarikh Mula: ' . $model->tarikh_mula . ' <br>Tarikh Tamat: ' . $model->tarikh_tamat . ' <br>Jumlah bantuan yang dipohon : RM ' . $model->jumlah_bantuan_yang_dipohon . ' <br><br> Link: ' . BaseUrl::to(['bantuan-penganjuran-kejohanan/view', 'id' => $model->bantuan_penganjuran_kejohanan_id], true) . ' <br><br> Sekian. <br><br> "KE ARAH KECEMERLANGAN SUKAN"<br> Majlis Sukan Negara Malaysia. ')->send(); } } } return $this->redirect(['view', 'id' => $model->bantuan_penganjuran_kejohanan_id]); } /** * Finds the BantuanPenganjuranKejohanan model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return BantuanPenganjuranKejohanan the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = BantuanPenganjuranKejohanan::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } // Add function for delete image or file public function actionDeleteupload($id, $field) { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $img = $this->findModel($id)->$field; if($img){ /* if (!unlink($img)) { return false; } */ @unlink($img); } $img = $this->findModel($id); $img->$field = NULL; $img->update(); return $this->redirect(['update', 'id' => $id]); } public function actionLaporanStatistikBantuanPenganjuranKejohananMengikutBadanSukan() { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = new MsnLaporan(); $model->format = 'html'; if ($model->load(Yii::$app->request->post())) { if($model->format == "html") { $report_url = BaseUrl::to(['generate-laporan-statistik-bantuan-penganjuran-kejohanan-mengikut-badan-sukan' , 'tarikh_hingga' => $model->tarikh_hingga , 'tarikh_dari' => $model->tarikh_dari , 'format' => $model->format ], true); echo "<script type=\"text/javascript\" language=\"Javascript\">window.open('".$report_url."');</script>"; } else { return $this->redirect(['generate-laporan-statistik-bantuan-penganjuran-kejohanan-mengikut-badan-sukan' , 'tarikh_dari' => $model->tarikh_dari , 'tarikh_hingga' => $model->tarikh_hingga , 'format' => $model->format ]); } } return $this->render('laporan_statistik_bantuan_penganjuran_kejohanan_mengikut_badan_sukan', [ 'model' => $model, 'readonly' => false, ]); } public function actionGenerateLaporanStatistikBantuanPenganjuranKejohananMengikutBadanSukan($tarikh_dari, $tarikh_hingga, $format) { if($tarikh_dari == "") $tarikh_dari = array(); else $tarikh_dari = array($tarikh_dari); if($tarikh_hingga == "") $tarikh_hingga = array(); else $tarikh_hingga = array($tarikh_hingga); $controls = array( 'FROM_DATE' => $tarikh_dari, 'TO_DATE' => $tarikh_hingga, ); GeneralFunction::generateReport('/spsb/MSN/LaporanStatistikBantuanPenganjuranKejohananMengikutBadanSukan', $format, $controls, 'laporan_statistik_bantuan_penganjuran_kejohanan_mengikut_badan_sukan'); } public function actionLaporanSenaraiBantuanGeranKejohanan() { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = new MsnLaporan(); $model->format = 'html'; if ($model->load(Yii::$app->request->post())) { if($model->format == "html") { $report_url = BaseUrl::to(['generate-laporan-senarai-bantuan-geran-kejohanan' , 'tarikh_hingga' => $model->tarikh_hingga , 'tarikh_dari' => $model->tarikh_dari , 'format' => $model->format ], true); echo "<script type=\"text/javascript\" language=\"Javascript\">window.open('".$report_url."');</script>"; } else { return $this->redirect(['generate-laporan-senarai-bantuan-geran-kejohanan' , 'tarikh_dari' => $model->tarikh_dari , 'tarikh_hingga' => $model->tarikh_hingga , 'format' => $model->format ]); } } return $this->render('laporan_senarai_bantuan_geran_kejohanan', [ 'model' => $model, 'readonly' => false, ]); } public function actionGenerateLaporanSenaraiBantuanGeranKejohanan($tarikh_dari, $tarikh_hingga, $format) { if($tarikh_dari == "") $tarikh_dari = array(); else $tarikh_dari = array($tarikh_dari); if($tarikh_hingga == "") $tarikh_hingga = array(); else $tarikh_hingga = array($tarikh_hingga); $controls = array( 'FROM_DATE' => $tarikh_dari, 'TO_DATE' => $tarikh_hingga, ); GeneralFunction::generateReport('/spsb/MSN/LaporanSenaraiBantuanGeranKejohanan', $format, $controls, 'laporan_senarai_bantuan_geran_kejohanan'); } public function actionPrint($id) { if (Yii::$app->user->isGuest) { return $this->redirect(array(GeneralVariable::loginPagePath)); } $model = $this->findModel($id); $ref = RefSukan::findOne(['id' => $model->sukan]); $model->sukan = $ref['desc']; $ref = RefBandar::findOne(['id' => $model->alamat_bandar]); $model->alamat_bandar = $ref['desc']; $ref = RefNegeri::findOne(['id' => $model->alamat_negeri]); $model->alamat_negeri = $ref['desc']; $ref = RefBank::findOne(['id' => $model->nama_bank]); $model->nama_bank = $ref['desc']; $ref = RefPeringkatBantuanPenganjuranKejohanan::findOne(['id' => $model->peringkat]); $model->peringkat = $ref['desc']; $ref = ProfilBadanSukan::findOne(['profil_badan_sukan' => $model->badan_sukan]); $model->badan_sukan = $ref['nama_badan_sukan']; $model->status_permohonan_id = $model->status_permohonan; $ref = RefStatusBantuanPenganjuranKejohanan::findOne(['id' => $model->status_permohonan]); $model->status_permohonan = $ref['desc']; $BantuanPenganjuranKejohananKewangan = BantuanPenganjuranKejohananKewangan::find()->joinWith(['refSumberKewanganBantuanPenganjuranKejohanan'])->where(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id])->all(); $BantuanPenganjuranKejohananBayaran = BantuanPenganjuranKejohananBayaran::find()->joinWith(['refJenisBayaranBantuanPenganjuranKejohanan'])->where(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id])->all(); $BantuanPenganjuranKejohananElemen = BantuanPenganjuranKejohananElemen::find()->joinWith(['refElemenBantuanPenganjuranKejohanan']) ->joinWith(['refSubElemenBantuanPenganjuranKejohanan'])->where(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id])->all(); $BantuanPenganjuranKejohananDianjurkan = BantuanPenganjuranKejohananDianjurkan::find()->where(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id])->all(); $BantuanPenganjuranKejohananOlehMsn = BantuanPenganjuranKejohananOlehMsn::find()->where(['bantuan_penganjuran_kejohanan_id' => $model->bantuan_penganjuran_kejohanan_id])->all(); $pdf = new \mPDF('utf-8', 'A4'); $pdf->title = 'Bantuan Penganjuran Kejohanan'; $stylesheet = file_get_contents('css/report.css'); $pdf->WriteHTML($stylesheet,1); $pdf->WriteHTML($this->renderpartial('print', [ 'model' => $model, 'title' => $pdf->title, 'BantuanPenganjuranKejohananKewangan' => $BantuanPenganjuranKejohananKewangan, 'BantuanPenganjuranKejohananBayaran' => $BantuanPenganjuranKejohananBayaran, 'BantuanPenganjuranKejohananElemen' => $BantuanPenganjuranKejohananElemen, 'BantuanPenganjuranKejohananDianjurkan' => $BantuanPenganjuranKejohananDianjurkan, 'BantuanPenganjuranKejohananOlehMsn' => $BantuanPenganjuranKejohananOlehMsn, ])); $pdf->Output(str_replace(' ', '_', $pdf->title).'_'.$model->bantuan_penganjuran_kejohanan_id.'.pdf', 'I'); } }
hung101/kbs
frontend/controllers/BantuanPenganjuranKejohananController.php
PHP
bsd-3-clause
36,159
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/nacl/nacl_listener.h" #include <errno.h> #include <stdlib.h> #include "base/command_line.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/rand_util.h" #include "chrome/common/nacl_messages.h" #include "chrome/nacl/nacl_ipc_adapter.h" #include "chrome/nacl/nacl_validation_db.h" #include "chrome/nacl/nacl_validation_query.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_switches.h" #include "ipc/ipc_sync_channel.h" #include "ipc/ipc_sync_message_filter.h" #include "native_client/src/trusted/service_runtime/sel_main_chrome.h" #if defined(OS_POSIX) #include "base/file_descriptor_posix.h" #endif #if defined(OS_LINUX) #include "content/public/common/child_process_sandbox_support_linux.h" #endif #if defined(OS_WIN) #include <fcntl.h> #include <io.h> #include "content/public/common/sandbox_init.h" #endif namespace { #if defined(OS_MACOSX) // On Mac OS X, shm_open() works in the sandbox but does not give us // an FD that we can map as PROT_EXEC. Rather than doing an IPC to // get an executable SHM region when CreateMemoryObject() is called, // we preallocate one on startup, since NaCl's sel_ldr only needs one // of them. This saves a round trip. base::subtle::Atomic32 g_shm_fd = -1; int CreateMemoryObject(size_t size, int executable) { if (executable && size > 0) { int result_fd = base::subtle::NoBarrier_AtomicExchange(&g_shm_fd, -1); if (result_fd != -1) { // ftruncate() is disallowed by the Mac OS X sandbox and // returns EPERM. Luckily, we can get the same effect with // lseek() + write(). if (lseek(result_fd, size - 1, SEEK_SET) == -1) { LOG(ERROR) << "lseek() failed: " << errno; return -1; } if (write(result_fd, "", 1) != 1) { LOG(ERROR) << "write() failed: " << errno; return -1; } return result_fd; } } // Fall back to NaCl's default implementation. return -1; } #elif defined(OS_LINUX) int CreateMemoryObject(size_t size, int executable) { return content::MakeSharedMemorySegmentViaIPC(size, executable); } #elif defined(OS_WIN) NaClListener* g_listener; // We wrap the function to convert the bool return value to an int. int BrokerDuplicateHandle(NaClHandle source_handle, uint32_t process_id, NaClHandle* target_handle, uint32_t desired_access, uint32_t options) { return content::BrokerDuplicateHandle(source_handle, process_id, target_handle, desired_access, options); } int AttachDebugExceptionHandler(const void* info, size_t info_size) { std::string info_string(reinterpret_cast<const char*>(info), info_size); bool result = false; if (!g_listener->Send(new NaClProcessMsg_AttachDebugExceptionHandler( info_string, &result))) return false; return result; } #endif } // namespace class BrowserValidationDBProxy : public NaClValidationDB { public: explicit BrowserValidationDBProxy(NaClListener* listener) : listener_(listener) { } virtual bool QueryKnownToValidate(const std::string& signature) OVERRIDE { // Initialize to false so that if the Send fails to write to the return // value we're safe. For example if the message is (for some reason) // dispatched as an async message the return parameter will not be written. bool result = false; if (!listener_->Send(new NaClProcessMsg_QueryKnownToValidate(signature, &result))) { LOG(ERROR) << "Failed to query NaCl validation cache."; result = false; } return result; } virtual void SetKnownToValidate(const std::string& signature) OVERRIDE { // Caching is optional: NaCl will still work correctly if the IPC fails. if (!listener_->Send(new NaClProcessMsg_SetKnownToValidate(signature))) { LOG(ERROR) << "Failed to update NaCl validation cache."; } } private: // The listener never dies, otherwise this might be a dangling reference. NaClListener* listener_; }; NaClListener::NaClListener() : shutdown_event_(true, false), io_thread_("NaCl_IOThread"), #if defined(OS_LINUX) prereserved_sandbox_size_(0), #endif main_loop_(NULL) { io_thread_.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); #if defined(OS_WIN) DCHECK(g_listener == NULL); g_listener = this; #endif } NaClListener::~NaClListener() { NOTREACHED(); shutdown_event_.Signal(); #if defined(OS_WIN) g_listener = NULL; #endif } bool NaClListener::Send(IPC::Message* msg) { DCHECK(main_loop_ != NULL); if (base::MessageLoop::current() == main_loop_) { // This thread owns the channel. return channel_->Send(msg); } else { // This thread does not own the channel. return filter_->Send(msg); } } void NaClListener::Listen() { std::string channel_name = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessChannelID); channel_.reset(new IPC::SyncChannel(this, io_thread_.message_loop_proxy(), &shutdown_event_)); filter_ = new IPC::SyncMessageFilter(&shutdown_event_); channel_->AddFilter(filter_.get()); channel_->Init(channel_name, IPC::Channel::MODE_CLIENT, true); main_loop_ = base::MessageLoop::current(); main_loop_->Run(); } bool NaClListener::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NaClListener, msg) IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStart) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void NaClListener::OnStart(const nacl::NaClStartParams& params) { struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate(); if (args == NULL) { LOG(ERROR) << "NaClChromeMainArgsCreate() failed"; return; } if (params.enable_ipc_proxy) { // Create the initial PPAPI IPC channel between the NaCl IRT and the // browser process. The IRT uses this channel to communicate with the // browser and to create additional IPC channels to renderer processes. IPC::ChannelHandle handle = IPC::Channel::GenerateVerifiedChannelID("nacl"); scoped_refptr<NaClIPCAdapter> ipc_adapter( new NaClIPCAdapter(handle, io_thread_.message_loop_proxy())); ipc_adapter->ConnectChannel(); // Pass a NaClDesc to the untrusted side. This will hold a ref to the // NaClIPCAdapter. args->initial_ipc_desc = ipc_adapter->MakeNaClDesc(); #if defined(OS_POSIX) handle.socket = base::FileDescriptor( ipc_adapter->TakeClientFileDescriptor(), true); #endif if (!Send(new NaClProcessHostMsg_PpapiChannelCreated(handle))) LOG(ERROR) << "Failed to send IPC channel handle to NaClProcessHost."; } std::vector<nacl::FileDescriptor> handles = params.handles; #if defined(OS_LINUX) || defined(OS_MACOSX) args->urandom_fd = dup(base::GetUrandomFD()); if (args->urandom_fd < 0) { LOG(ERROR) << "Failed to dup() the urandom FD"; return; } args->create_memory_object_func = CreateMemoryObject; # if defined(OS_MACOSX) CHECK(handles.size() >= 1); g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]); handles.pop_back(); # endif #endif if (params.uses_irt) { CHECK(handles.size() >= 1); NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]); handles.pop_back(); #if defined(OS_WIN) args->irt_fd = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle), _O_RDONLY | _O_BINARY); if (args->irt_fd < 0) { LOG(ERROR) << "_open_osfhandle() failed"; return; } #else args->irt_fd = irt_handle; #endif } else { // Otherwise, the IRT handle is not even sent. args->irt_fd = -1; } if (params.validation_cache_enabled) { // SHA256 block size. CHECK_EQ(params.validation_cache_key.length(), (size_t) 64); // The cache structure is not freed and exists until the NaCl process exits. args->validation_cache = CreateValidationCache( new BrowserValidationDBProxy(this), params.validation_cache_key, params.version); } CHECK(handles.size() == 1); args->imc_bootstrap_handle = nacl::ToNativeHandle(handles[0]); args->enable_exception_handling = params.enable_exception_handling; args->enable_debug_stub = params.enable_debug_stub; args->enable_dyncode_syscalls = params.enable_dyncode_syscalls; #if defined(OS_LINUX) || defined(OS_MACOSX) args->debug_stub_server_bound_socket_fd = nacl::ToNativeHandle( params.debug_stub_server_bound_socket); #endif #if defined(OS_WIN) args->broker_duplicate_handle_func = BrokerDuplicateHandle; args->attach_debug_exception_handler_func = AttachDebugExceptionHandler; #endif #if defined(OS_LINUX) args->prereserved_sandbox_size = prereserved_sandbox_size_; #endif NaClChromeMainStart(args); NOTREACHED(); }
loopCM/chromium
chrome/nacl/nacl_listener.cc
C++
bsd-3-clause
9,324
/* * Copyright (c) 2012, František Haas, Martin Lacina, Jaroslav Kotrč, Jiří Daniel * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package cz.cuni.mff.spl.utils.ssh; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import cz.cuni.mff.spl.utils.logging.SplLog; import cz.cuni.mff.spl.utils.logging.SplLogger; import cz.cuni.mff.spl.utils.ssh.exception.SshException; /** * <p> * This class provides auto reconnecting session for JSch library. * * @author Frantisek Haas * */ public class SshReconnectingSession implements ISshSession { private static final SplLog logger = SplLogger.getLogger(SshReconnectingSession.class); private static final int KEEP_ALIVE_INTERVAL_MS = 10000; private final SshDetails details; /** If session is initialized connecting and auto reconnecting is enabled. */ private boolean initialized = false; private JSch jsch = null; private Session session = null; private ChannelSftp sftpChannel = null; /** To log reconnecting only once per lost connection. */ private boolean logReconnecting = true; /** * <p> * Creates the session. Does not open any connections. To start the session * working call {@link #connect}. Even if it fails further calls to * {@link #connect()}, {@link #getSession()} and {@link #getSftpChannel()} * will try to open the connection. The {@link #close()} closes the * connection. * * @param details */ public SshReconnectingSession(SshDetails details) { this.details = details; } /** * @return * Returns connection details. */ public SshDetails getDetails() { return details; } /** * <p> * Initializes the session and tries to open the connection. * * @throws SshException * <p> * If connection fails. But later calls to {@link #connect()}, * {@link #getSession()} and {@link #getSftpChannel()} will try * to open the connection again. */ @Override public void connect() throws SshException { if (initialized && logReconnecting) { logger.info("Connection lost ... reconnecting."); } if (!initialized) { jsch = SshUtils.createJsch(details); initialized = true; } try { if (!isConnected()) { innerClose(); try { session = SshUtils.createSession(jsch, details); session.setServerAliveInterval(KEEP_ALIVE_INTERVAL_MS); sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); logger.trace("Successfully connected session."); } catch (SshException e) { innerClose(); logger.trace("Failed to connect session."); throw e; } catch (JSchException e) { innerClose(); logger.trace("Failed to connect session."); throw new SshException(e); } } } finally { logReconnecting = isConnected(); } } /** * <p> * Initializes the session and tries to open the connection. * * @return * <p> * True if connected. False If connection fails. But later calls to * {@link #connect()}, {@link #getSession()} and * {@link #getSftpChannel()} will try to open the connection again. * */ @Override public boolean silentConnect() { try { connect(); return true; } catch (SshException e) { return false; } } /** * Checks if connection is established. Tries to send keep alive message. * * @return */ @Override public boolean isConnected() { if (session == null || !session.isConnected() || sftpChannel == null || !sftpChannel.isConnected()) { return false; } else { return true; } } /** * <p> * If there's a valid connected session it's returned. If there's not the * function tries to connect one and return it. * * @return * Session if it's valid and connected. Otherwise {@code null}. */ @Override public Session getSession() { if (!initialized) { return null; } if (!isConnected()) { silentConnect(); } return session; } /** * <p> * If there's a valid connected session it's returned. If there's not the * function tries to connect one and return it. * * @return * Session if it's valid and connected. Otherwise {@code null}. */ @Override public ChannelSftp getSftpChannel() { if (!initialized) { return null; } if (!isConnected()) { silentConnect(); } return sftpChannel; } public void innerClose() { if (sftpChannel != null) { sftpChannel.disconnect(); sftpChannel = null; } if (session != null) { session.disconnect(); session = null; } } @Override public void close() { initialized = false; innerClose(); } }
lottie-c/spl_tests_new
src/java/cz/cuni/mff/spl/utils/ssh/SshReconnectingSession.java
Java
bsd-3-clause
7,212
<?php /* * Autor : Juan Carlos Ludeña Montesinos * Año : Marzo 2016 * Descripción : * */ namespace Admin\Controller; use Common\Controller\SecurityAdminController; use Zend\View\Model\ViewModel; use \Common\Helpers\String; class PermisoController extends SecurityAdminController { public function indexAction() { $params = array( 'rol_id' => String::xssClean($this->params()->fromQuery('rol_id')), 'recurso_id' => String::xssClean($this->params()->fromQuery('recurso_id')), ); $form = $this->crearBuscarForm(); $form->setData($params); if (empty($params['rol_id'])) { $roles = $form->get('rol_id')->getValueOptions(); foreach ($roles as $key => $value) { $params['rol_id'] = $key; break; } } $criteria = array( 'where' => $params, 'limit' => LIMIT_BUSCAR, ); $gridList = $this->_getPermisoService()->getRepository()->search($criteria); $countList = $this->_getPermisoService()->getRepository()->countTotal($criteria); $view = new ViewModel(); $view->setVariable('gridList', $gridList); $view->setVariable('countList', $countList); $view->setVariable('form', $form); return $view; } public function crearAction() { $request = $this->getRequest(); $form = $this->crearCrudForm(AC_CREAR); if ($request->isPost()) { $this->_prepareSave(AC_CREAR, $form); } $view = new ViewModel(); $view->setVariable('form', $form); return $view; } public function editarAction() { $id = $this->params('id', null); $request = $this->getRequest(); $form = $this->crearCrudForm(AC_EDITAR, $id); $criteria = array( 'where' => array( 'id' => $id ), ); $row = $this->_getPermisoService()->getRepository()->findOne($criteria); if (empty($row)) { throw new \Exception(NO_DATA); } if (!empty($row['acl'])) { $row['listar'] = (strpos($row['acl'], 'R') === false) ? '0' : '1' ; $row['crear'] = (strpos($row['acl'], 'C') === false) ? '0' : '1' ; $row['modificar'] = (strpos($row['acl'], 'U') === false) ? '0' : '1' ; $row['eliminar'] = (strpos($row['acl'], 'D') === false) ? '0' : '1' ; } $form->setData($row); if ($request->isPost()) { $this->_prepareSave(AC_EDITAR, $form, $id); } $view = new ViewModel(); $view->setVariable('form', $form); return $view; } public function eliminarAction() { $request = $this->getRequest(); $results = array('success' => false, 'msg' => ER_ELIMINAR); if ($request->isPost()) { $id = $this->params('id', null); if (!empty($id)) { $this->_getPermisoService()->getRepository() ->delete(array('id' => $id)); $results = array('success' => true, 'msg' => OK_ELIMINAR); } $key = ($results['success']) ? 'success' : 'error'; $this->flashMessenger()->addMessage(array($key => $results['msg'])); } $response = $this->getResponse(); $response->getHeaders()->addHeaderLine( 'Content-Type', 'application/json' ); $response->setContent(json_encode($results)); return $response; } protected function _prepareSave($action, $form, $id = null) { $request = $this->getRequest(); $data = $request->getPost()->toArray(); $form->setInputFilter(new \Admin\Filter\PermisoFilter()); $form->setData($data); if ($form->isValid()) { $data = $form->getData(); try { $acl = ''; if ($data['listar'] == '1') { $acl = $acl . 'R'; } if ($data['crear'] == '1') { $acl = $acl . 'C'; } if ($data['modificar'] == '1') { $acl = $acl . 'U'; } if ($data['eliminar'] == '1') { $acl = $acl . 'D'; } $paramsIn = array( 'acl' => $acl, 'rol_id' => $data['rol_id'], 'recurso_id' => $data['recurso_id'], ); $repository = $this->_getPermisoService()->getRepository(); if (!empty($id)) { $permiso = $repository->findOne(array('where' => array( 'rol_id' => $data['rol_id'], 'recurso_id' => $data['recurso_id'], ))); if (!empty($permiso) && $permiso['id'] == $id) { $repository->save($paramsIn, $id); } else { $this->flashMessenger()->addMessage(array( 'error' => 'La combinación de recurso y rol ya fue asignado.', )); } } else { $permiso = $repository->findOne(array('where' => array( 'rol_id' => $data['rol_id'], 'recurso_id' => $data['recurso_id'], ))); if (!empty($permiso)) { $this->flashMessenger()->addMessage(array( 'error' => 'La combinación de recurso y rol ya fue asignado.', )); } else { $repository->save($paramsIn); $this->flashMessenger()->addMessage(array( 'success' => ($action == AC_CREAR) ? OK_CREAR : OK_EDITAR, )); } } } catch (\Exception $e) { $this->flashMessenger()->addMessage(array( 'error' => ($action == AC_CREAR) ? ER_CREAR : ER_EDITAR, )); } $this->redirect()->toRoute('admin/crud', array( 'controller' => 'permiso', 'action' => 'index' )); } } public function crearCrudForm($action, $id = null) { $options = array( 'controller' => 'permiso', 'action' => $action, ); if (!empty($id)) { $options['id'] = $id; } $form = $this->_getPermisoForm(); $form->setAttribute('action', $this->url()->fromRoute('admin/crud', $options)); return $form; } public function crearBuscarForm() { $form = $this->_getPermisoForm(); $form->setAttribute('action', $this->url()->fromRoute('admin/crud', array( 'controller' => 'permiso', 'action' => 'index' ))); $form->setAttribute('method', 'get'); return $form; } protected function _getPermisoForm() { return $this->getServiceLocator()->get('Admin\Form\PermisoForm'); } protected function _getPermisoService() { return $this->getServiceLocator()->get('Admin\Model\Service\PermisoService'); } }
NextTrick/cp
module/Admin/src/Admin/Controller/PermisoController.php
PHP
bsd-3-clause
7,524
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/drive/drive_api_service.h" #include <string> #include <vector> #include "base/bind.h" #include "base/message_loop_proxy.h" #include "chrome/browser/google_apis/drive_api_operations.h" #include "chrome/browser/google_apis/operation_runner.h" #include "chrome/browser/google_apis/time_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/net/url_util.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace drive { namespace { // OAuth2 scopes for Drive API. const char kDriveScope[] = "https://www.googleapis.com/auth/drive"; const char kDriveAppsReadonlyScope[] = "https://www.googleapis.com/auth/drive.apps.readonly"; } // namespace DriveAPIService::DriveAPIService(const std::string& custom_user_agent) : profile_(NULL), runner_(NULL), custom_user_agent_(custom_user_agent) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } DriveAPIService::~DriveAPIService() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (runner_.get()) { runner_->operation_registry()->RemoveObserver(this); runner_->auth_service()->RemoveObserver(this); } } void DriveAPIService::Initialize(Profile* profile) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); profile_ = profile; std::vector<std::string> scopes; scopes.push_back(kDriveScope); scopes.push_back(kDriveAppsReadonlyScope); runner_.reset( new google_apis::OperationRunner(profile, scopes, custom_user_agent_)); runner_->Initialize(); runner_->auth_service()->AddObserver(this); runner_->operation_registry()->AddObserver(this); } void DriveAPIService::AddObserver(google_apis::DriveServiceObserver* observer) { observers_.AddObserver(observer); } void DriveAPIService::RemoveObserver( google_apis::DriveServiceObserver* observer) { observers_.RemoveObserver(observer); } bool DriveAPIService::CanStartOperation() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return HasRefreshToken(); } void DriveAPIService::CancelAll() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); runner_->CancelAll(); } bool DriveAPIService::CancelForFilePath(const FilePath& file_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return operation_registry()->CancelForFilePath(file_path); } google_apis::OperationProgressStatusList DriveAPIService::GetProgressStatusList() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return operation_registry()->GetProgressStatusList(); } void DriveAPIService::GetDocuments( const GURL& url, int64 start_changestamp, const std::string& search_query, bool shared_with_me, const std::string& directory_resource_id, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (search_query.empty()) GetChangelist(url, start_changestamp, callback); else GetFilelist(url, search_query, callback); return; // TODO(kochi): Implement !directory_resource_id.empty() case. NOTREACHED(); } void DriveAPIService::GetFilelist( const GURL& url, const std::string& search_query, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); runner_->StartOperationWithRetry( new google_apis::GetFilelistOperation(operation_registry(), url, search_query, callback)); } void DriveAPIService::GetChangelist( const GURL& url, int64 start_changestamp, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); runner_->StartOperationWithRetry( new google_apis::GetChangelistOperation(operation_registry(), url, start_changestamp, callback)); } void DriveAPIService::GetDocumentEntry( const std::string& resource_id, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); runner_->StartOperationWithRetry(new google_apis::GetFileOperation( operation_registry(), resource_id, callback)); } void DriveAPIService::GetAccountMetadata( const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); runner_->StartOperationWithRetry( new google_apis::GetAboutOperation(operation_registry(), callback)); } void DriveAPIService::GetApplicationInfo( const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); runner_->StartOperationWithRetry( new google_apis::GetApplistOperation(operation_registry(), callback)); } void DriveAPIService::DownloadDocument( const FilePath& virtual_path, const FilePath& local_cache_path, const GURL& document_url, google_apis::DocumentExportFormat format, const google_apis::DownloadActionCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::DownloadFile( const FilePath& virtual_path, const FilePath& local_cache_path, const GURL& document_url, const google_apis::DownloadActionCallback& download_action_callback, const google_apis::GetContentCallback& get_content_callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::DeleteDocument( const GURL& document_url, const google_apis::EntryActionCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::AddNewDirectory( const GURL& parent_content_url, const FilePath::StringType& directory_name, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::CopyDocument( const std::string& resource_id, const FilePath::StringType& new_name, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::RenameResource( const GURL& resource_url, const FilePath::StringType& new_name, const google_apis::EntryActionCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::AddResourceToDirectory( const GURL& parent_content_url, const GURL& resource_url, const google_apis::EntryActionCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::RemoveResourceFromDirectory( const GURL& parent_content_url, const GURL& resource_url, const std::string& resource_id, const google_apis::EntryActionCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::InitiateUpload( const google_apis::InitiateUploadParams& params, const google_apis::InitiateUploadCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::ResumeUpload( const google_apis::ResumeUploadParams& params, const google_apis::ResumeUploadCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } void DriveAPIService::AuthorizeApp( const GURL& resource_url, const std::string& app_ids, const google_apis::GetDataCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // TODO(kochi): Implement this. NOTREACHED(); } bool DriveAPIService::HasAccessToken() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return runner_->auth_service()->HasAccessToken(); } bool DriveAPIService::HasRefreshToken() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return runner_->auth_service()->HasRefreshToken(); } google_apis::OperationRegistry* DriveAPIService::operation_registry() const { return runner_->operation_registry(); } void DriveAPIService::OnOAuth2RefreshTokenChanged() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (CanStartOperation()) { FOR_EACH_OBSERVER( google_apis::DriveServiceObserver, observers_, OnReadyToPerformOperations()); } } void DriveAPIService::OnProgressUpdate( const google_apis::OperationProgressStatusList& list) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER( google_apis::DriveServiceObserver, observers_, OnProgressUpdate(list)); } void DriveAPIService::OnAuthenticationFailed( google_apis::GDataErrorCode error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FOR_EACH_OBSERVER( google_apis::DriveServiceObserver, observers_, OnAuthenticationFailed(error)); } } // namespace drive
leighpauls/k2cro4
chrome/browser/chromeos/drive/drive_api_service.cc
C++
bsd-3-clause
9,535
#ifndef NEK_TYPE_TRAITS_IS_INTEGRAL_HPP #define NEK_TYPE_TRAITS_IS_INTEGRAL_HPP #include <nek/type_traits/integral_constant.hpp> #include <nek/type_traits/remove_cv.hpp> namespace nek { namespace is_integral_detail { template <class T> struct is_integral : public false_type { }; template <> struct is_integral<bool> : public true_type { }; template <> struct is_integral<wchar_t> : public true_type { }; template <> struct is_integral<char> : public true_type { }; template <> struct is_integral<signed char> : public true_type { }; template <> struct is_integral<unsigned char> : public true_type { }; template <> struct is_integral<signed short> : public true_type { }; template <> struct is_integral<unsigned short> : public true_type { }; template <> struct is_integral<signed int> : public true_type { }; template <> struct is_integral<unsigned int> : public true_type { }; template <> struct is_integral<signed long> : public true_type { }; template <> struct is_integral<unsigned long> : public true_type { }; template <> struct is_integral<long long> : public true_type { }; template <> struct is_integral<unsigned long long> : public true_type { }; } template <class T> struct is_integral : public is_integral_detail::is_integral<remove_cv_t<T>> { }; } #endif
nekko1119/nek
nek/type_traits/is_integral.hpp
C++
bsd-3-clause
1,942
<?php Yii::setAlias('plugin', '@common/../Public/plugin'); Yii::setAlias('pluginPath','../../../Public/plugin');
hehekeke/msup
backend/config/bootstrap.php
PHP
bsd-3-clause
114
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/socket/socket_bio_adapter.h" #include <string.h> #include <algorithm> #include "base/bind.h" #include "base/feature_list.h" #include "base/location.h" #include "base/logging.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/socket/socket.h" #include "net/socket/stream_socket.h" #include "net/ssl/openssl_ssl_util.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "starboard/memory.h" #include "starboard/types.h" #include "third_party/boringssl/src/include/openssl/bio.h" namespace { net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation("socket_bio_adapter", R"( semantics { sender: "Socket BIO Adapter" description: "SocketBIOAdapter is used only internal to //net code as an internal " "detail to implement a TLS connection for a Socket class, and is not " "being called directly outside of this abstraction." trigger: "Establishing a TLS connection to a remote endpoint. There are many " "different ways in which a TLS connection may be triggered, such as " "loading an HTTPS URL." data: "All data sent or received over a TLS connection. This traffic may " "either be the handshake or application data. During the handshake, " "the target host name, user's IP, data related to previous " "handshake, client certificates, and channel ID, may be sent. When " "the connection is used to load an HTTPS URL, the application data " "includes cookies, request headers, and the response body." destination: OTHER destination_other: "Any destination the implementing socket is connected to." } policy { cookies_allowed: NO setting: "This feature cannot be disabled." policy_exception_justification: "Essential for navigation." })"); } // namespace namespace net { SocketBIOAdapter::SocketBIOAdapter(StreamSocket* socket, int read_buffer_capacity, int write_buffer_capacity, Delegate* delegate) : socket_(socket), read_buffer_capacity_(read_buffer_capacity), read_offset_(0), read_result_(0), write_buffer_capacity_(write_buffer_capacity), write_buffer_used_(0), write_error_(OK), delegate_(delegate), weak_factory_(this) { bio_.reset(BIO_new(&kBIOMethod)); bio_->ptr = this; bio_->init = 1; read_callback_ = base::BindRepeating(&SocketBIOAdapter::OnSocketReadComplete, weak_factory_.GetWeakPtr()); write_callback_ = base::BindRepeating( &SocketBIOAdapter::OnSocketWriteComplete, weak_factory_.GetWeakPtr()); } SocketBIOAdapter::~SocketBIOAdapter() { // BIOs are reference-counted and may outlive the adapter. Clear the pointer // so future operations fail. bio_->ptr = nullptr; } bool SocketBIOAdapter::HasPendingReadData() { return read_result_ > 0; } size_t SocketBIOAdapter::GetAllocationSize() const { size_t buffer_size = 0; if (read_buffer_) buffer_size += read_buffer_capacity_; if (write_buffer_) buffer_size += write_buffer_capacity_; return buffer_size; } int SocketBIOAdapter::BIORead(char* out, int len) { if (len <= 0) return len; // If there is no result available synchronously, report any Write() errors // that were observed. Otherwise the application may have encountered a socket // error while writing that would otherwise not be reported until the // application attempted to write again - which it may never do. See // https://crbug.com/249848. if (write_error_ != OK && write_error_ != ERR_IO_PENDING && (read_result_ == 0 || read_result_ == ERR_IO_PENDING)) { OpenSSLPutNetError(FROM_HERE, write_error_); return -1; } if (read_result_ == 0) { // Instantiate the read buffer and read from the socket. Although only |len| // bytes were requested, intentionally read to the full buffer size. The SSL // layer reads the record header and body in separate reads to avoid // overreading, but issuing one is more efficient. SSL sockets are not // reused after shutdown for non-SSL traffic, so overreading is fine. DCHECK(!read_buffer_); DCHECK_EQ(0, read_offset_); read_buffer_ = base::MakeRefCounted<IOBuffer>(read_buffer_capacity_); int result = ERR_READ_IF_READY_NOT_IMPLEMENTED; if (base::FeatureList::IsEnabled(Socket::kReadIfReadyExperiment)) { result = socket_->ReadIfReady( read_buffer_.get(), read_buffer_capacity_, base::Bind(&SocketBIOAdapter::OnSocketReadIfReadyComplete, weak_factory_.GetWeakPtr())); if (result == ERR_IO_PENDING) read_buffer_ = nullptr; } if (result == ERR_READ_IF_READY_NOT_IMPLEMENTED) { result = socket_->Read(read_buffer_.get(), read_buffer_capacity_, read_callback_); } if (result == ERR_IO_PENDING) { read_result_ = ERR_IO_PENDING; } else { HandleSocketReadResult(result); } } // There is a pending Read(). Inform the caller to retry when it completes. if (read_result_ == ERR_IO_PENDING) { BIO_set_retry_read(bio()); return -1; } // If the last Read() failed, report the error. if (read_result_ < 0) { OpenSSLPutNetError(FROM_HERE, read_result_); return -1; } // Report the result of the last Read() if non-empty. CHECK_LT(read_offset_, read_result_); len = std::min(len, read_result_ - read_offset_); memcpy(out, read_buffer_->data() + read_offset_, len); read_offset_ += len; // Release the buffer when empty. if (read_offset_ == read_result_) { read_buffer_ = nullptr; read_offset_ = 0; read_result_ = 0; } return len; } void SocketBIOAdapter::HandleSocketReadResult(int result) { DCHECK_NE(ERR_IO_PENDING, result); // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here, so that higher // levels don't report success. if (result == 0) result = ERR_CONNECTION_CLOSED; read_result_ = result; // The read buffer is no longer needed. if (read_result_ <= 0) read_buffer_ = nullptr; } void SocketBIOAdapter::OnSocketReadComplete(int result) { DCHECK_EQ(ERR_IO_PENDING, read_result_); HandleSocketReadResult(result); delegate_->OnReadReady(); } void SocketBIOAdapter::OnSocketReadIfReadyComplete(int result) { DCHECK_EQ(ERR_IO_PENDING, read_result_); DCHECK_GE(OK, result); // Do not use HandleSocketReadResult() because result == OK doesn't mean EOF. read_result_ = result; delegate_->OnReadReady(); } int SocketBIOAdapter::BIOWrite(const char* in, int len) { if (len <= 0) return len; // If the write buffer is not empty, there must be a pending Write() to flush // it. DCHECK(write_buffer_used_ == 0 || write_error_ == ERR_IO_PENDING); // If a previous Write() failed, report the error. if (write_error_ != OK && write_error_ != ERR_IO_PENDING) { OpenSSLPutNetError(FROM_HERE, write_error_); return -1; } // Instantiate the write buffer if needed. if (!write_buffer_) { DCHECK_EQ(0, write_buffer_used_); write_buffer_ = base::MakeRefCounted<GrowableIOBuffer>(); write_buffer_->SetCapacity(write_buffer_capacity_); } // If the ring buffer is full, inform the caller to try again later. if (write_buffer_used_ == write_buffer_->capacity()) { BIO_set_retry_write(bio()); return -1; } int bytes_copied = 0; // If there is space after the offset, fill it. if (write_buffer_used_ < write_buffer_->RemainingCapacity()) { int chunk = std::min(write_buffer_->RemainingCapacity() - write_buffer_used_, len); memcpy(write_buffer_->data() + write_buffer_used_, in, chunk); in += chunk; len -= chunk; bytes_copied += chunk; write_buffer_used_ += chunk; } // If there is still space for remaining data, try to wrap around. if (len > 0 && write_buffer_used_ < write_buffer_->capacity()) { // If there were any room after the offset, the previous branch would have // filled it. CHECK_LE(write_buffer_->RemainingCapacity(), write_buffer_used_); int write_offset = write_buffer_used_ - write_buffer_->RemainingCapacity(); int chunk = std::min(len, write_buffer_->capacity() - write_buffer_used_); memcpy(write_buffer_->StartOfBuffer() + write_offset, in, chunk); in += chunk; len -= chunk; bytes_copied += chunk; write_buffer_used_ += chunk; } // Either the buffer is now full or there is no more input. DCHECK(len == 0 || write_buffer_used_ == write_buffer_->capacity()); // Schedule a socket Write() if necessary. (The ring buffer may previously // have been empty.) SocketWrite(); // If a read-interrupting write error was synchronously discovered, // asynchronously notify OnReadReady. See https://crbug.com/249848. Avoid // reentrancy by deferring it to a later event loop iteration. if (write_error_ != OK && write_error_ != ERR_IO_PENDING && read_result_ == ERR_IO_PENDING) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&SocketBIOAdapter::CallOnReadReady, weak_factory_.GetWeakPtr())); } return bytes_copied; } void SocketBIOAdapter::SocketWrite() { while (write_error_ == OK && write_buffer_used_ > 0) { int write_size = std::min(write_buffer_used_, write_buffer_->RemainingCapacity()); int result = socket_->Write(write_buffer_.get(), write_size, write_callback_, kTrafficAnnotation); if (result == ERR_IO_PENDING) { write_error_ = ERR_IO_PENDING; return; } HandleSocketWriteResult(result); } } void SocketBIOAdapter::HandleSocketWriteResult(int result) { DCHECK_NE(ERR_IO_PENDING, result); if (result < 0) { write_error_ = result; // The write buffer is no longer needed. write_buffer_ = nullptr; write_buffer_used_ = 0; return; } // Advance the ring buffer. write_buffer_->set_offset(write_buffer_->offset() + result); write_buffer_used_ -= result; if (write_buffer_->RemainingCapacity() == 0) write_buffer_->set_offset(0); write_error_ = OK; // Release the write buffer if empty. if (write_buffer_used_ == 0) write_buffer_ = nullptr; } void SocketBIOAdapter::OnSocketWriteComplete(int result) { DCHECK_EQ(ERR_IO_PENDING, write_error_); bool was_full = write_buffer_used_ == write_buffer_->capacity(); HandleSocketWriteResult(result); SocketWrite(); // If transitioning from being unable to accept data to being able to, signal // OnWriteReady. if (was_full) { base::WeakPtr<SocketBIOAdapter> guard(weak_factory_.GetWeakPtr()); delegate_->OnWriteReady(); // OnWriteReady may delete the adapter. if (!guard) return; } // Write errors are fed back into BIO_read once the read buffer is empty. If // BIO_read is currently blocked, signal early that a read result is ready. if (result < 0 && read_result_ == ERR_IO_PENDING) delegate_->OnReadReady(); } void SocketBIOAdapter::CallOnReadReady() { if (read_result_ == ERR_IO_PENDING) delegate_->OnReadReady(); } SocketBIOAdapter* SocketBIOAdapter::GetAdapter(BIO* bio) { DCHECK_EQ(&kBIOMethod, bio->method); SocketBIOAdapter* adapter = reinterpret_cast<SocketBIOAdapter*>(bio->ptr); if (adapter) DCHECK_EQ(bio, adapter->bio()); return adapter; } int SocketBIOAdapter::BIOWriteWrapper(BIO* bio, const char* in, int len) { BIO_clear_retry_flags(bio); SocketBIOAdapter* adapter = GetAdapter(bio); if (!adapter) { OpenSSLPutNetError(FROM_HERE, ERR_UNEXPECTED); return -1; } return adapter->BIOWrite(in, len); } int SocketBIOAdapter::BIOReadWrapper(BIO* bio, char* out, int len) { BIO_clear_retry_flags(bio); SocketBIOAdapter* adapter = GetAdapter(bio); if (!adapter) { OpenSSLPutNetError(FROM_HERE, ERR_UNEXPECTED); return -1; } return adapter->BIORead(out, len); } long SocketBIOAdapter::BIOCtrlWrapper(BIO* bio, int cmd, long larg, void* parg) { switch (cmd) { case BIO_CTRL_FLUSH: // The SSL stack requires BIOs handle BIO_flush. return 1; } NOTIMPLEMENTED(); return 0; } const BIO_METHOD SocketBIOAdapter::kBIOMethod = { 0, // type (unused) nullptr, // name (unused) SocketBIOAdapter::BIOWriteWrapper, SocketBIOAdapter::BIOReadWrapper, nullptr, // puts nullptr, // gets SocketBIOAdapter::BIOCtrlWrapper, nullptr, // create nullptr, // destroy nullptr, // callback_ctrl }; } // namespace net
youtube/cobalt
net/socket/socket_bio_adapter.cc
C++
bsd-3-clause
13,104
<?php class Pager { /** * Returns a concatenation of key => value parameters ready to use in a URL. */ public static function buildQueryString($dict) { $params = array(); $str = ''; foreach ($dict as $key => $val) { $str .= "$key=$val"; $params[] = urlencode($key) . '=' . urlencode($val); } return implode('&', $params); } /** * Returns an array with all the information needed to create a pager bar. * ------------------------------------------------------------------------------------- * | « | ... | c - a | ... | c - 2 | c - 1 | c | c + 1 | c + 2 | ... | c + a | ... | » | * ------------------------------------------------------------------------------------- * ^ * | * current page * * @param int $rows The total number of rows to show. * @param int $current The page we want to show, the 'c' in the figure. * @param string $url The base URL that each item will point to. * @param int $adjacent Number of items before and after the current page, the 'a' in the figure. * @param array $params Additional key => value parameters to append to the item's URL. * @return array $items The information for each item of the pager. */ public static function paginate($rows, $current, $url, $adjacent, $params) { $pages = intval(($rows + PROBLEMS_PER_PAGE - 1) / PROBLEMS_PER_PAGE); if ($current < 1 || $current > $pages) { $current = 1; } $query = ''; if (count($params) > 0) { $query = '&' . self::buildQueryString($params); } $items = array(); $prev = array('label' => '«', 'url' => '', 'class' => ''); if ($current > 1) { $prev['url'] = $url . '?page=' . ($current - 1) . $query; } else { $prev['url'] = ''; $prev['class'] = 'disabled'; } array_push($items, $prev); if ($current > $adjacent + 1) { $first = array( 'label' => '1', 'url' => $url . '?page=1' . $query, 'class' => '' ); $period = array( 'label' => '...', 'url' => '', 'class' => 'disabled' ); array_push($items, $first); array_push($items, $period); } for ($i = max(1, $current - $adjacent); $i <= min($pages, $current + $adjacent); $i++) { $item = array( 'label' => $i, 'url' => $url . '?page=' . $i . $query, 'class' => ($i == $current) ? 'active' : '' ); array_push($items, $item); } if ($current + $adjacent < $pages) { $period = array( 'label' => '...', 'url' => '', 'class' => 'disabled' ); $last = array( 'label' => $pages, 'url' => $url . '?page=' . $pages . $query, 'class' => '' ); array_push($items, $period); array_push($items, $last); } $next = array('label' => '»', 'url' => '', 'class' => ''); if ($current < $pages) { $next['url'] = $url . '?page=' . ($current + 1) . $query; } else { $next['url'] = ''; $next['class'] = 'disabled'; } array_push($items, $next); return $items; } } ?>
rendon/omegaup
frontend/server/libs/Pager.php
PHP
bsd-3-clause
3,039
// ***************************************************************************** // // © Component Factory Pty Ltd 2012. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy, // Seaford, Vic 3198, Australia and are supplied subject to licence terms. // // Version 4.4.1.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Text; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections.Generic; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Navigator { /// <summary> /// Add conversion to a string for display in properties window at design time. /// </summary> public class ButtonSpecNavFixedConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert the object to the specified type. /// </summary> /// <param name="context">An ITypeDescriptorContext that provides a format context.</param> /// <param name="destinationType">A Type that represents the type you want to convert to.</param> /// <returns>true if this converter can perform the conversion; otherwise, false.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { // Can always convert to a string representation if (destinationType == typeof(string)) return true; // Let base class do standard processing return base.CanConvertTo(context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A CultureInfo. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The Object to convert.</param> /// <param name="destinationType">The Type to convert the value parameter to.</param> /// <returns>An Object that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { // Can always convert to a string representation if (destinationType == typeof(string)) { // Cast to correct type ButtonSpecNavFixed buttonSpec = (ButtonSpecNavFixed)value; // Ask the button spec for the correct string return buttonSpec.ToString(); } // Let base class attempt other conversions return base.ConvertTo(context, culture, value, destinationType); } } }
Cocotteseb/Krypton
Source/Krypton Components/ComponentFactory.Krypton.Navigator/ButtonSpecs/ButtonSpecNavFixedConverter.cs
C#
bsd-3-clause
3,309
/* -- MAGMA (version 2.1.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date August 2016 @author Raffaele Solca @author Stan Tomov @author Mark Gates @generated from src/zhetrd2_gpu.cpp, normal z -> d, Tue Aug 30 09:38:14 2016 */ #include "magma_internal.h" /***************************************************************************//** Purpose ------- DSYTRD2_GPU reduces a real symmetric matrix A to real symmetric tridiagonal form T by an orthogonal similarity transformation: Q**H * A * Q = T. This version passes a workspace that is used in an optimized GPU matrix-vector product. Arguments --------- @param[in] uplo magma_uplo_t - = MagmaUpper: Upper triangle of A is stored; - = MagmaLower: Lower triangle of A is stored. @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in,out] dA DOUBLE PRECISION array on the GPU, dimension (LDDA,N) On entry, the symmetric matrix A. If UPLO = MagmaUpper, the leading N-by-N upper triangular part of A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced. If UPLO = MagmaLower, the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = MagmaUpper, the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = MagmaLower, the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. @param[in] ldda INTEGER The leading dimension of the array A. LDDA >= max(1,N). @param[out] d DOUBLE PRECISION array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). @param[out] e DOUBLE PRECISION array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = MagmaUpper, E(i) = A(i+1,i) if UPLO = MagmaLower. @param[out] tau DOUBLE PRECISION array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). @param[out] A (workspace) DOUBLE PRECISION array, dimension (LDA,N) On exit the diagonal, the upper part (if uplo=MagmaUpper) or the lower part (if uplo=MagmaLower) are copies of DA @param[in] lda INTEGER The leading dimension of the array A. LDA >= max(1,N). @param[out] work (workspace) DOUBLE PRECISION array, dimension (MAX(1,LWORK)) On exit, if INFO = 0, WORK[0] returns the optimal LWORK. @param[in] lwork INTEGER The dimension of the array WORK. LWORK >= N*NB, where NB is the optimal blocksize given by magma_get_dsytrd_nb(). \n If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. @param[out] dwork (workspace) DOUBLE PRECISION array on the GPU, dim (MAX(1,LDWORK)) @param[in] ldwork INTEGER The dimension of the array DWORK. LDWORK >= ldda*ceil(n/64) + 2*ldda*nb, where nb = magma_get_dsytrd_nb(n), and 64 is for the blocksize of magmablas_dsymv. @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value Further Details --------------- If UPLO = MagmaUpper, the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = MagmaLower, the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = MagmaUpper: if UPLO = MagmaLower: ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). @ingroup magma_hetrd *******************************************************************************/ extern "C" magma_int_t magma_dsytrd2_gpu( magma_uplo_t uplo, magma_int_t n, magmaDouble_ptr dA, magma_int_t ldda, double *d, double *e, double *tau, double *A, magma_int_t lda, double *work, magma_int_t lwork, magmaDouble_ptr dwork, magma_int_t ldwork, magma_int_t *info) { #define A(i_, j_) ( A + (i_) + (j_)*lda ) #define dA(i_, j_) (dA + (i_) + (j_)*ldda) /* Constants */ const double c_zero = MAGMA_D_ZERO; const double c_neg_one = MAGMA_D_NEG_ONE; const double c_one = MAGMA_D_ONE; const double d_one = MAGMA_D_ONE; /* Local variables */ const char* uplo_ = lapack_uplo_const( uplo ); magma_int_t nb = magma_get_dsytrd_nb( n ); magma_int_t kk, nx; magma_int_t i, j, i_n; magma_int_t iinfo; magma_int_t ldw, lddw, lwkopt; magma_int_t lquery; *info = 0; bool upper = (uplo == MagmaUpper); lquery = (lwork == -1); if (! upper && uplo != MagmaLower) { *info = -1; } else if (n < 0) { *info = -2; } else if (ldda < max(1,n)) { *info = -4; } else if (lda < max(1,n)) { *info = -9; } else if (lwork < nb*n && ! lquery) { *info = -11; } else if (ldwork < ldda*magma_ceildiv(n,64) + 2*ldda*nb) { *info = -13; } /* Determine the block size. */ ldw = n; lddw = ldda; // hopefully ldda is rounded up to multiple of 32; ldwork is in terms of ldda, so lddw can't be > ldda. lwkopt = n * nb; if (*info == 0) { work[0] = magma_dmake_lwork( lwkopt ); } if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } else if (lquery) return *info; /* Quick return if possible */ if (n == 0) { work[0] = c_one; return *info; } // nx <= n is required // use LAPACK for n < 3000, otherwise switch at 512 if (n < 3000) nx = n; else nx = 512; double *work2; if (MAGMA_SUCCESS != magma_dmalloc_cpu( &work2, n )) { *info = MAGMA_ERR_HOST_ALLOC; return *info; } magma_queue_t queue = NULL; magma_device_t cdev; magma_getdevice( &cdev ); magma_queue_create( cdev, &queue ); // clear out dwork in case it has NANs (used as y in dsymv) // rest of dwork (used as work in magmablas_dsymv) doesn't need to be cleared magmablas_dlaset( MagmaFull, n, nb, c_zero, c_zero, dwork, lddw, queue ); if (upper) { /* Reduce the upper triangle of A. Columns 1:kk are handled by the unblocked method. */ kk = n - magma_roundup( n - nx, nb ); for (i = n - nb; i >= kk; i -= nb) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ /* Get the current panel */ magma_dgetmatrix( i+nb, nb, dA(0, i), ldda, A(0, i), lda, queue ); magma_dlatrd2( uplo, i+nb, nb, A(0, 0), lda, e, tau, work, ldw, work2, n, dA(0, 0), ldda, dwork, lddw, dwork + 2*lddw*nb, ldwork - 2*lddw*nb, queue ); /* Update the unreduced submatrix A(0:i-2,0:i-2), using an update of the form: A := A - V*W' - W*V' */ magma_dsetmatrix( i + nb, nb, work, ldw, dwork, lddw, queue ); magma_dsyr2k( uplo, MagmaNoTrans, i, nb, c_neg_one, dA(0, i), ldda, dwork, lddw, d_one, dA(0, 0), ldda, queue ); /* Copy superdiagonal elements back into A, and diagonal elements into D */ for (j = i; j < i+nb; ++j) { *A(j-1,j) = MAGMA_D_MAKE( e[j - 1], 0 ); d[j] = MAGMA_D_REAL( *A(j, j) ); } } magma_dgetmatrix( kk, kk, dA(0, 0), ldda, A(0, 0), lda, queue ); /* Use CPU code to reduce the last or only block */ lapackf77_dsytrd( uplo_, &kk, A(0, 0), &lda, d, e, tau, work, &lwork, &iinfo ); magma_dsetmatrix( kk, kk, A(0, 0), lda, dA(0, 0), ldda, queue ); } else { /* Reduce the lower triangle of A */ for (i = 0; i < n-nx; i += nb) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ /* Get the current panel */ magma_dgetmatrix( n-i, nb, dA(i, i), ldda, A(i, i), lda, queue ); magma_dlatrd2( uplo, n-i, nb, A(i, i), lda, &e[i], &tau[i], work, ldw, work2, n, dA(i, i), ldda, dwork, lddw, dwork + 2*lddw*nb, ldwork - 2*lddw*nb, queue ); /* Update the unreduced submatrix A(i+ib:n,i+ib:n), using an update of the form: A := A - V*W' - W*V' */ magma_dsetmatrix( n-i, nb, work, ldw, dwork, lddw, queue ); // cublas 6.5 crashes here if lddw % 32 != 0, e.g., N=250. magma_dsyr2k( MagmaLower, MagmaNoTrans, n-i-nb, nb, c_neg_one, dA(i+nb, i), ldda, &dwork[nb], lddw, d_one, dA(i+nb, i+nb), ldda, queue ); /* Copy subdiagonal elements back into A, and diagonal elements into D */ for (j = i; j < i+nb; ++j) { *A(j+1,j) = MAGMA_D_MAKE( e[j], 0 ); d[j] = MAGMA_D_REAL( *A(j, j) ); } } /* Use CPU code to reduce the last or only block */ magma_dgetmatrix( n-i, n-i, dA(i, i), ldda, A(i, i), lda, queue ); i_n = n-i; lapackf77_dsytrd( uplo_, &i_n, A(i, i), &lda, &d[i], &e[i], &tau[i], work, &lwork, &iinfo ); magma_dsetmatrix( n-i, n-i, A(i, i), lda, dA(i, i), ldda, queue ); } magma_free_cpu( work2 ); magma_queue_destroy( queue ); work[0] = magma_dmake_lwork( lwkopt ); return *info; } /* magma_dsytrd2_gpu */
maxhutch/magma
src/dsytrd2_gpu.cpp
C++
bsd-3-clause
12,031
(function ($) { "use strict"; /* DEFINE VARIABLES */ var fu = $("#media-upload"), // FOR JQUERY FILE UPLOAD fc = $("#file-container"), // FILE CONTAINER DISPLAY md = $("#media-detail"), // FOR DETAIL ITEM mf = $("#media-form"), // FOR FORM OF THE SELECTED ITEM ad = $('#address'), me = {"files": []}, // JSON OBJECT OF MEDIA ITEM se = {}; // JSON OBJECT OF SELECTED ITEM /* FILE UPLOAD CONFIGURATION */ fu.fileupload({ url: fu.data("url"), dropZone: $(".dropzone"), autoUpload: true, filesContainer: "#file-container", prependFiles: true }); fu.fileupload("option", "redirect", window.location.href.replace(/\/[^\/]*$/, "/cors/result.html?%s")); fu.addClass("fileupload-processing"); /* DRAG AND DROP */ $(document).bind("dragover", function (e) { var dropZone = $(".dropzone"), foundDropzone, timeout = window.dropZoneTimeout; if (!timeout) dropZone.addClass("in"); else clearTimeout(timeout); var found = false, node = e.target; do { if ($(node).hasClass("dropzone")) { found = true; foundDropzone = $(node); break; } node = node.parentNode; } while (node !== null); dropZone.removeClass("in hover"); if (found) { foundDropzone.addClass("hover"); } window.dropZoneTimeout = setTimeout(function () { window.dropZoneTimeout = null; dropZone.removeClass("in hover"); }, 100); }); /* ADD NEW UPLOADED FILE TO MEDIA JSON */ fu.bind("fileuploaddone", function (e, data) { $.each(data.result, function (index, file) { me.files[me.files.length] = file[0]; }); }); /* GET MEDIA DATA THAT APPEAR ON MEDIA WITHOUT FILTERING */ $.ajax({ url: ad.data('json-url'), dataType: "json", success: function (response) { me = response; $.ajax({ url: ad.data('pagination-url'), success: function (response) { $('#media-pagination').html(response); } }); fc.html(tmpl("template-download", response)); } }); /* SIDEBAR NAVIGATION */ $(document).on('click', '.media-popup-nav', function (e) { e.preventDefault(); var $this = $(this); $this.closest("ul").find("li").removeClass("active"); $this.parent("li").addClass("active"); if ($this.hasClass('all')) { $('.pagination-item').removeAttr('data-post_id'); } else { $('.pagination-item').attr('data-post_id', $(this).data("post_id")); } $.ajax({ url: ad.data('json-url'), data: {post_id: $this.data('post_id')}, dataType: "json", success: function (response) { me = response; $.ajax({ url: ad.data('pagination-url'), data: {post_id: $this.data('post_id')}, success: function (response) { var mp = $(".media-pagination"); mp.html(response); } }); fc.html(tmpl("template-download", response)); } }); }); /* PAGINATION CLICK */ $(document).on('click', '.pagination-item', function (e) { e.preventDefault(); var $this = $(this), p1 = $(this).data('page'), p2 = p1 + 1; $.ajax({ url: $this.attr('href'), data: {post_id: $this.data('post_id')}, dataType: "json", success: function (response) { me = response; $.ajax({ url: ad.data('pagination-url'), data: {post_id: $this.data('post_id'), page: p2, 'per-page': $this.data('per-page')}, success: function (response) { var mp = $(".media-pagination"); mp.html(response); } }); fc.html(tmpl("template-download", response)); } }); }); /* SHOW DETAIL ITEM */ fc.selectable({ filter: "li", tolerance: "fit", selected: function (event, ui) { $.each(me.files, function (i, file) { if ($(ui.selected).data('id') === file.id) { md.html(tmpl('template-media-detail', file)); mf.html(tmpl('template-media-form', file)); se[$(ui.selected).data("id")] = $("#media-form-inner").serializeObject(); } }); }, unselected: function (event, ui) { delete se[$(ui.unselected).data('id')]; } }); /* UPDATE SELECTED */ $(document).on("blur", "#media-form-inner [id^='media-']", function () { var parent = $(this).parents('#media-form-inner'), id = parent.data("id"); se[id] = parent.serializeObject(); }); /* UPDATE TITLE, EXCERPT, CONTENT OF MEDIA VIA AJAX CALL */ $(document).on("blur", "#media-media_title, #media-media_excerpt, #media-media_content", function () { var mfi = $(this).closest('#media-form-inner'); $.ajax({ url: mfi.data("update-url"), type: "POST", data: { id: mfi.data("id"), attribute: $(this).data('attr'), attribute_value: $(this).val(), _csrf: yii.getCsrfToken() }, success: function(response){ console.log(response); } }); }); /* UPDATE LINK TO */ $(document).on('change', '#media-media_link_to', function () { var link_value = $('#media-media_link_to_value'); if ($(this).val() === 'none') { link_value.val(''); link_value.attr('readonly', true); } else if ($(this).val() === 'custom') { link_value.val('http://'); link_value.attr('readonly', false); } else { link_value.val($(this).val()); } }); /* DELETE MEDIA ITEM ON MEDIA POP UP */ $(document).on("click", '#delete-media', function (e) { e.preventDefault(); e.stopImmediatePropagation(); var $this = $(this); if (confirm($this.data('confirm'))) { $.ajax({ url: $this.data('url'), type: "POST", success: function (data) { $('.media-item[data-id="' + $this.data('id') + '"]').closest('li').remove(); md.html(''); mf.html(''); delete se[$this.data('id')]; } }); } }); /* MEDIA FILTER SUBMIT */ $(document).on("submit", "#media-filter", function(e){ e.preventDefault(); e.stopImmediatePropagation(); var data = $(this).serialize(); $.ajax({ url: ad.data('json-url'), data: data, dataType: "json", success: function(response){ me = response; $.ajax({ url: ad.data('pagination-url'), data: data, success: function (response) { var mp = $(".media-pagination"); mp.html(response); } }); fc.html(tmpl("template-download", me)); } }); }); /* INSERT INTO TINY MCE */ $(document).on("click", "#insert-media", function (e) { e.preventDefault(); if(top.tinymce !== undefined){ $.ajax({ url: $(this).data('insert-url'), data: {media: se, _csrf: yii.getCsrfToken()}, type: 'POST', success: function(response){ top.tinymce.activeEditor.execCommand("mceInsertContent", false, response); top.tinymce.activeEditor.windowManager.close(); } }); }else{ $.ajax({ url: $(this).data('insert-url'), data: {media: se, _csrf: yii.getCsrfToken()}, type: 'POST', success: function(response){ alert(response); } }); } }); }(jQuery));
cloud-github/Yii2-cms
admin/js/media.popup.js
JavaScript
bsd-3-clause
9,054
require 'relyze/core' class Plugin < Relyze::Plugin::Analysis def initialize super( { :guid => '{273AFF27-6C32-4231-93AC-896311411246}', :name => 'Diff Copy Data', :description => %q{ After a differential analysis has been performed, copy block names and comments from all matched functions in the current analysis over to the diffed analysis. }, :authors => [ 'Relyze Software Limited' ], :license => 'Relyze Plugin License', :shortcuts => { :diff_copy_data => 'Alt+D' }, :require => { :files => [ 'set' ] }, :min_application_version => '1.2.0' } ) end def diff_copy_data copy = @relyze.list_dialog( self.name, 'Select what to copy:', [ 'Names and comments', 'Names only', 'Comments only' ] ) return if copy.nil? copy_names = false copy_comments = false if( copy == 'Names and comments' ) copy_names = true copy_comments = true elsif( copy == 'Names only' ) copy_names = true elsif( copy == 'Comments only' ) copy_comments = true end diff_copy( copy_names, copy_comments ) end def run diff_copy_data end def diff_copy( copy_names, copy_comments ) return if cm.nil? print_message( "Starting..." ) processed_names = ::Set.new processed_comments = ::Set.new cm.synchronize_read do dr = @relyze.tab_current_diff if( dr.nil? ) print_error( "No diff results." ) break end # swap the DiffModelResults to the other side if we need to, e.g. the # user right clicked on the B view and ran this plugin rather than # the A view. if( dr.model != cm ) dr = dr.matched end print_message( "Copying comments from '#{dr.name}' to '#{dr.matched.name}'..." ) dr.functions do | dr_func | next if dr_func.is_removed? or dr_func.is_added? dr_func.blocks do | dr_block | next if dr_block.is_removed? or dr_block.is_added? if( copy_names and dr_block.block.custom_name? ) if( not processed_names.include?( dr_block.rva ) ) dr.matched.model.synchronize_write do dr_block.matched.block.name = dr_block.name processed_names << dr_block.rva end end end if( copy_comments ) dr_block.instructions do | dr_inst | next if dr_inst.is_removed? or dr_inst.is_added? next if not dr.model.comment?( dr_inst.rva ) next if processed_comments.include?( dr_inst.rva ) dr.matched.model.synchronize_write do commentA = dr.model.get_comment( dr_inst.rva ) if( dr.matched.model.comment?( dr_inst.matched.rva ) ) commentB = dr.matched.model.get_comment( dr_inst.matched.rva ) break if commentA == commentB commentA << "\r\n\r\nPrevious Comment:#{ commentB }" end dr.matched.model.add_comment( dr_inst.matched.rva, commentA ) processed_comments << dr_inst.rva end end end end end end print_message( "Finished. Copied #{processed_names.length} names and #{processed_comments.length} comments." ) if( @relyze.gui? ) @relyze.update_gui end end end
relyze-ltd/plugins
release/diff_copy_data.rb
Ruby
bsd-3-clause
5,008
var NAVTREEINDEX17 = { "classIoss_1_1Tet4.html#ae945be949a6165bf9cebf2b770699ebd":[4,0,69,135,22], "classIoss_1_1Tet4.html#af2f9d7a80f796ded6a5ddfe374ed808e":[4,0,69,135,19], "classIoss_1_1Tet7.html":[4,0,69,136], "classIoss_1_1Tet7.html#a13df36e1096ef89227119e5d308ed628":[4,0,69,136,16], "classIoss_1_1Tet7.html#a16e6fa628f011addd36fc7322faa42c0":[4,0,69,136,19], "classIoss_1_1Tet7.html#a1e12d6c712675de8a1c8fc33b0b8c92d":[4,0,69,136,9], "classIoss_1_1Tet7.html#a29e1874549c01fd3c4be76ce3e4a9f67":[4,0,69,136,4], "classIoss_1_1Tet7.html#a37e0a7bce58a5da950d1ffb58ccbe8c4":[4,0,69,136,23], "classIoss_1_1Tet7.html#a497597e125f4502ff0a59a50b97ee0d9":[4,0,69,136,0], "classIoss_1_1Tet7.html#a508d1b597207d3872de42f3adf5b57fe":[4,0,69,136,2], "classIoss_1_1Tet7.html#a5b51028e307e1d244a5e6d17086f172e":[4,0,69,136,14], "classIoss_1_1Tet7.html#a5d0ff7276306ce77f9f6aa3ff1a04c68":[4,0,69,136,17], "classIoss_1_1Tet7.html#a6185f51cb7d94cb95220d98027ebaca0":[4,0,69,136,5], "classIoss_1_1Tet7.html#a64e46d81e51eda112c26105ec99c6cfe":[4,0,69,136,1], "classIoss_1_1Tet7.html#a8a12f05296d24f424b8466da9441bf0c":[4,0,69,136,22], "classIoss_1_1Tet7.html#a8bc616e8c2c9f2a493317979c67fa047":[4,0,69,136,7], "classIoss_1_1Tet7.html#a93b1ed3d1f0c22a79a794971845787f8":[4,0,69,136,12], "classIoss_1_1Tet7.html#aa99a6537359811e7ff5e8303c058faa2":[4,0,69,136,3], "classIoss_1_1Tet7.html#aad6a34b82fd2536894803cb9a6d3770a":[4,0,69,136,25], "classIoss_1_1Tet7.html#ab39e17b1fc522bfd33eccda8a0d770b8":[4,0,69,136,11], "classIoss_1_1Tet7.html#ab6ea8527499e31b590ff96a6f167adb0":[4,0,69,136,21], "classIoss_1_1Tet7.html#ac0cec8c082b6b0dd48b12849b3925792":[4,0,69,136,24], "classIoss_1_1Tet7.html#ac70c36c3acc282ddf505e21d263c5e70":[4,0,69,136,6], "classIoss_1_1Tet7.html#aca98ce328e3342d199d61e775601f966":[4,0,69,136,18], "classIoss_1_1Tet7.html#acdf346236e1c828a7f2465d3d90647c1":[4,0,69,136,20], "classIoss_1_1Tet7.html#ad2abb9b07e6f3cf751e664b9c8b8d597":[4,0,69,136,8], "classIoss_1_1Tet7.html#ad3c34a488797fe95f2ed9fa15d6421e9":[4,0,69,136,15], "classIoss_1_1Tet7.html#aeef6548bb945ed9834a9ceef46a0c20e":[4,0,69,136,13], "classIoss_1_1Tet7.html#af07d90322884ef186c3e2c777ed13084":[4,0,69,136,10], "classIoss_1_1Tet8.html":[4,0,69,137], "classIoss_1_1Tet8.html#a00b61be09130b0410063302f64f43bcc":[4,0,69,137,5], "classIoss_1_1Tet8.html#a011bc0eff2c9265228cdf52b83678c9b":[4,0,69,137,7], "classIoss_1_1Tet8.html#a03b2292e8a7cdd7351e603e73134d34e":[4,0,69,137,15], "classIoss_1_1Tet8.html#a25457b776295b67a48a9ca00674f0d94":[4,0,69,137,13], "classIoss_1_1Tet8.html#a2e8a36b032da95bed6b7e1571428964f":[4,0,69,137,1], "classIoss_1_1Tet8.html#a30f56430f429096f36a3972a0b80cbd1":[4,0,69,137,16], "classIoss_1_1Tet8.html#a35ecd3d481252dff9eb20dc4dc49e36c":[4,0,69,137,20], "classIoss_1_1Tet8.html#a3ed02b12943ee78a551128eb1c40544f":[4,0,69,137,17], "classIoss_1_1Tet8.html#a4c7f31adf0bc54963f73e7514a0848e4":[4,0,69,137,12], "classIoss_1_1Tet8.html#a548e6882af1baf769ff64113da6a3570":[4,0,69,137,14], "classIoss_1_1Tet8.html#a5e8d00b887f319058205ed9248ea492b":[4,0,69,137,21], "classIoss_1_1Tet8.html#a6669f4ba0986fb3a72da72a81759bd16":[4,0,69,137,23], "classIoss_1_1Tet8.html#a7de7e6c605fb27d31a803cd374c5e40e":[4,0,69,137,0], "classIoss_1_1Tet8.html#a9137b19a3fb4cec9a75d932a19fb88a4":[4,0,69,137,3], "classIoss_1_1Tet8.html#a9885a8df8a5deb1ebe64d055e0381edf":[4,0,69,137,2], "classIoss_1_1Tet8.html#a9cfdf666e5e3997eb04d6b64fca2aafe":[4,0,69,137,9], "classIoss_1_1Tet8.html#ab10481a406a6e6c21b9ad1927edea4f0":[4,0,69,137,4], "classIoss_1_1Tet8.html#ac3213933e5e7534d6e57785451788dd1":[4,0,69,137,8], "classIoss_1_1Tet8.html#ad8b8917b2d07797175cde71693211f70":[4,0,69,137,10], "classIoss_1_1Tet8.html#ae1058c79432e4ad3819aa6d1dc289da4":[4,0,69,137,22], "classIoss_1_1Tet8.html#ae34777703a05db0dea75a51fd4c9369f":[4,0,69,137,11], "classIoss_1_1Tet8.html#af22d74d02ec643002e8f29ed43afd1af":[4,0,69,137,6], "classIoss_1_1Tet8.html#afaf24cab8a279fa5198dd013d24435ca":[4,0,69,137,18], "classIoss_1_1Tet8.html#afd832344bca83f1bb0b6d6501b6d0403":[4,0,69,137,19], "classIoss_1_1Tracer.html":[4,0,69,138], "classIoss_1_1Tracer.html#a0424194979de9618ae5aa5ace9238059":[4,0,69,138,2], "classIoss_1_1Tracer.html#a162b60918f354c5b578dd176db7d18b5":[4,0,69,138,1], "classIoss_1_1Tracer.html#a77abfa36452763455cfae5f9b3dbec3c":[4,0,69,138,0], "classIoss_1_1Transform.html":[4,0,69,139], "classIoss_1_1Transform.html#a037d9cb9194d128d62c078c76e2a3e9c":[4,0,69,139,4], "classIoss_1_1Transform.html#a08b3d25e81aad971319e5226dbe6c5d4":[4,0,69,139,8], "classIoss_1_1Transform.html#a0a04fddfb90aa8093846bca0bfd5bae9":[4,0,69,139,9], "classIoss_1_1Transform.html#a2e07c7b72c70b6571745cad8c19829aa":[4,0,69,139,2], "classIoss_1_1Transform.html#a2ed9cede3ba9cca42682290603977b66":[4,0,69,139,1], "classIoss_1_1Transform.html#a38a16d4864b0c5b0fd9748a4546167a5":[4,0,69,139,6], "classIoss_1_1Transform.html#a73a8a80e4a4ff6a3c8b3a7c8ca6173c3":[4,0,69,139,3], "classIoss_1_1Transform.html#abf6cd01b7fdc9b09b9f956da4904e242":[4,0,69,139,5], "classIoss_1_1Transform.html#ad567453635ee4e6bcc3bb20279ddc74e":[4,0,69,139,0], "classIoss_1_1Transform.html#ae6af4e1c07b4dbbc84cc12ff1485b062":[4,0,69,139,7], "classIoss_1_1Tri3.html":[4,0,69,140], "classIoss_1_1Tri3.html#a00497b28142b0128564efc4485abac40":[4,0,69,140,21], "classIoss_1_1Tri3.html#a0afecfcc2808957fe70dc8eff7859d23":[4,0,69,140,13], "classIoss_1_1Tri3.html#a0c1427196558a2add60569c581948044":[4,0,69,140,7], "classIoss_1_1Tri3.html#a1dd94af979b99b166e4a97399d4aaa18":[4,0,69,140,3], "classIoss_1_1Tri3.html#a3fcd8ca13ccdb29ddde6b26a30800f09":[4,0,69,140,5], "classIoss_1_1Tri3.html#a44fb0127fc9e6387d76a56fdbb6aea36":[4,0,69,140,2], "classIoss_1_1Tri3.html#a5af625ebd0a0f5856791f94a6b19326b":[4,0,69,140,9], "classIoss_1_1Tri3.html#a70d571e1b83b73d99e2e2eb558e19f4c":[4,0,69,140,6], "classIoss_1_1Tri3.html#a70e465e12ad1fdd7e71d8d45a2cbf624":[4,0,69,140,20], "classIoss_1_1Tri3.html#a7d3559610a65520e9219ce2c6f596083":[4,0,69,140,12], "classIoss_1_1Tri3.html#a97ebfc797a34a6a75effb91965372580":[4,0,69,140,1], "classIoss_1_1Tri3.html#a99a9fcf57e733edceb2c868f3e670f3f":[4,0,69,140,14], "classIoss_1_1Tri3.html#a9d0a293948f686a44a6fc33ca79e59d3":[4,0,69,140,18], "classIoss_1_1Tri3.html#a9d3a5e2ff52cfa2d372963388fc4c8b9":[4,0,69,140,22], "classIoss_1_1Tri3.html#abcf3977487f14331b788a2244e5dfeed":[4,0,69,140,15], "classIoss_1_1Tri3.html#acd35db085d490501cc1861eaa15dd1de":[4,0,69,140,19], "classIoss_1_1Tri3.html#ad2193f85fe82211f182eda2e22f2d3b7":[4,0,69,140,10], "classIoss_1_1Tri3.html#ad2aeaef685733064c58871168b2da196":[4,0,69,140,16], "classIoss_1_1Tri3.html#ad58d40594c44f55f78620daf1e9beddd":[4,0,69,140,8], "classIoss_1_1Tri3.html#add8e943c4537c3ae5b8d5bd12a1412c9":[4,0,69,140,0], "classIoss_1_1Tri3.html#aeecc1f6ad221d7c624b3e255bbcfd25c":[4,0,69,140,11], "classIoss_1_1Tri3.html#afbfec6c87e7f29b04e226a6b921eb4b5":[4,0,69,140,4], "classIoss_1_1Tri3.html#afd12cfff5e317ce895ad210afaddac44":[4,0,69,140,17], "classIoss_1_1Tri4.html":[4,0,69,141], "classIoss_1_1Tri4.html#a013db626c1488d5b9aeefd90ded56274":[4,0,69,141,3], "classIoss_1_1Tri4.html#a089412d62e838525bae41dd2b3c8a863":[4,0,69,141,10], "classIoss_1_1Tri4.html#a0c3f8b9c919e0a203797a30e86989076":[4,0,69,141,4], "classIoss_1_1Tri4.html#a240083abc5d59f707bde11529a5e0251":[4,0,69,141,21], "classIoss_1_1Tri4.html#a2e741315708bd0bd49860bcc8a737677":[4,0,69,141,14], "classIoss_1_1Tri4.html#a35d4c4b88da6fbc2a012165929da6eda":[4,0,69,141,22], "classIoss_1_1Tri4.html#a5068f545c8885247fd7335f7558d6f3d":[4,0,69,141,12], "classIoss_1_1Tri4.html#a58650889ae52b5b76902bbbeb90ebd9b":[4,0,69,141,1], "classIoss_1_1Tri4.html#a5b5f986611e5685a1534813de33a673f":[4,0,69,141,0], "classIoss_1_1Tri4.html#a67f786bb5cfec7bec072ec06f32c0915":[4,0,69,141,18], "classIoss_1_1Tri4.html#a6a45356f2540b9387c5fbc22b3fba97d":[4,0,69,141,13], "classIoss_1_1Tri4.html#a71ef18b101d0c8d03890792977480271":[4,0,69,141,11], "classIoss_1_1Tri4.html#a8694a27fd6128adf1bbb3169eb71843e":[4,0,69,141,8], "classIoss_1_1Tri4.html#a8d04a744ec919be6705975b5410757e1":[4,0,69,141,9], "classIoss_1_1Tri4.html#a9559b34bd82633bcf034903c815fa0b6":[4,0,69,141,17], "classIoss_1_1Tri4.html#aa0c9dd8db3639cb06366eae3d7fba154":[4,0,69,141,6], "classIoss_1_1Tri4.html#ab6d214f03ef7b7f8438c04d08a6693f4":[4,0,69,141,16], "classIoss_1_1Tri4.html#ac5ef86f7468ed92ebd47434108b0e793":[4,0,69,141,15], "classIoss_1_1Tri4.html#ac8a61b40a3db3a2b4d35b2726b582d69":[4,0,69,141,2], "classIoss_1_1Tri4.html#ad4ae0392238aa94bf74cbd1fb4d72e39":[4,0,69,141,7], "classIoss_1_1Tri4.html#ae019a32790a14f676230d55bc11bcd23":[4,0,69,141,5], "classIoss_1_1Tri4.html#ae423f11a0fb84600efddb6bd11277112":[4,0,69,141,19], "classIoss_1_1Tri4.html#afe46a478baaa7c441ecec0924be27480":[4,0,69,141,20], "classIoss_1_1Tri4a.html":[4,0,69,142], "classIoss_1_1Tri4a.html#a25910996f609d6f00a3ba71f7ccb5fc3":[4,0,69,142,5], "classIoss_1_1Tri4a.html#a2815b2cd0b48f3dfc6f1c5a2b61d1178":[4,0,69,142,1], "classIoss_1_1Tri4a.html#a2a97cb506ec29eb05fc5130982610f92":[4,0,69,142,8], "classIoss_1_1Tri4a.html#a424c58fabd60b466719d6faaf0003f1f":[4,0,69,142,20], "classIoss_1_1Tri4a.html#a51beb2b1f3bc2ad9081722e8bb9d75cd":[4,0,69,142,19], "classIoss_1_1Tri4a.html#a59649ebbd2ddf4a5e14a6ae3f645f20e":[4,0,69,142,2], "classIoss_1_1Tri4a.html#a5dfe322ed0a094e93eaa992f99cec871":[4,0,69,142,12], "classIoss_1_1Tri4a.html#a6814569dd48827ad9762bf043666ccdf":[4,0,69,142,21], "classIoss_1_1Tri4a.html#a6c328ee45b3fe18d94942c14002d7dc4":[4,0,69,142,3], "classIoss_1_1Tri4a.html#a6e1d4ff5e717b1ab4db9cd36ae560c4e":[4,0,69,142,0], "classIoss_1_1Tri4a.html#a76478395a1e3567f128cf1cdbf9d2838":[4,0,69,142,17], "classIoss_1_1Tri4a.html#a77ed4a87c304c42a5a95baed8e64741b":[4,0,69,142,23], "classIoss_1_1Tri4a.html#a7bb3df352e69e1b9dae27f72dd45de04":[4,0,69,142,4], "classIoss_1_1Tri4a.html#a8056802fee146e9590b4f503cc151990":[4,0,69,142,22], "classIoss_1_1Tri4a.html#a8de8b020910eaeff60e169696a31b081":[4,0,69,142,10], "classIoss_1_1Tri4a.html#a9db31edf11f7f67633f8e4472e651558":[4,0,69,142,15], "classIoss_1_1Tri4a.html#ac4a6e2c1e1a9128dc0103b3dd5f60648":[4,0,69,142,7], "classIoss_1_1Tri4a.html#ac76ddceb4fb6b8e63abdb7973c00577f":[4,0,69,142,16], "classIoss_1_1Tri4a.html#ac8b593d930d34b65e8b229fc7b831163":[4,0,69,142,6], "classIoss_1_1Tri4a.html#ade855f124f71b4632990cc8a94715243":[4,0,69,142,14], "classIoss_1_1Tri4a.html#ae11cd6b6c936f596284fd30d427ede78":[4,0,69,142,18], "classIoss_1_1Tri4a.html#ae189248fdfffb9723f0940a28fba0f59":[4,0,69,142,13], "classIoss_1_1Tri4a.html#aecb707faf827cfa3d7674a50cd8a0e01":[4,0,69,142,11], "classIoss_1_1Tri4a.html#af7a441282b97165a2efc948dacd45d34":[4,0,69,142,9], "classIoss_1_1Tri6.html":[4,0,69,143], "classIoss_1_1Tri6.html#a1742a5d223acd57dd35601558a8e88ea":[4,0,69,143,18], "classIoss_1_1Tri6.html#a22e045b48cdd439d6ca9ada864f7c0fa":[4,0,69,143,12], "classIoss_1_1Tri6.html#a2342fb9e4e320d5d5aae6121ada1dda9":[4,0,69,143,19], "classIoss_1_1Tri6.html#a3100ba4a5d131f86c926b1159704d0f2":[4,0,69,143,5], "classIoss_1_1Tri6.html#a32453b699308c9fb01137085fffecc8f":[4,0,69,143,4], "classIoss_1_1Tri6.html#a4f08c83b56ff296e11f39206148703f9":[4,0,69,143,1], "classIoss_1_1Tri6.html#a770e5eaa73aeed57ea57a9b38f57de69":[4,0,69,143,16], "classIoss_1_1Tri6.html#a7f8deedf41a215512a738cd93eaaa0e1":[4,0,69,143,21], "classIoss_1_1Tri6.html#a879f00a93ef7588a1cd0fcff818e6230":[4,0,69,143,15], "classIoss_1_1Tri6.html#a9cd8881347532603f209a71824381589":[4,0,69,143,20], "classIoss_1_1Tri6.html#aa8b6274f991d8bd4cf3271d6ab727604":[4,0,69,143,17], "classIoss_1_1Tri6.html#aab22eefd376744d44ceebff8c26f1d44":[4,0,69,143,7], "classIoss_1_1Tri6.html#aab2eb3ab749d58b54e324f0ce144444e":[4,0,69,143,9], "classIoss_1_1Tri6.html#ab799c277be6ff03318328af89be88dc2":[4,0,69,143,2], "classIoss_1_1Tri6.html#ab8509e9f199d876eb3daca8296f544d9":[4,0,69,143,13], "classIoss_1_1Tri6.html#abe906bca33957d2182597376f861d14b":[4,0,69,143,14], "classIoss_1_1Tri6.html#ad2bccfaad6094b531d2f5819b61365e9":[4,0,69,143,0], "classIoss_1_1Tri6.html#ae7fd816d324b8f623f374926204233dd":[4,0,69,143,11], "classIoss_1_1Tri6.html#ae85c16cbeb78fca3f21009c965151e2a":[4,0,69,143,6], "classIoss_1_1Tri6.html#aec005d92c3ed3ea2c11934e4e717193c":[4,0,69,143,22], "classIoss_1_1Tri6.html#af2afd7e564e1fe0bcfee313bdaed11b8":[4,0,69,143,3], "classIoss_1_1Tri6.html#af445874fc040863b4b365dffb4cd42ba":[4,0,69,143,8], "classIoss_1_1Tri6.html#afeaf081098bce861ca91adfddc120341":[4,0,69,143,10], "classIoss_1_1Tri7.html":[4,0,69,144], "classIoss_1_1Tri7.html#a023e98ceb4d292a9eb7e859393c73133":[4,0,69,144,20], "classIoss_1_1Tri7.html#a08c0d7df5d23b5d167b3da41c471c5a8":[4,0,69,144,10], "classIoss_1_1Tri7.html#a0fd12222086391d13953446553357e24":[4,0,69,144,1], "classIoss_1_1Tri7.html#a177a84df7606246e26d4fdf6a45ccdff":[4,0,69,144,14], "classIoss_1_1Tri7.html#a1b46841ac4427ba6a7250ad01e48fd85":[4,0,69,144,17], "classIoss_1_1Tri7.html#a1caacfbbd85dacdfcea7456d4f34785b":[4,0,69,144,16], "classIoss_1_1Tri7.html#a243a435eb0062b91461ed2a13defc420":[4,0,69,144,19], "classIoss_1_1Tri7.html#a2767210d1ab21177f2fb73fa80701bcf":[4,0,69,144,6], "classIoss_1_1Tri7.html#a2e36fa4800efaa5612e5b603bbcd1bd8":[4,0,69,144,12], "classIoss_1_1Tri7.html#a2e3a4a6d48b34a490df162de77a51988":[4,0,69,144,9], "classIoss_1_1Tri7.html#a398c635a1787e692ab31c4cad5add040":[4,0,69,144,2], "classIoss_1_1Tri7.html#a47d03409072406d0d2a45f0cc2d7b86b":[4,0,69,144,5], "classIoss_1_1Tri7.html#a4fe80cae1ee5fd3070c1b17cade5e59f":[4,0,69,144,8], "classIoss_1_1Tri7.html#a651838ca5b586bd9419b6f98766c4365":[4,0,69,144,7], "classIoss_1_1Tri7.html#a6f48eb90ab2f175b55eafc66d0fffff1":[4,0,69,144,11], "classIoss_1_1Tri7.html#a8de757a487f8f32ae082a216078abaf2":[4,0,69,144,4], "classIoss_1_1Tri7.html#a9797e1b785695a4d26ee4fe2a67677c9":[4,0,69,144,18], "classIoss_1_1Tri7.html#a9e2e5de42b3a3efa1ddd9c7a6633f30d":[4,0,69,144,13], "classIoss_1_1Tri7.html#abfd7a5ef7840894f75b65ae35d45710a":[4,0,69,144,21], "classIoss_1_1Tri7.html#ac4c3eb039489a5f276e9a1492267502e":[4,0,69,144,3], "classIoss_1_1Tri7.html#ac4dbf0f7cae3c70328909d204084eba2":[4,0,69,144,0], "classIoss_1_1Tri7.html#ac60c95c0d3b0f4b380ad7456934c759e":[4,0,69,144,22], "classIoss_1_1Tri7.html#afc03e1ed3e41a9bd3f691ab2a5a83287":[4,0,69,144,15], "classIoss_1_1TriShell3.html":[4,0,69,145], "classIoss_1_1TriShell3.html#a036e26dedc61661127a9b1895218d946":[4,0,69,145,7], "classIoss_1_1TriShell3.html#a0dc6bebf7ea7657abc2e63a12bd0bddb":[4,0,69,145,16], "classIoss_1_1TriShell3.html#a190b3a5b0e4d4f626ad19c35b7fe4d01":[4,0,69,145,19], "classIoss_1_1TriShell3.html#a1e14fe5ed3c3f79ef106dc7a4245154e":[4,0,69,145,14], "classIoss_1_1TriShell3.html#a2c179e48f700166e5470c36a4d7b1c55":[4,0,69,145,13], "classIoss_1_1TriShell3.html#a3a2e43db0446b70dae125cea9103e250":[4,0,69,145,21], "classIoss_1_1TriShell3.html#a504a11c3dbb30648fbcf8cca05eb6496":[4,0,69,145,2], "classIoss_1_1TriShell3.html#a5bf8fbe762cbb91d057a644aecacea34":[4,0,69,145,17], "classIoss_1_1TriShell3.html#a5c399b2094722db9709c3f80540b50a8":[4,0,69,145,0], "classIoss_1_1TriShell3.html#a6e9c7dd07e5e92a148701b33061d1dd4":[4,0,69,145,8], "classIoss_1_1TriShell3.html#a71d65344c4cc54507ad01c5999f89e35":[4,0,69,145,23], "classIoss_1_1TriShell3.html#a830f20e54dba1b40d77ad72bee5e5836":[4,0,69,145,11], "classIoss_1_1TriShell3.html#a849f39ba598476953e68b20eb68afcf5":[4,0,69,145,15], "classIoss_1_1TriShell3.html#a8945846e559d73a82c949926ddbe8bd8":[4,0,69,145,5], "classIoss_1_1TriShell3.html#a982f9f10c322d7eed5f2f16e6f7a914e":[4,0,69,145,9], "classIoss_1_1TriShell3.html#ab0089b7b18ba4646977b43755c73f2c3":[4,0,69,145,6], "classIoss_1_1TriShell3.html#ab25e33b89086a7ee7d639919d5d8f107":[4,0,69,145,3], "classIoss_1_1TriShell3.html#abc756a25684952aa129837486d155744":[4,0,69,145,12], "classIoss_1_1TriShell3.html#ac85c51dd7e794a921c51cb7da9966fc9":[4,0,69,145,10], "classIoss_1_1TriShell3.html#ae7df765f22e03ab1e76c30e0b77fcdf5":[4,0,69,145,1], "classIoss_1_1TriShell3.html#aed8950ad60c701b815b8496a0c50e690":[4,0,69,145,20], "classIoss_1_1TriShell3.html#af4adcf209c460b2ebd782db1597601d0":[4,0,69,145,22], "classIoss_1_1TriShell3.html#afa185d68a0c59bd01751a48b97fcfd98":[4,0,69,145,18], "classIoss_1_1TriShell3.html#aff6973b37150283884832ca0a9564dab":[4,0,69,145,4], "classIoss_1_1TriShell4.html":[4,0,69,146], "classIoss_1_1TriShell4.html#a002a93c56b3124909307580a2a7316ae":[4,0,69,146,2], "classIoss_1_1TriShell4.html#a1988b9ea1ca6ff408342c89f2678101e":[4,0,69,146,3], "classIoss_1_1TriShell4.html#a1b9c25f1f7d7b7f995ce4717cdb56102":[4,0,69,146,17], "classIoss_1_1TriShell4.html#a20be75da2c06aaf57c3b4e051a8f9d63":[4,0,69,146,16], "classIoss_1_1TriShell4.html#a34f96eabcb67dd336f4bba6eae6547ae":[4,0,69,146,10], "classIoss_1_1TriShell4.html#a420e5437756539fceb08c38a614cea47":[4,0,69,146,1], "classIoss_1_1TriShell4.html#a4287b9b457030b490a4383ac36087439":[4,0,69,146,8], "classIoss_1_1TriShell4.html#a45d002b40c8e4f7001bf1cea049d7a0e":[4,0,69,146,5], "classIoss_1_1TriShell4.html#a4abc705677e620df0497c6e78b63e7ec":[4,0,69,146,12], "classIoss_1_1TriShell4.html#a4c20572cd3c4110a436a1e1cbfb2f8a9":[4,0,69,146,21], "classIoss_1_1TriShell4.html#a6d01004f3fc5053893de464fe61056f8":[4,0,69,146,14], "classIoss_1_1TriShell4.html#a7afc1d0da6821aefbe1eb103ff50dab4":[4,0,69,146,11], "classIoss_1_1TriShell4.html#a82ddc1635b0291c35c8498122d7e5dc1":[4,0,69,146,4], "classIoss_1_1TriShell4.html#a84d116f292724ce2e2112fa850f9b322":[4,0,69,146,20], "classIoss_1_1TriShell4.html#a87258b7f488a85a8138f0603e9d0acdc":[4,0,69,146,0], "classIoss_1_1TriShell4.html#a888eba93c31eb1b815559d1a77602c38":[4,0,69,146,7], "classIoss_1_1TriShell4.html#a98a21bb0323cb09b92909e66f9ed073c":[4,0,69,146,9], "classIoss_1_1TriShell4.html#aa7e22e4178c14763a481339179b4e137":[4,0,69,146,15], "classIoss_1_1TriShell4.html#aa87c9628c2332642aa96d1e405883238":[4,0,69,146,19], "classIoss_1_1TriShell4.html#aadb36aeda57340bd17137d8783b44e93":[4,0,69,146,22], "classIoss_1_1TriShell4.html#aaf10025253ad5d01cd9db87f4d916991":[4,0,69,146,18], "classIoss_1_1TriShell4.html#ad7afb332445b43a4788a44c63250ee42":[4,0,69,146,6], "classIoss_1_1TriShell4.html#ae9ce2d0c366d5d5c875a5cdda558c3d4":[4,0,69,146,23], "classIoss_1_1TriShell4.html#af1eb529200e7724ca1df486ab1aca437":[4,0,69,146,13], "classIoss_1_1TriShell6.html":[4,0,69,147], "classIoss_1_1TriShell6.html#a0ce4c50290a2f86e7df1e6399b03f046":[4,0,69,147,5], "classIoss_1_1TriShell6.html#a0ea48813e987a2edf0eb2782f0490532":[4,0,69,147,10], "classIoss_1_1TriShell6.html#a24313d5b5259f993b77f5b97d6f2e546":[4,0,69,147,7], "classIoss_1_1TriShell6.html#a2c2ab11aa74661eb2f1f419ca3c380e6":[4,0,69,147,2], "classIoss_1_1TriShell6.html#a3fea7f1a6bca3646c964f3dacb0865c9":[4,0,69,147,21], "classIoss_1_1TriShell6.html#a4641861d7b4a840480f4c237089faef9":[4,0,69,147,11], "classIoss_1_1TriShell6.html#a46b0355e6ca9e177b1b5b346062a8356":[4,0,69,147,4], "classIoss_1_1TriShell6.html#a6962dd09041216a482023cfa6f88c01a":[4,0,69,147,22], "classIoss_1_1TriShell6.html#a6addf0ab034e091a17d078ff745e1d47":[4,0,69,147,16] };
nschloe/seacas
docs/ioss_html/navtreeindex17.js
JavaScript
bsd-3-clause
18,862
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Reflection; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System.Collections.Generic; using System.Xml; namespace OpenSim.Region.Framework.Scenes { public partial class SceneObjectGroup : EntityBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Force all task inventories of prims in the scene object to persist /// </summary> public void ForceInventoryPersistence() { lock (m_parts) { foreach (SceneObjectPart part in m_parts.Values) { part.Inventory.ForceInventoryPersistence(); } } } /// <summary> /// Start the scripts contained in all the prims in this group. /// </summary> public void CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) { // Don't start scripts if they're turned off in the region! if (!m_scene.RegionInfo.RegionSettings.DisableScripts) { foreach (SceneObjectPart part in m_parts.Values) { part.Inventory.CreateScriptInstances(startParam, postOnRez, engine, stateSource); } } } /// <summary> /// Stop the scripts contained in all the prims in this group /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { lock (m_parts) { foreach (SceneObjectPart part in m_parts.Values) { part.Inventory.RemoveScriptInstances(sceneObjectBeingDeleted); } } } /// <summary> /// /// </summary> /// <param name="remoteClient"></param> /// <param name="localID"></param> public bool GetPartInventoryFileName(IClientAPI remoteClient, uint localID) { SceneObjectPart part = GetChildPart(localID); if (part != null) { return part.Inventory.GetInventoryFileName(remoteClient, localID); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find part {0} in object group {1}, {2} to retreive prim inventory", localID, Name, UUID); } return false; } /// <summary> /// Return serialized inventory metadata for the given constituent prim /// </summary> /// <param name="localID"></param> /// <param name="xferManager"></param> public void RequestInventoryFile(IClientAPI client, uint localID, IXfer xferManager) { SceneObjectPart part = GetChildPart(localID); if (part != null) { part.Inventory.RequestInventoryFile(client, xferManager); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find part {0} in object group {1}, {2} to request inventory data", localID, Name, UUID); } } /// <summary> /// Add an inventory item to a prim in this group. /// </summary> /// <param name="remoteClient"></param> /// <param name="localID"></param> /// <param name="item"></param> /// <param name="copyItemID">The item UUID that should be used by the new item.</param> /// <returns></returns> public bool AddInventoryItem(IClientAPI remoteClient, uint localID, InventoryItemBase item, UUID copyItemID) { UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID; SceneObjectPart part = GetChildPart(localID); if (part != null) { TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ItemID = newItemId; taskItem.AssetID = item.AssetID; taskItem.Name = item.Name; taskItem.Description = item.Description; taskItem.OwnerID = part.OwnerID; // Transfer ownership taskItem.CreatorID = item.CreatorIdAsUuid; taskItem.Type = item.AssetType; taskItem.InvType = item.InvType; if (remoteClient != null && remoteClient.AgentId != part.OwnerID && m_scene.Permissions.PropagatePermissions()) { taskItem.BasePermissions = item.BasePermissions & item.NextPermissions; taskItem.CurrentPermissions = item.CurrentPermissions & item.NextPermissions; taskItem.EveryonePermissions = item.EveryOnePermissions & item.NextPermissions; taskItem.GroupPermissions = item.GroupPermissions & item.NextPermissions; taskItem.NextPermissions = item.NextPermissions; taskItem.CurrentPermissions |= 8; } else { taskItem.BasePermissions = item.BasePermissions; taskItem.CurrentPermissions = item.CurrentPermissions; taskItem.CurrentPermissions |= 8; taskItem.EveryonePermissions = item.EveryOnePermissions; taskItem.GroupPermissions = item.GroupPermissions; taskItem.NextPermissions = item.NextPermissions; } taskItem.Flags = item.Flags; // TODO: These are pending addition of those fields to TaskInventoryItem // taskItem.SalePrice = item.SalePrice; // taskItem.SaleType = item.SaleType; taskItem.CreationDate = (uint)item.CreationDate; bool addFromAllowedDrop = false; if (remoteClient!=null) { addFromAllowedDrop = remoteClient.AgentId != part.OwnerID; } part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop); return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}", localID, Name, UUID, newItemId); } return false; } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="primID"></param> /// <param name="itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID) { SceneObjectPart part = GetChildPart(primID); if (part != null) { return part.Inventory.GetInventoryItem(itemID); } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}", primID, part.Name, part.UUID, itemID); } return null; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory</param> /// <returns>false if the item did not exist, true if the update occurred succesfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { SceneObjectPart part = GetChildPart(item.ParentPartID); if (part != null) { part.Inventory.UpdateInventoryItem(item); return true; } else { m_log.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim ID {0} to update item {1}, {2}", item.ParentPartID, item.Name, item.ItemID); } return false; } public int RemoveInventoryItem(uint localID, UUID itemID) { SceneObjectPart part = GetChildPart(localID); if (part != null) { int type = part.Inventory.RemoveInventoryItem(itemID); return type; } return -1; } public uint GetEffectivePermissions() { uint perms=(uint)(PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Move | PermissionMask.Transfer) | 7; uint ownerMask = 0x7fffffff; foreach (SceneObjectPart part in m_parts.Values) { ownerMask &= part.OwnerMask; perms &= part.Inventory.MaskEffectivePermissions(); } if ((ownerMask & (uint)PermissionMask.Modify) == 0) perms &= ~(uint)PermissionMask.Modify; if ((ownerMask & (uint)PermissionMask.Copy) == 0) perms &= ~(uint)PermissionMask.Copy; if ((ownerMask & (uint)PermissionMask.Transfer) == 0) perms &= ~(uint)PermissionMask.Transfer; // If root prim permissions are applied here, this would screw // with in-inventory manipulation of the next owner perms // in a major way. So, let's move this to the give itself. // Yes. I know. Evil. // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0) // perms &= ~((uint)PermissionMask.Modify >> 13); // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0) // perms &= ~((uint)PermissionMask.Copy >> 13); // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0) // perms &= ~((uint)PermissionMask.Transfer >> 13); return perms; } public void ApplyNextOwnerPermissions() { foreach (SceneObjectPart part in m_parts.Values) { part.ApplyNextOwnerPermissions(); } } public string GetStateSnapshot() { Dictionary<UUID, string> states = new Dictionary<UUID, string>(); foreach (SceneObjectPart part in m_parts.Values) { foreach (KeyValuePair<UUID, string> s in part.Inventory.GetScriptStates()) states[s.Key] = s.Value; } if (states.Count < 1) return ""; XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ScriptData", ""); xmldoc.AppendChild(rootElement); XmlElement wrapper = xmldoc.CreateElement("", "ScriptStates", ""); rootElement.AppendChild(wrapper); foreach (KeyValuePair<UUID, string> state in states) { XmlDocument sdoc = new XmlDocument(); sdoc.LoadXml(state.Value); XmlNodeList rootL = sdoc.GetElementsByTagName("State"); XmlNode rootNode = rootL[0]; XmlNode newNode = xmldoc.ImportNode(rootNode, true); wrapper.AppendChild(newNode); } return xmldoc.InnerXml; } public void SetState(string objXMLData, IScene ins) { if (!(ins is Scene)) return; Scene s = (Scene)ins; if (objXMLData == String.Empty) return; IScriptModule scriptModule = null; foreach (IScriptModule sm in s.RequestModuleInterfaces<IScriptModule>()) { if (sm.ScriptEngineName == s.DefaultScriptEngine) scriptModule = sm; else if (scriptModule == null) scriptModule = sm; } if (scriptModule == null) return; XmlDocument doc = new XmlDocument(); try { doc.LoadXml(objXMLData); } catch (Exception) // (System.Xml.XmlException) { // We will get here if the XML is invalid or in unit // tests. Really should determine which it is and either // fail silently or log it // Fail silently, for now. // TODO: Fix this // return; } XmlNodeList rootL = doc.GetElementsByTagName("ScriptData"); if (rootL.Count != 1) return; XmlElement rootE = (XmlElement)rootL[0]; XmlNodeList dataL = rootE.GetElementsByTagName("ScriptStates"); if (dataL.Count != 1) return; XmlElement dataE = (XmlElement)dataL[0]; foreach (XmlNode n in dataE.ChildNodes) { XmlElement stateE = (XmlElement)n; UUID itemID = new UUID(stateE.GetAttribute("UUID")); scriptModule.SetXMLState(itemID, n.OuterXml); } } public void ResumeScripts() { foreach (SceneObjectPart part in m_parts.Values) { part.Inventory.ResumeScripts(); } } } }
cdbean/CySim
OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
C#
bsd-3-clause
16,199
RSpec.describe Mdm::WebSite, type: :model do it_should_behave_like 'Metasploit::Concern.run' context 'factory' do it 'should be valid' do web_site = FactoryBot.build(:mdm_web_site) expect(web_site).to be_valid end end context 'database' do context 'timestamps'do it { is_expected.to have_db_column(:created_at).of_type(:datetime).with_options(:null => false) } it { is_expected.to have_db_column(:updated_at).of_type(:datetime).with_options(:null => false) } end context 'columns' do it { is_expected.to have_db_column(:service_id).of_type(:integer).with_options(:null => false) } it { is_expected.to have_db_column(:vhost).of_type(:string) } it { is_expected.to have_db_column(:comments).of_type(:text) } it { is_expected.to have_db_column(:options).of_type(:text) } end context 'indices' do it { is_expected.to have_db_index(:comments) } it { is_expected.to have_db_index(:options) } it { is_expected.to have_db_index(:vhost) } end end context '#destroy' do it 'should successfully destroy the object' do web_site = FactoryBot.create(:mdm_web_site) expect { web_site.destroy }.to_not raise_error expect { web_site.reload }.to raise_error(ActiveRecord::RecordNotFound) end end context 'associations' do it { is_expected.to belong_to(:service).class_name('Mdm::Service') } it { is_expected.to have_many(:web_forms).class_name('Mdm::WebForm').dependent(:destroy) } it { is_expected.to have_many(:web_pages).class_name('Mdm::WebPage').dependent(:destroy) } it { is_expected.to have_many(:web_vulns).class_name('Mdm::WebVuln').dependent(:destroy) } end context 'methods' do context '#form_count' do it 'should return an accurate count of associated Webforms' do mysite = FactoryBot.create(:mdm_web_site) FactoryBot.create(:mdm_web_form, :web_site => mysite) FactoryBot.create(:mdm_web_form, :web_site => mysite) expect(mysite.form_count).to eq(2) FactoryBot.create(:mdm_web_form, :web_site => mysite) expect(mysite.form_count).to eq(3) end end context '#page_count' do it 'should return an accurate count of associated Webpages' do mysite = FactoryBot.create(:mdm_web_site) FactoryBot.create(:mdm_web_page, :web_site => mysite) FactoryBot.create(:mdm_web_page, :web_site => mysite) expect(mysite.page_count).to eq(2) FactoryBot.create(:mdm_web_page, :web_site => mysite) expect(mysite.page_count).to eq(3) end end context '#vuln_count' do it 'should return an accurate count of associated Webvulns' do mysite = FactoryBot.create(:mdm_web_site) FactoryBot.create(:mdm_web_vuln, :web_site => mysite) FactoryBot.create(:mdm_web_vuln, :web_site => mysite) expect(mysite.vuln_count).to eq(2) FactoryBot.create(:mdm_web_vuln, :web_site => mysite) expect(mysite.vuln_count).to eq(3) end end end end
rapid7/metasploit_data_models
spec/app/models/mdm/web_site_spec.rb
Ruby
bsd-3-clause
3,095
package eta.runtime.thunk; import eta.runtime.stg.Closure; import eta.runtime.stg.StgContext; public class ApV extends UpdatableThunk { public Closure p; public ApV(final Closure p) { super(); this.p = p; } @Override public Closure thunkEnter(StgContext context) { return p.applyV(context); } }
pparkkin/eta
rts/src/eta/runtime/thunk/ApV.java
Java
bsd-3-clause
347
<?php $this->widget('application.modules.category.widgets.ListCategoryWidget', array('alias' => 'content_block_'.Yii::app()->language)); ?> <!--Blog start--> <div class="blog_wrapper"> <!--Blog container start--> <div class="blog container clearfix"> <?php $this->widget('application.modules.blog.widgets.ListBlogsWidget', array()); ?> <div class="clearfix"></div> </div> <!--Blog container end--> </div> <!--Blog end--> <!--Decorated separator--> <div class="decor_separator decor_07"></div> <!--Contacts--> <div class="contacts container"> <p class="address">вул.Підвальна 5, Львів, Україна, 79000 <br> arsenal.lviv@facebook.com <br> 067 372 4455</p> <?php Yii::import('application.extension.EGMap.*'); $gMap = new EGMap(); $gMap->setJsName('test_map'); $gMap->width = '100%'; $gMap->height = 440; $gMap->zoom = 16; $gMap->setCenter(49.841022, 24.035470); $info_box = new EGMapInfoBox('<div style="color:#fff;border: 1px solid black; margin-top: 8px; background: #000; padding: 5px;"><img src="/css/arsenal.jpg" width="100px"/></div>'); $info_box->pixelOffset = new EGMapSize('0','-140'); $info_box->maxWidth = 0; $info_box->boxStyle = array( 'width'=>'"120px"', 'height'=>'"120px"', 'background'=>'"url(http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/examples/tipbox.gif) no-repeat"' ); $info_box->closeBoxMargin = '"10px 2px 2px 2px"'; $info_box->infoBoxClearance = new EGMapSize(1,1); $info_box->enableEventPropagation ='"floatPane"'; $marker = new EGMapMarker(49.841022, 24.035470, array('title' => 'Ресторан "Арсенал"')); $marker->addHtmlInfoBox($info_box); $gMap->addMarker($marker); $gMap->renderMap(); ?> </div>
flesch91/uaweb-work.github.com
themes/arsenal/views/site/index.php
PHP
bsd-3-clause
1,937
/** * Copyright (c) 2013, 2016, The Regents of the University of California, The Cytoscape Consortium * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.ndexbio.task; import java.io.IOException; import java.sql.SQLException; import java.util.UUID; import org.ndexbio.common.models.dao.postgresql.TaskDAO; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.object.Status; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; public abstract class NdexTaskProcessor implements Runnable { protected boolean shutdown; public NdexTaskProcessor () { shutdown = false; } public void shutdown() { shutdown = true; } protected static void saveTaskStatus (UUID taskID, Status status, String message, String stackTrace) throws NdexException, SQLException, JsonParseException, JsonMappingException, IOException { try (TaskDAO dao = new TaskDAO ()) { dao.updateTaskStatus(taskID, status, message,stackTrace); dao.commit(); } } }
ndexbio/ndex-rest
src/main/java/org/ndexbio/task/NdexTaskProcessor.java
Java
bsd-3-clause
2,543
""" These URL patterns are included in two different ways in the main urls.py, with an extra argument present in one case. Thus, there are two different ways for each name to resolve and Django must distinguish the possibilities based on the argument list. """ from django.conf.urls import url from .views import empty_view urlpatterns = [ url(r'^part/(?P<value>\w+)/$', empty_view, name="part"), url(r'^part2/(?:(?P<value>\w+)/)?$', empty_view, name="part2"), ]
yephper/django
tests/urlpatterns_reverse/included_urls2.py
Python
bsd-3-clause
489
<?php use yii\db\Schema; use yii\db\Migration; class m150723_084129_news_create_table extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('news', [ 'id' => Schema::TYPE_PK, 'title' => Schema::TYPE_STRING . ' NOT NULL', 'dt_add' => Schema::TYPE_INTEGER . ' NOT NULL', 'content' => Schema::TYPE_TEXT . ' NOT NULL', 'tags' => Schema::TYPE_STRING . ' NOT NULL', 'status' => Schema::TYPE_INTEGER . ' NOT NULL', ], $tableOptions); } public function down() { $this->dropTable('news'); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ }
apuc/api
console/migrations/m150723_084129_news_create_table.php
PHP
bsd-3-clause
1,233
// Copyright 2019 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "starboard/shared/starboard/file_atomic_replace_write_file.h" #include <algorithm> #include "starboard/common/log.h" #include "starboard/file.h" #if SB_API_VERSION >= 12 namespace starboard { namespace shared { namespace starboard { bool SbFileAtomicReplaceWriteFile(const char* path, const char* data, int64_t data_size) { SbFileError error; SbFile temp_file = SbFileOpen( path, kSbFileCreateAlways | kSbFileWrite | kSbFileRead, NULL, &error); if (error != kSbFileOk) { return false; } SbFileTruncate(temp_file, 0); const char* source = data; int64_t to_write = data_size; while (to_write > 0) { const int to_write_max = static_cast<int>(std::min(to_write, static_cast<int64_t>(kSbInt32Max))); const int bytes_written = SbFileWrite(temp_file, source, to_write_max); if (bytes_written < 0) { SbFileClose(temp_file); SbFileDelete(path); return false; } source += bytes_written; to_write -= bytes_written; } SbFileFlush(temp_file); if (!SbFileClose(temp_file)) { return false; } return true; } } // namespace starboard } // namespace shared } // namespace starboard #endif // SB_API_VERSION >= 12
youtube/cobalt
starboard/shared/starboard/file_atomic_replace_write_file.cc
C++
bsd-3-clause
1,899
package com.groupon.lex.metrics.json; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.groupon.lex.metrics.Tags; import static com.groupon.lex.metrics.json.Json.extractMetricValue; import java.util.HashMap; import java.util.function.Function; import java.util.stream.Collectors; class JsonTags extends HashMap<String, Object> { private static final Function<Tags, JsonTags> TAGS_CACHE = CacheBuilder.newBuilder() .softValues() .build(CacheLoader.from((Tags in) -> new JsonTags(in)))::getUnchecked; public JsonTags() {} private JsonTags(Tags tags) { super(tags.stream() .collect(Collectors.toMap(tag_entry -> tag_entry.getKey(), tag_entry -> extractMetricValue(tag_entry.getValue())))); } public static JsonTags valueOf(Tags tags) { return TAGS_CACHE.apply(tags); } }
groupon/monsoon
exporter/src/main/java/com/groupon/lex/metrics/json/JsonTags.java
Java
bsd-3-clause
903