code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataFactory.Models { /// <summary> /// Defines values for GlobalParameterType. /// </summary> public static class GlobalParameterType { public const string Object = "Object"; public const string String = "String"; public const string Int = "Int"; public const string Float = "Float"; public const string Bool = "Bool"; public const string Array = "Array"; } }
yugangw-msft/azure-sdk-for-net
sdk/datafactory/Microsoft.Azure.Management.DataFactory/src/Generated/Models/GlobalParameterType.cs
C#
apache-2.0
823
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.buildout.config; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.jetbrains.python.PyBundle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.HashMap; import java.util.Map; public class BuildoutCfgColorsPage implements ColorSettingsPage { private static final AttributesDescriptor[] ATTRS = new AttributesDescriptor[]{ new AttributesDescriptor(PyBundle.message("buildout.color.section.name"), BuildoutCfgSyntaxHighlighter.BUILDOUT_SECTION_NAME), new AttributesDescriptor(PyBundle.message("buildout.color.key"), BuildoutCfgSyntaxHighlighter.BUILDOUT_KEY), new AttributesDescriptor(PyBundle.message("buildout.color.value"), BuildoutCfgSyntaxHighlighter.BUILDOUT_VALUE), new AttributesDescriptor(PyBundle.message("buildout.color.key.value.separator"), BuildoutCfgSyntaxHighlighter.BUILDOUT_KEY_VALUE_SEPARATOR), new AttributesDescriptor(PyBundle.message("buildout.color.comment"), BuildoutCfgSyntaxHighlighter.BUILDOUT_COMMENT) }; @NonNls private static final HashMap<String, TextAttributesKey> ourTagToDescriptorMap = new HashMap<>(); static { //ourTagToDescriptorMap.put("comment", DjangoTemplateHighlighterColors.DJANGO_COMMENT); } @Override @NotNull public String getDisplayName() { return PyBundle.message("buildout.config"); } @Override public Icon getIcon() { return BuildoutCfgFileType.INSTANCE.getIcon(); } @Override public AttributesDescriptor @NotNull [] getAttributeDescriptors() { return ATTRS; } @Override public ColorDescriptor @NotNull [] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @Override @NotNull public SyntaxHighlighter getHighlighter() { final SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(BuildoutCfgFileType.INSTANCE, null, null); assert highlighter != null; return highlighter; } @Override @NotNull public String getDemoText() { return "; Buildout config\n"+ "[buildout]\n" + "parts = python\n" + "develop = .\n" + "eggs = django-shorturls\n" + "\n" + "[python]\n" + "recipe = zc.recipe.egg\n" + "interpreter = python\n" + "eggs = ${buildout:eggs}"; } @Override public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return ourTagToDescriptorMap; } }
siosio/intellij-community
python/src/com/jetbrains/python/buildout/config/BuildoutCfgColorsPage.java
Java
apache-2.0
2,920
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jitsi.impl.neomedia.transform.zrtp; import gnu.java.zrtp.*; import gnu.java.zrtp.utils.*; import java.util.*; import org.jitsi.impl.neomedia.*; import org.jitsi.service.neomedia.*; /** * Controls zrtp in the MediaStream. * * @author Damian Minkov */ public class ZrtpControlImpl extends AbstractSrtpControl<ZRTPTransformEngine> implements ZrtpControl { /** * Additional info codes for and data to support ZRTP4J. * These could be added to the library. However they are specific for this * implementation, needing them for various GUI changes. */ public static enum ZRTPCustomInfoCodes { ZRTPDisabledByCallEnd, ZRTPEnabledByDefault, ZRTPEngineInitFailure, ZRTPNotEnabledByUser } /** * Whether current is master session. */ private boolean masterSession = false; /** * This is the connector, required to send ZRTP packets * via the DatagramSocket. */ private AbstractRTPConnector zrtpConnector = null; /** * Creates the control. */ public ZrtpControlImpl() { super(SrtpControlType.ZRTP); } /** * Cleans up the current zrtp control and its engine. */ @Override public void cleanup(Object user) { super.cleanup(user); zrtpConnector = null; } /* * (non-Javadoc) * * @see * net.java.sip.communicator.service.neomedia.ZrtpControl#getCiperString() */ public String getCipherString() { return getTransformEngine().getUserCallback().getCipherString(); } /** * Get negotiated ZRTP protocol version. * * @return the integer representation of the negotiated ZRTP protocol version. */ public int getCurrentProtocolVersion() { ZRTPTransformEngine zrtpEngine = this.transformEngine; return (zrtpEngine != null) ? zrtpEngine.getCurrentProtocolVersion() : 0; } /** * Return the zrtp hello hash String. * * @param index * Hello hash of the Hello packet identfied by index. Index must * be 0 <= index < SUPPORTED_ZRTP_VERSIONS. * @return String the zrtp hello hash. */ public String getHelloHash(int index) { return getTransformEngine().getHelloHash(index); } /** * Get the ZRTP Hello Hash data - separate strings. * * @param index * Hello hash of the Hello packet identfied by index. Index must * be 0 <= index < SUPPORTED_ZRTP_VERSIONS. * @return String array containing the version string at offset 0, the Hello * hash value as hex-digits at offset 1. Hello hash is available * immediately after class instantiation. Returns <code>null</code> * if ZRTP is not available. */ public String[] getHelloHashSep(int index) { return getTransformEngine().getHelloHashSep(index); } /** * Get number of supported ZRTP protocol versions. * * @return the number of supported ZRTP protocol versions. */ public int getNumberSupportedVersions() { ZRTPTransformEngine zrtpEngine = this.transformEngine; return (zrtpEngine != null) ? zrtpEngine.getNumberSupportedVersions() : 0; } /** * Get the peer's Hello Hash data. * * Use this method to get the peer's Hello Hash data. The method returns the * data as a string. * * @return a String containing the Hello hash value as hex-digits. * Peer Hello hash is available after we received a Hello packet * from our peer. If peer's hello hash is not available return null. */ public String getPeerHelloHash() { ZRTPTransformEngine zrtpEngine = this.transformEngine; return (zrtpEngine != null) ? zrtpEngine.getPeerHelloHash() : ""; } /* * (non-Javadoc) * * @see * net.java.sip.communicator.service.neomedia.ZrtpControl#getPeerZid * () */ public byte[] getPeerZid() { return getTransformEngine().getPeerZid(); } /* * (non-Javadoc) * * @see * net.java.sip.communicator.service.neomedia.ZrtpControl#getPeerZidString() */ public String getPeerZidString() { byte[] zid = getPeerZid(); String s = new String(ZrtpUtils.bytesToHexString(zid, zid.length)); return s; } /** * Method for getting the default secure status value for communication * * @return the default enabled/disabled status value for secure * communication */ public boolean getSecureCommunicationStatus() { ZRTPTransformEngine zrtpEngine = this.transformEngine; return (zrtpEngine != null) && zrtpEngine.getSecureCommunicationStatus(); } /* * (non-Javadoc) * * @see * net.java.sip.communicator.service.neomedia.ZrtpControl#getSecurityString * () */ public String getSecurityString() { return getTransformEngine().getUserCallback().getSecurityString(); } /** * Returns the timeout value that will we will wait * and fire timeout secure event if call is not secured. * The value is in milliseconds. * @return the timeout value that will we will wait * and fire timeout secure event if call is not secured. */ public long getTimeoutValue() { // this is the default value as mentioned in rfc6189 // we will later grab this setting from zrtp return 3750; } /** * Initializes a new <tt>ZRTPTransformEngine</tt> instance to be associated * with and used by this <tt>ZrtpControlImpl</tt> instance. * * @return a new <tt>ZRTPTransformEngine</tt> instance to be associated with * and used by this <tt>ZrtpControlImpl</tt> instance */ protected ZRTPTransformEngine createTransformEngine() { ZRTPTransformEngine transformEngine = new ZRTPTransformEngine(); // NOTE: set paranoid mode before initializing // zrtpEngine.setParanoidMode(paranoidMode); transformEngine.initialize( "GNUZRTP4J.zid", false, ZrtpConfigureUtils.getZrtpConfiguration()); transformEngine.setUserCallback(new SecurityEventManager(this)); return transformEngine; } /* * (non-Javadoc) * * @see * net.java.sip.communicator.service.neomedia.ZrtpControl#isSecurityVerified * () */ public boolean isSecurityVerified() { return getTransformEngine().getUserCallback().isSecurityVerified(); } /** * Returns false, ZRTP exchanges is keys over the media path. * * @return false */ public boolean requiresSecureSignalingTransport() { return false; } /** * Sets the <tt>RTPConnector</tt> which is to use or uses this ZRTP engine. * * @param connector the <tt>RTPConnector</tt> which is to use or uses this * ZRTP engine */ public void setConnector(AbstractRTPConnector connector) { zrtpConnector = connector; } /** * When in multistream mode, enables the master session. * * @param masterSession whether current control, controls the master session */ @Override public void setMasterSession(boolean masterSession) { // by default its not master, change only if set to be master // sometimes (jingle) streams are re-initing and // we must reuse old value (true) event that false is submitted if(masterSession) this.masterSession = masterSession; } /** * Start multi-stream ZRTP sessions. After the ZRTP Master (DH) session * reached secure state the SCCallback calls this method to start the * multi-stream ZRTP sessions. Enable auto-start mode (auto-sensing) to the * engine. * * @param master master SRTP data */ @Override public void setMultistream(SrtpControl master) { if(master == null || master == this) return; if(!(master instanceof ZrtpControlImpl)) throw new IllegalArgumentException("master is no ZRTP control"); ZrtpControlImpl zm = (ZrtpControlImpl)master; ZRTPTransformEngine engine = getTransformEngine(); engine.setMultiStrParams(zm.getTransformEngine().getMultiStrParams()); engine.setEnableZrtp(true); engine.getUserCallback().setMasterEventManager( zm.getTransformEngine().getUserCallback()); } /** * Sets the SAS verification * * @param verified the new SAS verification status */ public void setSASVerification(boolean verified) { ZRTPTransformEngine engine = getTransformEngine(); if (verified) engine.SASVerified(); else engine.resetSASVerified(); } /** * Starts and enables zrtp in the stream holding this control. * @param mediaType the media type of the stream this control controls. */ public void start(MediaType mediaType) { boolean zrtpAutoStart; // ZRTP engine initialization ZRTPTransformEngine engine = getTransformEngine(); // Create security user callback for each peer. SecurityEventManager securityEventManager = engine.getUserCallback(); // Decide if this will become the ZRTP Master session: // - Statement: audio media session will be started before video // media session // - if no other audio session was started before then this will // become // ZRTP Master session // - only the ZRTP master sessions start in "auto-sensing" mode // to immediately catch ZRTP communication from other client // - after the master session has completed its key negotiation // it will start other media sessions (see SCCallback) if (masterSession) { zrtpAutoStart = true; // we know that audio is considered as master for zrtp securityEventManager.setSessionType(mediaType); } else { // check whether video was not already started // it may happen when using multistreams, audio has inited // and started video // initially engine has value enableZrtp = false zrtpAutoStart = transformEngine.isEnableZrtp(); securityEventManager.setSessionType(mediaType); } engine.setConnector(zrtpConnector); securityEventManager.setSrtpListener(getSrtpListener()); // tells the engine whether to autostart(enable) // zrtp communication, if false it just passes packets without // transformation engine.setEnableZrtp(zrtpAutoStart); engine.sendInfo( ZrtpCodes.MessageSeverity.Info, EnumSet.of(ZRTPCustomInfoCodes.ZRTPEnabledByDefault)); } }
HappyYang/libjitsi
src/org/jitsi/impl/neomedia/transform/zrtp/ZrtpControlImpl.java
Java
apache-2.0
11,256
/* * L.GridLayer is used as base class for grid-like layers like TileLayer. */ L.GridLayer = L.Layer.extend({ options: { pane: 'tilePane', tileSize: 256, opacity: 1, updateWhenIdle: L.Browser.mobile, updateInterval: 200, attribution: null, zIndex: null, bounds: null, minZoom: 0 // maxZoom: <Number> }, initialize: function (options) { options = L.setOptions(this, options); }, onAdd: function () { this._initContainer(); this._levels = {}; this._tiles = {}; this._resetView(); this._update(); }, beforeAdd: function (map) { map._addZoomLimit(this); }, onRemove: function (map) { L.DomUtil.remove(this._container); map._removeZoomLimit(this); this._container = null; this._tileZoom = null; }, bringToFront: function () { if (this._map) { L.DomUtil.toFront(this._container); this._setAutoZIndex(Math.max); } return this; }, bringToBack: function () { if (this._map) { L.DomUtil.toBack(this._container); this._setAutoZIndex(Math.min); } return this; }, getAttribution: function () { return this.options.attribution; }, getContainer: function () { return this._container; }, setOpacity: function (opacity) { this.options.opacity = opacity; this._updateOpacity(); return this; }, setZIndex: function (zIndex) { this.options.zIndex = zIndex; this._updateZIndex(); return this; }, isLoading: function () { return this._loading; }, redraw: function () { if (this._map) { this._removeAllTiles(); this._update(); } return this; }, getEvents: function () { var events = { viewreset: this._resetAll, zoom: this._resetView, moveend: this._onMoveEnd }; if (!this.options.updateWhenIdle) { // update tiles on move, but not more often than once per given interval if (!this._onMove) { this._onMove = L.Util.throttle(this._onMoveEnd, this.options.updateInterval, this); } events.move = this._onMove; } if (this._zoomAnimated) { events.zoomanim = this._animateZoom; } return events; }, createTile: function () { return document.createElement('div'); }, getTileSize: function () { var s = this.options.tileSize; return s instanceof L.Point ? s : new L.Point(s, s); }, _updateZIndex: function () { if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) { this._container.style.zIndex = this.options.zIndex; } }, _setAutoZIndex: function (compare) { // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back) var layers = this.getPane().children, edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min for (var i = 0, len = layers.length, zIndex; i < len; i++) { zIndex = layers[i].style.zIndex; if (layers[i] !== this._container && zIndex) { edgeZIndex = compare(edgeZIndex, +zIndex); } } if (isFinite(edgeZIndex)) { this.options.zIndex = edgeZIndex + compare(-1, 1); this._updateZIndex(); } }, _updateOpacity: function () { if (!this._map) { return; } // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles if (L.Browser.ielt9 || !this._map._fadeAnimated) { return; } L.DomUtil.setOpacity(this._container, this.options.opacity); var now = +new Date(), nextFrame = false, willPrune = false; for (var key in this._tiles) { var tile = this._tiles[key]; if (!tile.current || !tile.loaded) { continue; } var fade = Math.min(1, (now - tile.loaded) / 200); L.DomUtil.setOpacity(tile.el, fade); if (fade < 1) { nextFrame = true; } else { if (tile.active) { willPrune = true; } tile.active = true; } } if (willPrune) { this._pruneTiles(); } if (nextFrame) { L.Util.cancelAnimFrame(this._fadeFrame); this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this); } }, _initContainer: function () { if (this._container) { return; } this._container = L.DomUtil.create('div', 'leaflet-layer'); this._updateZIndex(); if (this.options.opacity < 1) { this._updateOpacity(); } this.getPane().appendChild(this._container); }, _updateLevels: function () { var zoom = this._tileZoom, maxZoom = this.options.maxZoom; for (var z in this._levels) { if (this._levels[z].el.children.length || z === zoom) { this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z); } else { L.DomUtil.remove(this._levels[z].el); delete this._levels[z]; } } var level = this._levels[zoom], map = this._map; if (!level) { level = this._levels[zoom] = {}; level.el = L.DomUtil.create('div', 'leaflet-tile-container leaflet-zoom-animated', this._container); level.el.style.zIndex = maxZoom; level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round(); level.zoom = zoom; this._setZoomTransform(level, map.getCenter(), map.getZoom()); // force the browser to consider the newly added element for transition L.Util.falseFn(level.el.offsetWidth); } this._level = level; return level; }, _pruneTiles: function () { var key, tile; var zoom = this._map.getZoom(); if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { return this._removeAllTiles(); } for (key in this._tiles) { tile = this._tiles[key]; tile.retain = tile.current; } for (key in this._tiles) { tile = this._tiles[key]; if (tile.current && !tile.active) { var coords = tile.coords; if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) { this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2); } } } for (key in this._tiles) { if (!this._tiles[key].retain) { this._removeTile(key); } } }, _removeAllTiles: function () { for (var key in this._tiles) { this._removeTile(key); } }, _resetAll: function () { for (var z in this._levels) { L.DomUtil.remove(this._levels[z].el); delete this._levels[z]; } this._removeAllTiles(); this._tileZoom = null; this._resetView(); }, _retainParent: function (x, y, z, minZoom) { var x2 = Math.floor(x / 2), y2 = Math.floor(y / 2), z2 = z - 1; var key = x2 + ':' + y2 + ':' + z2, tile = this._tiles[key]; if (tile && tile.active) { tile.retain = true; return true; } else if (tile && tile.loaded) { tile.retain = true; } if (z2 > minZoom) { return this._retainParent(x2, y2, z2, minZoom); } return false; }, _retainChildren: function (x, y, z, maxZoom) { for (var i = 2 * x; i < 2 * x + 2; i++) { for (var j = 2 * y; j < 2 * y + 2; j++) { var key = i + ':' + j + ':' + (z + 1), tile = this._tiles[key]; if (tile && tile.active) { tile.retain = true; continue; } else if (tile && tile.loaded) { tile.retain = true; } if (z + 1 < maxZoom) { this._retainChildren(i, j, z + 1, maxZoom); } } } }, _resetView: function (e) { var pinch = e && e.pinch; this._setView(this._map.getCenter(), this._map.getZoom(), pinch, pinch); }, _animateZoom: function (e) { this._setView(e.center, e.zoom, true, e.noUpdate); }, _setView: function (center, zoom, noPrune, noUpdate) { var tileZoom = Math.round(zoom), tileZoomChanged = this._tileZoom !== tileZoom; if (!noUpdate && tileZoomChanged) { if (this._abortLoading) { this._abortLoading(); } this._tileZoom = tileZoom; this._updateLevels(); this._resetGrid(); if (!L.Browser.mobileWebkit) { this._update(center, tileZoom); } if (!noPrune) { this._pruneTiles(); } } this._setZoomTransforms(center, zoom); }, _setZoomTransforms: function (center, zoom) { for (var i in this._levels) { this._setZoomTransform(this._levels[i], center, zoom); } }, _setZoomTransform: function (level, center, zoom) { var scale = this._map.getZoomScale(zoom, level.zoom), translate = level.origin.multiplyBy(scale) .subtract(this._map._getNewPixelOrigin(center, zoom)).round(); if (L.Browser.any3d) { L.DomUtil.setTransform(level.el, translate, scale); } else { L.DomUtil.setPosition(level.el, translate); } }, _resetGrid: function () { var map = this._map, crs = map.options.crs, tileSize = this._tileSize = this.getTileSize(), tileZoom = this._tileZoom; var bounds = this._map.getPixelWorldBounds(this._tileZoom); if (bounds) { this._globalTileRange = this._pxBoundsToTileRange(bounds); } this._wrapX = crs.wrapLng && [ Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x), Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y) ]; this._wrapY = crs.wrapLat && [ Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x), Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y) ]; }, _onMoveEnd: function () { if (!this._map) { return; } this._update(); this._pruneTiles(); }, _getTiledPixelBounds: function (center, zoom, tileZoom) { var map = this._map; var scale = map.getZoomScale(zoom, tileZoom), pixelCenter = map.project(center, tileZoom).floor(), halfSize = map.getSize().divideBy(scale * 2); return new L.Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize)); }, _update: function (center, zoom) { var map = this._map; if (!map) { return; } if (center === undefined) { center = map.getCenter(); } if (zoom === undefined) { zoom = map.getZoom(); } var tileZoom = Math.round(zoom); if (tileZoom > this.options.maxZoom || tileZoom < this.options.minZoom) { return; } var pixelBounds = this._getTiledPixelBounds(center, zoom, tileZoom); var tileRange = this._pxBoundsToTileRange(pixelBounds), tileCenter = tileRange.getCenter(), queue = []; for (var key in this._tiles) { this._tiles[key].current = false; } // create a queue of coordinates to load tiles from for (var j = tileRange.min.y; j <= tileRange.max.y; j++) { for (var i = tileRange.min.x; i <= tileRange.max.x; i++) { var coords = new L.Point(i, j); coords.z = tileZoom; if (!this._isValidTile(coords)) { continue; } var tile = this._tiles[this._tileCoordsToKey(coords)]; if (tile) { tile.current = true; } else { queue.push(coords); } } } // sort tile queue to load tiles in order of their distance to center queue.sort(function (a, b) { return a.distanceTo(tileCenter) - b.distanceTo(tileCenter); }); if (queue.length !== 0) { // if its the first batch of tiles to load if (!this._loading) { this._loading = true; this.fire('loading'); } // create DOM fragment to append tiles in one batch var fragment = document.createDocumentFragment(); for (i = 0; i < queue.length; i++) { this._addTile(queue[i], fragment); } this._level.el.appendChild(fragment); } }, _isValidTile: function (coords) { var crs = this._map.options.crs; if (!crs.infinite) { // don't load tile if it's out of bounds and not wrapped var bounds = this._globalTileRange; if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) || (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; } } if (!this.options.bounds) { return true; } // don't load tile if it doesn't intersect the bounds in options var tileBounds = this._tileCoordsToBounds(coords); return L.latLngBounds(this.options.bounds).overlaps(tileBounds); }, _keyToBounds: function (key) { return this._tileCoordsToBounds(this._keyToTileCoords(key)); }, // converts tile coordinates to its geographical bounds _tileCoordsToBounds: function (coords) { var map = this._map, tileSize = this.getTileSize(), nwPoint = coords.scaleBy(tileSize), sePoint = nwPoint.add(tileSize), nw = map.wrapLatLng(map.unproject(nwPoint, coords.z)), se = map.wrapLatLng(map.unproject(sePoint, coords.z)); return new L.LatLngBounds(nw, se); }, // converts tile coordinates to key for the tile cache _tileCoordsToKey: function (coords) { return coords.x + ':' + coords.y + ':' + coords.z; }, // converts tile cache key to coordinates _keyToTileCoords: function (key) { var k = key.split(':'), coords = new L.Point(+k[0], +k[1]); coords.z = +k[2]; return coords; }, _removeTile: function (key) { var tile = this._tiles[key]; if (!tile) { return; } L.DomUtil.remove(tile.el); delete this._tiles[key]; this.fire('tileunload', { tile: tile.el, coords: this._keyToTileCoords(key) }); }, _initTile: function (tile) { L.DomUtil.addClass(tile, 'leaflet-tile'); var tileSize = this.getTileSize(); tile.style.width = tileSize.x + 'px'; tile.style.height = tileSize.y + 'px'; tile.onselectstart = L.Util.falseFn; tile.onmousemove = L.Util.falseFn; // update opacity on tiles in IE7-8 because of filter inheritance problems if (L.Browser.ielt9 && this.options.opacity < 1) { L.DomUtil.setOpacity(tile, this.options.opacity); } // without this hack, tiles disappear after zoom on Chrome for Android // https://github.com/Leaflet/Leaflet/issues/2078 if (L.Browser.android && !L.Browser.android23) { tile.style.WebkitBackfaceVisibility = 'hidden'; } }, _addTile: function (coords, container) { var tilePos = this._getTilePos(coords), key = this._tileCoordsToKey(coords); var tile = this.createTile(this._wrapCoords(coords), L.bind(this._tileReady, this, coords)); this._initTile(tile); // if createTile is defined with a second argument ("done" callback), // we know that tile is async and will be ready later; otherwise if (this.createTile.length < 2) { // mark tile as ready, but delay one frame for opacity animation to happen setTimeout(L.bind(this._tileReady, this, coords, null, tile), 0); } L.DomUtil.setPosition(tile, tilePos); // save tile in cache this._tiles[key] = { el: tile, coords: coords, current: true }; container.appendChild(tile); this.fire('tileloadstart', { tile: tile, coords: coords }); }, _tileReady: function (coords, err, tile) { if (!this._map) { return; } if (err) { this.fire('tileerror', { error: err, tile: tile, coords: coords }); } var key = this._tileCoordsToKey(coords); tile = this._tiles[key]; if (!tile) { return; } tile.loaded = +new Date(); if (this._map._fadeAnimated) { L.DomUtil.setOpacity(tile.el, 0); L.Util.cancelAnimFrame(this._fadeFrame); this._fadeFrame = L.Util.requestAnimFrame(this._updateOpacity, this); } else { tile.active = true; this._pruneTiles(); } L.DomUtil.addClass(tile.el, 'leaflet-tile-loaded'); this.fire('tileload', { tile: tile.el, coords: coords }); if (this._noTilesToLoad()) { this._loading = false; this.fire('load'); } }, _getTilePos: function (coords) { return coords.scaleBy(this.getTileSize()).subtract(this._level.origin); }, _wrapCoords: function (coords) { var newCoords = new L.Point( this._wrapX ? L.Util.wrapNum(coords.x, this._wrapX) : coords.x, this._wrapY ? L.Util.wrapNum(coords.y, this._wrapY) : coords.y); newCoords.z = coords.z; return newCoords; }, _pxBoundsToTileRange: function (bounds) { var tileSize = this.getTileSize(); return new L.Bounds( bounds.min.unscaleBy(tileSize).floor(), bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1])); }, _noTilesToLoad: function () { for (var key in this._tiles) { if (!this._tiles[key].loaded) { return false; } } return true; } }); L.gridLayer = function (options) { return new L.GridLayer(options); };
AndBicScadMedia/Leaflet
src/layer/tile/GridLayer.js
JavaScript
bsd-2-clause
15,707
class Mdp < Formula desc "Command-line based markdown presentation tool" homepage "https://github.com/visit1985/mdp" url "https://github.com/visit1985/mdp/archive/1.0.9.tar.gz" sha256 "893e13a9a61a89bacf29ee141bd9f6e8935710323701e3d36584a4bb90e1372d" head "https://github.com/visit1985/mdp.git" bottle do cellar :any_skip_relocation sha256 "6771747a2b8bc5d42770188f99060be438cb9d13b5371e14fbf9a147155c62ea" => :sierra sha256 "e109dc3235ce7c8525b141d062c8f5483b5fe2e47d12c80f3fce5e74b16d766f" => :el_capitan sha256 "9b47182af992b02773445de59b2e9dcb75d18ac72a229d36f019de9847d2f4c1" => :yosemite end def install system "make" system "make", "install", "PREFIX=#{prefix}" pkgshare.install "sample.md" end test do assert_match version.to_s, shell_output("#{bin}/mdp -v") end end
kuahyeow/homebrew-core
Formula/mdp.rb
Ruby
bsd-2-clause
832
<?php /** * @package sapphire * @subpackage tests */ class DataObjectTest extends SapphireTest { static $fixture_file = 'sapphire/tests/DataObjectTest.yml'; protected $extraDataObjects = array( 'DataObjectTest_Team', 'DataObjectTest_Fixture', 'DataObjectTest_SubTeam', 'OtherSubclassWithSameField', 'DataObjectTest_FieldlessTable', 'DataObjectTest_FieldlessSubTable', 'DataObjectTest_ValidatedObject', 'DataObjectTest_Player', 'DataObjectSetTest_TeamComment' ); function testDataIntegrityWhenTwoSubclassesHaveSameField() { // Save data into DataObjectTest_SubTeam.SubclassDatabaseField $obj = new DataObjectTest_SubTeam(); $obj->SubclassDatabaseField = "obj-SubTeam"; $obj->write(); // Change the class $obj->ClassName = 'OtherSubclassWithSameField'; $obj->write(); $obj->flushCache(); // Re-fetch from the database and confirm that the data is sourced from // OtherSubclassWithSameField.SubclassDatabaseField $obj = DataObject::get_by_id('DataObjectTest_Team', $obj->ID); $this->assertNull($obj->SubclassDatabaseField); // Confirm that save the object in the other direction. $obj->SubclassDatabaseField = 'obj-Other'; $obj->write(); $obj->ClassName = 'DataObjectTest_SubTeam'; $obj->write(); $obj->flushCache(); // If we restore the class, the old value has been lying dormant and will be available again. // NOTE: This behaviour is volatile; we may change this in the future to clear fields that // are no longer relevant when changing ClassName $obj = DataObject::get_by_id('DataObjectTest_Team', $obj->ID); $this->assertEquals('obj-SubTeam', $obj->SubclassDatabaseField); } /** * Test deletion of DataObjects * - Deleting using delete() on the DataObject * - Deleting using DataObject::delete_by_id() */ function testDelete() { // Test deleting using delete() on the DataObject // Get the first page $page = $this->objFromFixture('Page', 'page1'); $pageID = $page->ID; // Check the page exists before deleting $this->assertTrue(is_object($page) && $page->exists()); // Delete the page $page->delete(); // Check that page does not exist after deleting $page = DataObject::get_by_id('Page', $pageID); $this->assertTrue(!$page || !$page->exists()); // Test deleting using DataObject::delete_by_id() // Get the second page $page2 = $this->objFromFixture('Page', 'page2'); $page2ID = $page2->ID; // Check the page exists before deleting $this->assertTrue(is_object($page2) && $page2->exists()); // Delete the page DataObject::delete_by_id('Page', $page2->ID); // Check that page does not exist after deleting $page2 = DataObject::get_by_id('Page', $page2ID); $this->assertTrue(!$page2 || !$page2->exists()); } /** * Test methods that get DataObjects * - DataObject::get() * - All records of a DataObject * - Filtering * - Sorting * - Joins * - Limit * - Container class * - DataObject::get_by_id() * - DataObject::get_one() * - With and without caching * - With and without ordering */ function testGet() { // Test getting all records of a DataObject $comments = DataObject::get('PageComment'); $this->assertEquals(8, $comments->Count()); // Test WHERE clause $comments = DataObject::get('PageComment', "\"Name\"='Bob'"); $this->assertEquals(2, $comments->Count()); foreach($comments as $comment) { $this->assertEquals('Bob', $comment->Name); } // Test sorting $comments = DataObject::get('PageComment', '', '"Name" ASC'); $this->assertEquals(8, $comments->Count()); $this->assertEquals('Bob', $comments->First()->Name); $comments = DataObject::get('PageComment', '', '"Name" DESC'); $this->assertEquals(8, $comments->Count()); $this->assertEquals('Joe', $comments->First()->Name); // Test join $comments = DataObject::get('PageComment', "\"SiteTree\".\"Title\"='First Page'", '', 'INNER JOIN "SiteTree" ON "PageComment"."ParentID" = "SiteTree"."ID"'); $this->assertEquals(2, $comments->Count()); $this->assertEquals('Bob', $comments->First()->Name); $this->assertEquals('Bob', $comments->Last()->Name); // Test limit $comments = DataObject::get('PageComment', '', '"Name" ASC', '', '1,2'); $this->assertEquals(2, $comments->Count()); $this->assertEquals('Bob', $comments->First()->Name); $this->assertEquals('Dean', $comments->Last()->Name); // Test container class $comments = DataObject::get('PageComment', '', '', '', '', 'DataObjectSet'); $this->assertEquals('DataObjectSet', get_class($comments)); $comments = DataObject::get('PageComment', '', '', '', '', 'ComponentSet'); $this->assertEquals('ComponentSet', get_class($comments)); // Test get_by_id() $homepageID = $this->idFromFixture('Page', 'home'); $page = DataObject::get_by_id('Page', $homepageID); $this->assertEquals('Home', $page->Title); // Test get_one() without caching $comment1 = DataObject::get_one('PageComment', "\"Name\"='Joe'", false); $comment1->Comment = "Something Else"; $comment2 = DataObject::get_one('PageComment', "\"Name\"='Joe'", false); $this->assertNotEquals($comment1->Comment, $comment2->Comment); // Test get_one() with caching $comment1 = DataObject::get_one('PageComment', "\"Name\"='Jane'", true); $comment1->Comment = "Something Else"; $comment2 = DataObject::get_one('PageComment', "\"Name\"='Jane'", true); $this->assertEquals((string)$comment1->Comment, (string)$comment2->Comment); // Test get_one() with order by without caching $comment = DataObject::get_one('PageComment', '', false, '"Name" ASC'); $this->assertEquals('Bob', $comment->Name); $comment = DataObject::get_one('PageComment', '', false, '"Name" DESC'); $this->assertEquals('Joe', $comment->Name); // Test get_one() with order by with caching $comment = DataObject::get_one('PageComment', '', true, '"Name" ASC'); $this->assertEquals('Bob', $comment->Name); $comment = DataObject::get_one('PageComment', '', true, '"Name" DESC'); $this->assertEquals('Joe', $comment->Name); } /** * Test writing of database columns which don't correlate to a DBField, * e.g. all relation fields on has_one/has_many like "ParentID". * */ function testWritePropertyWithoutDBField() { $page = $this->objFromFixture('Page', 'page1'); $page->ParentID = 99; $page->write(); // reload the page from the database $savedPage = DataObject::get_by_id('Page', $page->ID); $this->assertTrue($savedPage->ParentID == 99); } /** * Test has many relationships * - Test getComponents() gets the ComponentSet of the other side of the relation * - Test the IDs on the DataObjects are set correctly */ function testHasManyRelationships() { $page = $this->objFromFixture('Page', 'home'); // Test getComponents() gets the ComponentSet of the other side of the relation $this->assertTrue($page->getComponents('Comments')->Count() == 2); // Test the IDs on the DataObjects are set correctly foreach($page->getComponents('Comments') as $comment) { $this->assertTrue($comment->ParentID == $page->ID); } } function testHasOneRelationship() { $team1 = $this->objFromFixture('DataObjectTest_Team', 'team1'); $player1 = $this->objFromFixture('DataObjectTest_Player', 'player1'); // Add a captain to team 1 $team1->setField('CaptainID', $player1->ID); $team1->write(); $this->assertEquals($player1->ID, $team1->Captain()->ID, 'The captain exists for team 1'); $this->assertEquals($player1->ID, $team1->getComponent('Captain')->ID, 'The captain exists through the component getter'); $this->assertEquals($team1->Captain()->FirstName, 'Player 1', 'Player 1 is the captain'); $this->assertEquals($team1->getComponent('Captain')->FirstName, 'Player 1', 'Player 1 is the captain'); } /** * @todo Test removeMany() and addMany() on $many_many relationships */ function testManyManyRelationships() { $player1 = $this->objFromFixture('DataObjectTest_Player', 'player1'); $player2 = $this->objFromFixture('DataObjectTest_Player', 'player2'); $team1 = $this->objFromFixture('DataObjectTest_Team', 'team1'); $team2 = $this->objFromFixture('DataObjectTest_Team', 'team2'); // Test adding single DataObject by reference $player1->Teams()->add($team1); $player1->flushCache(); $compareTeams = new ComponentSet($team1); $this->assertEquals( $player1->Teams()->column('ID'), $compareTeams->column('ID'), "Adding single record as DataObject to many_many" ); // test removing single DataObject by reference $player1->Teams()->remove($team1); $player1->flushCache(); $compareTeams = new ComponentSet(); $this->assertEquals( $player1->Teams()->column('ID'), $compareTeams->column('ID'), "Removing single record as DataObject from many_many" ); // test adding single DataObject by ID $player1->Teams()->add($team1->ID); $player1->flushCache(); $compareTeams = new ComponentSet($team1); $this->assertEquals( $player1->Teams()->column('ID'), $compareTeams->column('ID'), "Adding single record as ID to many_many" ); // test removing single DataObject by ID $player1->Teams()->remove($team1->ID); $player1->flushCache(); $compareTeams = new ComponentSet(); $this->assertEquals( $player1->Teams()->column('ID'), $compareTeams->column('ID'), "Removing single record as ID from many_many" ); } /** * @todo Extend type change tests (e.g. '0'==NULL) */ function testChangedFields() { $page = $this->objFromFixture('Page', 'home'); $page->Title = 'Home-Changed'; $page->ShowInMenus = true; $this->assertEquals( $page->getChangedFields(false, 1), array( 'Title' => array( 'before' => 'Home', 'after' => 'Home-Changed', 'level' => 2 ), 'ShowInMenus' => array( 'before' => 1, 'after' => true, 'level' => 1 ) ), 'Changed fields are correctly detected with strict type changes (level=1)' ); $this->assertEquals( $page->getChangedFields(false, 2), array( 'Title' => array( 'before'=>'Home', 'after'=>'Home-Changed', 'level' => 2 ) ), 'Changed fields are correctly detected while ignoring type changes (level=2)' ); $newPage = new Page(); $newPage->Title = "New Page Title"; $this->assertEquals( $newPage->getChangedFields(false, 2), array( 'Title' => array( 'before' => null, 'after' => 'New Page Title', 'level' => 2 ) ), 'Initialised fields are correctly detected as full changes' ); } function testIsChanged() { $page = $this->objFromFixture('Page', 'home'); $page->Title = 'Home-Changed'; $page->ShowInMenus = true; // type change only, database stores "1" $this->assertTrue($page->isChanged('Title', 1)); $this->assertTrue($page->isChanged('Title', 2)); $this->assertTrue($page->isChanged('ShowInMenus', 1)); $this->assertFalse($page->isChanged('ShowInMenus', 2)); $this->assertFalse($page->isChanged('Content', 1)); $this->assertFalse($page->isChanged('Content', 2)); $newPage = new Page(); $newPage->Title = "New Page Title"; $this->assertTrue($newPage->isChanged('Title', 1)); $this->assertTrue($newPage->isChanged('Title', 2)); $this->assertFalse($newPage->isChanged('Content', 1)); $this->assertFalse($newPage->isChanged('Content', 2)); $newPage->write(); $this->assertFalse($newPage->isChanged('Title', 1)); $this->assertFalse($newPage->isChanged('Title', 2)); $this->assertFalse($newPage->isChanged('Content', 1)); $this->assertFalse($newPage->isChanged('Content', 2)); $page = $this->objFromFixture('Page', 'home'); $page->Title = null; $this->assertTrue($page->isChanged('Title', 1)); $this->assertTrue($page->isChanged('Title', 2)); /* Test when there's not field provided */ $page = $this->objFromFixture('Page', 'home'); $page->Title = "New Page Title"; $this->assertTrue($page->isChanged()); $page->write(); $this->assertFalse($page->isChanged()); } function testRandomSort() { /* If we perforn the same regularly sorted query twice, it should return the same results */ $itemsA = DataObject::get("PageComment", "", "ID"); foreach($itemsA as $item) $keysA[] = $item->ID; $itemsB = DataObject::get("PageComment", "", "ID"); foreach($itemsB as $item) $keysB[] = $item->ID; $this->assertEquals($keysA, $keysB); /* If we perform the same random query twice, it shouldn't return the same results */ $itemsA = DataObject::get("PageComment", "", DB::getConn()->random()); foreach($itemsA as $item) $keysA[] = $item->ID; $itemsB = DataObject::get("PageComment", "", DB::getConn()->random()); foreach($itemsB as $item) $keysB[] = $item->ID; $this->assertNotEquals($keysA, $keysB); } function testWriteSavesToHasOneRelations() { /* DataObject::write() should save to a has_one relationship if you set a field called (relname)ID */ $team = new DataObjectTest_Team(); $captainID = $this->idFromFixture('DataObjectTest_Player', 'player1'); $team->CaptainID = $captainID; $team->write(); $this->assertEquals($captainID, DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()); /* After giving it a value, you should also be able to set it back to null */ $team->CaptainID = ''; $team->write(); $this->assertEquals(0, DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()); /* You should also be able to save a blank to it when it's first created */ $team = new DataObjectTest_Team(); $team->CaptainID = ''; $team->write(); $this->assertEquals(0, DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()); /* Ditto for existing records without a value */ $existingTeam = $this->objFromFixture('DataObjectTest_Team', 'team1'); $existingTeam->CaptainID = ''; $existingTeam->write(); $this->assertEquals(0, DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $existingTeam->ID")->value()); } function testCanAccessHasOneObjectsAsMethods() { /* If you have a has_one relation 'Captain' on $obj, and you set the $obj->CaptainID = (ID), then the object itself should * be accessible as $obj->Captain() */ $team = $this->objFromFixture('DataObjectTest_Team', 'team1'); $captainID = $this->idFromFixture('DataObjectTest_Player', 'captain1'); $team->CaptainID = $captainID; $this->assertNotNull($team->Captain()); $this->assertEquals($captainID, $team->Captain()->ID); } function testFieldNamesThatMatchMethodNamesWork() { /* Check that a field name that corresponds to a method on DataObject will still work */ $obj = new DataObjectTest_Fixture(); $obj->Data = "value1"; $obj->DbObject = "value2"; $obj->Duplicate = "value3"; $obj->write(); $this->assertNotNull($obj->ID); $this->assertEquals('value1', DB::query("SELECT \"Data\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()); $this->assertEquals('value2', DB::query("SELECT \"DbObject\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()); $this->assertEquals('value3', DB::query("SELECT \"Duplicate\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()); } /** * @todo Re-enable all test cases for field existence after behaviour has been fixed */ function testFieldExistence() { $teamInstance = $this->objFromFixture('DataObjectTest_Team', 'team1'); $teamSingleton = singleton('DataObjectTest_Team'); $subteamInstance = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1'); $subteamSingleton = singleton('DataObjectTest_SubTeam'); /* hasField() singleton checks */ $this->assertTrue($teamSingleton->hasField('ID'), 'hasField() finds built-in fields in singletons'); $this->assertTrue($teamSingleton->hasField('Title'), 'hasField() finds custom fields in singletons'); /* hasField() instance checks */ $this->assertFalse($teamInstance->hasField('NonExistingField'), 'hasField() doesnt find non-existing fields in instances'); $this->assertTrue($teamInstance->hasField('ID'), 'hasField() finds built-in fields in instances'); $this->assertTrue($teamInstance->hasField('Created'), 'hasField() finds built-in fields in instances'); $this->assertTrue($teamInstance->hasField('DatabaseField'), 'hasField() finds custom fields in instances'); //$this->assertFalse($teamInstance->hasField('SubclassDatabaseField'), 'hasField() doesnt find subclass fields in parentclass instances'); $this->assertTrue($teamInstance->hasField('DynamicField'), 'hasField() finds dynamic getters in instances'); $this->assertTrue($teamInstance->hasField('HasOneRelationshipID'), 'hasField() finds foreign keys in instances'); $this->assertTrue($teamInstance->hasField('DecoratedDatabaseField'), 'hasField() finds decorated fields in instances'); $this->assertTrue($teamInstance->hasField('DecoratedHasOneRelationshipID'), 'hasField() finds decorated foreign keys in instances'); //$this->assertTrue($teamInstance->hasField('DecoratedDynamicField'), 'hasField() includes decorated dynamic getters in instances'); /* hasField() subclass checks */ $this->assertTrue($subteamInstance->hasField('ID'), 'hasField() finds built-in fields in subclass instances'); $this->assertTrue($subteamInstance->hasField('Created'), 'hasField() finds built-in fields in subclass instances'); $this->assertTrue($subteamInstance->hasField('DatabaseField'), 'hasField() finds custom fields in subclass instances'); $this->assertTrue($subteamInstance->hasField('SubclassDatabaseField'), 'hasField() finds custom fields in subclass instances'); $this->assertTrue($subteamInstance->hasField('DynamicField'), 'hasField() finds dynamic getters in subclass instances'); $this->assertTrue($subteamInstance->hasField('HasOneRelationshipID'), 'hasField() finds foreign keys in subclass instances'); $this->assertTrue($subteamInstance->hasField('DecoratedDatabaseField'), 'hasField() finds decorated fields in subclass instances'); $this->assertTrue($subteamInstance->hasField('DecoratedHasOneRelationshipID'), 'hasField() finds decorated foreign keys in subclass instances'); /* hasDatabaseField() singleton checks */ //$this->assertTrue($teamSingleton->hasDatabaseField('ID'), 'hasDatabaseField() finds built-in fields in singletons'); $this->assertTrue($teamSingleton->hasDatabaseField('Title'), 'hasDatabaseField() finds custom fields in singletons'); /* hasDatabaseField() instance checks */ $this->assertFalse($teamInstance->hasDatabaseField('NonExistingField'), 'hasDatabaseField() doesnt find non-existing fields in instances'); //$this->assertTrue($teamInstance->hasDatabaseField('ID'), 'hasDatabaseField() finds built-in fields in instances'); $this->assertTrue($teamInstance->hasDatabaseField('Created'), 'hasDatabaseField() finds built-in fields in instances'); $this->assertTrue($teamInstance->hasDatabaseField('DatabaseField'), 'hasDatabaseField() finds custom fields in instances'); $this->assertFalse($teamInstance->hasDatabaseField('SubclassDatabaseField'), 'hasDatabaseField() doesnt find subclass fields in parentclass instances'); //$this->assertFalse($teamInstance->hasDatabaseField('DynamicField'), 'hasDatabaseField() doesnt dynamic getters in instances'); $this->assertTrue($teamInstance->hasDatabaseField('HasOneRelationshipID'), 'hasDatabaseField() finds foreign keys in instances'); $this->assertTrue($teamInstance->hasDatabaseField('DecoratedDatabaseField'), 'hasDatabaseField() finds decorated fields in instances'); $this->assertTrue($teamInstance->hasDatabaseField('DecoratedHasOneRelationshipID'), 'hasDatabaseField() finds decorated foreign keys in instances'); $this->assertFalse($teamInstance->hasDatabaseField('DecoratedDynamicField'), 'hasDatabaseField() doesnt include decorated dynamic getters in instances'); /* hasDatabaseField() subclass checks */ $this->assertTrue($subteamInstance->hasField('DatabaseField'), 'hasField() finds custom fields in subclass instances'); $this->assertTrue($subteamInstance->hasField('SubclassDatabaseField'), 'hasField() finds custom fields in subclass instances'); } /** * @todo Re-enable all test cases for field inheritance aggregation after behaviour has been fixed */ function testFieldInheritance() { $teamInstance = $this->objFromFixture('DataObjectTest_Team', 'team1'); $subteamInstance = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1'); $this->assertEquals( array_keys($teamInstance->inheritedDatabaseFields()), array( //'ID', //'ClassName', //'Created', //'LastEdited', 'Title', 'DatabaseField', 'DecoratedDatabaseField', 'CaptainID', 'HasOneRelationshipID', 'DecoratedHasOneRelationshipID' ), 'inheritedDatabaseFields() contains all fields defined on instance, including base fields, decorated fields and foreign keys' ); $this->assertEquals( array_keys(DataObject::database_fields('DataObjectTest_Team')), array( //'ID', 'ClassName', 'Created', 'LastEdited', 'Title', 'DatabaseField', 'DecoratedDatabaseField', 'CaptainID', 'HasOneRelationshipID', 'DecoratedHasOneRelationshipID' ), 'databaseFields() contains only fields defined on instance, including base fields, decorated fields and foreign keys' ); $this->assertEquals( array_keys($subteamInstance->inheritedDatabaseFields()), array( //'ID', //'ClassName', //'Created', //'LastEdited', 'SubclassDatabaseField', 'Title', 'DatabaseField', 'DecoratedDatabaseField', 'CaptainID', 'HasOneRelationshipID', 'DecoratedHasOneRelationshipID', ), 'inheritedDatabaseFields() on subclass contains all fields defined on instance, including base fields, decorated fields and foreign keys' ); $this->assertEquals( array_keys(DataObject::database_fields('DataObjectTest_SubTeam')), array( 'SubclassDatabaseField', ), 'databaseFields() on subclass contains only fields defined on instance' ); } function testDataObjectUpdate() { /* update() calls can use the dot syntax to reference has_one relations and other methods that return objects */ $team1 = $this->objFromFixture('DataObjectTest_Team', 'team1'); $team1->CaptainID = $this->idFromFixture('DataObjectTest_Player', 'captain1'); $team1->update(array( 'DatabaseField' => 'Something', 'Captain.FirstName' => 'Jim', 'Captain.Email' => 'jim@example.com', 'Captain.FavouriteTeam.Title' => 'New and improved team 1', )); /* Test the simple case of updating fields on the object itself */ $this->assertEquals('Something', $team1->DatabaseField); /* Setting Captain.Email and Captain.FirstName will have updated DataObjectTest_Captain.captain1 in the database. Although update() * doesn't usually write, it does write related records automatically. */ $captain1 = $this->objFromFixture('DataObjectTest_Player', 'captain1'); $this->assertEquals('Jim', $captain1->FirstName); $this->assertEquals('jim@example.com', $captain1->Email); /* Jim's favourite team is team 1; we need to reload the object to the the change that setting Captain.FavouriteTeam.Title made */ $reloadedTeam1 = $this->objFromFixture('DataObjectTest_Team', 'team1'); $this->assertEquals('New and improved team 1', $reloadedTeam1->Title); } public function testWritingInvalidDataObjectThrowsException() { $validatedObject = new DataObjectTest_ValidatedObject(); $this->setExpectedException('ValidationException'); $validatedObject->write(); } public function testWritingValidDataObjectDoesntThrowException() { $validatedObject = new DataObjectTest_ValidatedObject(); $validatedObject->Name = "Mr. Jones"; $validatedObject->write(); $this->assertTrue($validatedObject->isInDB(), "Validated object was not saved to database"); } public function testSubclassCreation() { /* Creating a new object of a subclass should set the ClassName field correctly */ $obj = new DataObjectTest_SubTeam(); $obj->write(); $this->assertEquals("DataObjectTest_SubTeam", DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()); } public function testForceInsert() { /* If you set an ID on an object and pass forceInsert = true, then the object should be correctly created */ $conn = DB::getConn(); if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('DataObjectTest_Team', true); $obj = new DataObjectTest_SubTeam(); $obj->ID = 1001; $obj->Title = 'asdfasdf'; $obj->SubclassDatabaseField = 'asdfasdf'; $obj->write(false, true); if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('DataObjectTest_Team', false); $this->assertEquals("DataObjectTest_SubTeam", DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()); /* Check that it actually saves to the database with the correct ID */ $this->assertEquals("1001", DB::query("SELECT \"ID\" FROM \"DataObjectTest_SubTeam\" WHERE \"SubclassDatabaseField\" = 'asdfasdf'")->value()); $this->assertEquals("1001", DB::query("SELECT \"ID\" FROM \"DataObjectTest_Team\" WHERE \"Title\" = 'asdfasdf'")->value()); } public function TestHasOwnTable() { /* Test DataObject::has_own_table() returns true if the object has $has_one or $db values */ $this->assertTrue(DataObject::has_own_table("DataObjectTest_Player")); $this->assertTrue(DataObject::has_own_table("DataObjectTest_Team")); $this->assertTrue(DataObject::has_own_table("DataObjectTest_Fixture")); /* Root DataObject that always have a table, even if they lack both $db and $has_one */ $this->assertTrue(DataObject::has_own_table("DataObjectTest_FieldlessTable")); /* Subclasses without $db or $has_one don't have a table */ $this->assertFalse(DataObject::has_own_table("DataObjectTest_FieldlessSubTable")); /* Return false if you don't pass it a subclass of DataObject */ $this->assertFalse(DataObject::has_own_table("DataObject")); $this->assertFalse(DataObject::has_own_table("ViewableData")); $this->assertFalse(DataObject::has_own_table("ThisIsntADataObject")); } public function testMerge() { // test right merge of subclasses $left = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1'); $right = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam2_with_player_relation'); $leftOrigID = $left->ID; $left->merge($right, 'right', false, false); $this->assertEquals( $left->Title, 'Subteam 2', 'merge() with "right" priority overwrites fields with existing values on subclasses' ); $this->assertEquals( $left->ID, $leftOrigID, 'merge() with "right" priority doesnt overwrite database ID' ); // test overwriteWithEmpty flag on existing left values $left = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam2_with_player_relation'); $right = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam3_with_empty_fields'); $left->merge($right, 'right', false, true); $this->assertEquals( $left->Title, 'Subteam 3', 'merge() with $overwriteWithEmpty overwrites non-empty fields on left object' ); // test overwriteWithEmpty flag on empty left values $left = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam1'); $right = $this->objFromFixture('DataObjectTest_SubTeam', 'subteam2_with_player_relation'); // $SubclassDatabaseField is empty on here $left->merge($right, 'right', false, true); $this->assertEquals( $left->SubclassDatabaseField, NULL, 'merge() with $overwriteWithEmpty overwrites empty fields on left object' ); // @todo test "left" priority flag // @todo test includeRelations flag // @todo test includeRelations in combination with overwriteWithEmpty // @todo test has_one relations // @todo test has_many and many_many relations } function testPopulateDefaults() { $obj = new DataObjectTest_Fixture(); $this->assertEquals( $obj->MyFieldWithDefault, "Default Value", "Defaults are populated for in-memory object from \$defaults array" ); } function testNewClassInstance() { $page = $this->objFromFixture('Page', 'page1'); $changedPage = $page->newClassInstance('RedirectorPage'); $changedFields = $changedPage->getChangedFields(); // Don't write the record, it will reset changed fields $this->assertType('RedirectorPage', $changedPage); $this->assertEquals($changedPage->ClassName, 'RedirectorPage'); $this->assertEquals($changedPage->RedirectionType, 'Internal'); //$this->assertEquals($changedPage->RecordClassName, 'RedirectorPage'); $this->assertContains('ClassName', array_keys($changedFields)); $this->assertEquals($changedFields['ClassName']['before'], 'Page'); $this->assertEquals($changedFields['ClassName']['after'], 'RedirectorPage'); $changedPage->write(); $this->assertType('RedirectorPage', $changedPage); $this->assertEquals($changedPage->ClassName, 'RedirectorPage'); } function testManyManyExtraFields() { $player = $this->objFromFixture('DataObjectTest_Player', 'player1'); $team = $this->objFromFixture('DataObjectTest_Team', 'team1'); // Extra fields are immediately available on the Team class (defined in $many_many_extraFields) $teamExtraFields = $team->many_many_extraFields('Players'); $this->assertEquals($teamExtraFields, array( 'Position' => 'Varchar(100)' )); // We'll have to go through the relation to get the extra fields on Player $playerExtraFields = $player->many_many_extraFields('Teams'); $this->assertEquals($playerExtraFields, array( 'Position' => 'Varchar(100)' )); // Iterate through a many-many relationship and confirm that extra fields are included $newTeam = new DataObjectTest_Team(); $newTeam->Title = "New team"; $newTeam->write(); $newTeamID = $newTeam->ID; $newPlayer = new DataObjectTest_Player(); $newPlayer->FirstName = "Sam"; $newPlayer->Surname = "Minnee"; $newPlayer->write(); // The idea of Sam as a prop is essentially humourous. $newTeam->Players()->add($newPlayer, array("Position" => "Prop")); // Requery and uncache everything $newTeam->flushCache(); $newTeam = DataObject::get_by_id('DataObjectTest_Team', $newTeamID); // Check that the Position many_many_extraField is extracted. $player = $newTeam->Players()->First(); $this->assertEquals('Sam', $player->FirstName); $this->assertEquals("Prop", $player->Position); // Check that ordering a many-many relation by an aggregate column doesn't fail $player = $this->objFromFixture('DataObjectTest_Player', 'player2'); $player->Teams("", "count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC"); } /** * Check that the queries generated for many-many relation queries can have unlimitedRowCount * called on them. */ function testManyManyUnlimitedRowCount() { $player = $this->objFromFixture('DataObjectTest_Player', 'player2'); $query = $player->getManyManyComponentsQuery('Teams'); $this->assertEquals(2, $query->unlimitedRowCount()); } /** * Tests that singular_name() generates sensible defaults. */ public function testSingularName() { $assertions = array ( 'DataObjectTest_Player' => 'Data Object Test Player', 'DataObjectTest_Team' => 'Data Object Test Team', 'DataObjectTest_Fixture' => 'Data Object Test Fixture' ); foreach($assertions as $class => $expectedSingularName) { $this->assertEquals ( $expectedSingularName, singleton($class)->singular_name(), "Assert that the singular_name for '$class' is correct." ); } } function testHasDatabaseField() { $team = singleton('DataObjectTest_Team'); $subteam = singleton('DataObjectTest_SubTeam'); $this->assertTrue( $team->hasDatabaseField('Title'), "hasOwnDatabaseField() works with \$db fields" ); $this->assertTrue( $team->hasDatabaseField('CaptainID'), "hasOwnDatabaseField() works with \$has_one fields" ); $this->assertFalse( $team->hasDatabaseField('NonExistentField'), "hasOwnDatabaseField() doesn't detect non-existend fields" ); $this->assertTrue( $team->hasDatabaseField('DecoratedDatabaseField'), "hasOwnDatabaseField() works with decorated fields" ); $this->assertFalse( $team->hasDatabaseField('SubclassDatabaseField'), "hasOwnDatabaseField() doesn't pick up fields in subclasses on parent class" ); $this->assertTrue( $subteam->hasDatabaseField('SubclassDatabaseField'), "hasOwnDatabaseField() picks up fields in subclasses" ); } function testFieldTypes() { $obj = new DataObjectTest_Fixture(); $obj->DateField = '1988-01-02'; $obj->DatetimeField = '1988-03-04 06:30'; $obj->write(); $obj->flushCache(); $obj = DataObject::get_by_id('DataObjectTest_Fixture', $obj->ID); $this->assertEquals('1988-01-02', $obj->DateField); $this->assertEquals('1988-03-04 06:30:00', $obj->DatetimeField); } function testTwoSubclassesWithTheSameFieldNameWork() { // Create two objects of different subclasses, setting the values of fields that are // defined separately in each subclass $obj1 = new DataObjectTest_SubTeam(); $obj1->SubclassDatabaseField = "obj1"; $obj2 = new OtherSubclassWithSameField(); $obj2->SubclassDatabaseField = "obj2"; // Write them to the database $obj1->write(); $obj2->write(); // Check that the values of those fields are properly read from the database $values = DataObject::get("DataObjectTest_Team", "\"DataObjectTest_Team\".\"ID\" IN ($obj1->ID, $obj2->ID)")->column("SubclassDatabaseField"); $this->assertEquals(array('obj1', 'obj2'), $values); } function testClassNameSetForNewObjects() { $d = new DataObjectTest_Player(); $this->assertEquals('DataObjectTest_Player', $d->ClassName); } public function testHasValue() { $team = new DataObjectTest_Team(); $this->assertFalse($team->hasValue('Title', null, false)); $this->assertFalse($team->hasValue('DatabaseField', null, false)); $team->Title = 'hasValue'; $this->assertTrue($team->hasValue('Title', null, false)); $this->assertFalse($team->hasValue('DatabaseField', null, false)); $team->DatabaseField = '<p></p>'; $this->assertTrue($team->hasValue('Title', null, false)); $this->assertFalse ( $team->hasValue('DatabaseField', null, false), 'Test that a blank paragraph on a HTML field is not a valid value.' ); $team->Title = '<p></p>'; $this->assertTrue ( $team->hasValue('Title', null, false), 'Test that an empty paragraph is a value for non-HTML fields.' ); $team->DatabaseField = 'hasValue'; $this->assertTrue($team->hasValue('Title', null, false)); $this->assertTrue($team->hasValue('DatabaseField', null, false)); } public function testHasMany() { $company = new DataObjectTest_Company(); $this->assertEquals ( array ( 'CurrentStaff' => 'DataObjectTest_Staff', 'PreviousStaff' => 'DataObjectTest_Staff' ), $company->has_many(), 'has_many strips field name data by default.' ); $this->assertEquals ( 'DataObjectTest_Staff', $company->has_many('CurrentStaff'), 'has_many strips field name data by default on single relationships.' ); $this->assertEquals ( array ( 'CurrentStaff' => 'DataObjectTest_Staff.CurrentCompany', 'PreviousStaff' => 'DataObjectTest_Staff.PreviousCompany' ), $company->has_many(null, false), 'has_many returns field name data when $classOnly is false.' ); $this->assertEquals ( 'DataObjectTest_Staff.CurrentCompany', $company->has_many('CurrentStaff', false), 'has_many returns field name data on single records when $classOnly is false.' ); } public function testGetRemoteJoinField() { $company = new DataObjectTest_Company(); $this->assertEquals('CurrentCompanyID', $company->getRemoteJoinField('CurrentStaff')); $this->assertEquals('PreviousCompanyID', $company->getRemoteJoinField('PreviousStaff')); $ceo = new DataObjectTest_CEO(); $this->assertEquals('CEOID', $ceo->getRemoteJoinField('Company', 'belongs_to')); $this->assertEquals('PreviousCEOID', $ceo->getRemoteJoinField('PreviousCompany', 'belongs_to')); } public function testBelongsTo() { $company = new DataObjectTest_Company(); $ceo = new DataObjectTest_CEO(); $company->write(); $ceo->write(); $company->CEOID = $ceo->ID; $company->write(); $this->assertEquals($company->ID, $ceo->Company()->ID, 'belongs_to returns the right results.'); $ceo = new DataObjectTest_CEO(); $ceo->write(); $this->assertTrue ( $ceo->Company() instanceof DataObjectTest_Company, 'DataObjects across belongs_to relations are automatically created.' ); $this->assertEquals($ceo->ID, $ceo->Company()->CEOID, 'Remote IDs are automatically set.'); $ceo->write(false, false, false, true); $this->assertTrue($ceo->Company()->isInDB(), 'write() writes belongs_to components to the database.'); $newCEO = DataObject::get_by_id('DataObjectTest_CEO', $ceo->ID); $this->assertEquals ( $ceo->Company()->ID, $newCEO->Company()->ID, 'belongs_to can be retrieved from the database.' ); } public function testInvalidate() { $do = new DataObjectTest_Fixture(); $do->write(); $do->delete(); try { // Prohibit invalid object manipulation $do->delete(); $do->write(); $do->duplicate(); } catch(Exception $e) { return; } $this->fail('Should throw an exception'); } } class DataObjectTest_Player extends Member implements TestOnly { static $has_one = array( 'FavouriteTeam' => 'DataObjectTest_Team', ); static $belongs_many_many = array( 'Teams' => 'DataObjectTest_Team' ); } class DataObjectTest_Team extends DataObject implements TestOnly { static $db = array( 'Title' => 'Varchar', 'DatabaseField' => 'HTMLVarchar' ); static $has_one = array( "Captain" => 'DataObjectTest_Player', 'HasOneRelationship' => 'DataObjectTest_Player', ); static $many_many = array( 'Players' => 'DataObjectTest_Player' ); static $many_many_extraFields = array( 'Players' => array( 'Position' => 'Varchar(100)' ) ); function getDynamicField() { return 'dynamicfield'; } } class DataObjectTest_Fixture extends DataObject implements TestOnly { static $db = array( // Funny field names 'Data' => 'Varchar', 'Duplicate' => 'Varchar', 'DbObject' => 'Varchar', // Field with default 'MyField' => 'Varchar', // Field types "DateField" => "Date", "DatetimeField" => "Datetime", ); static $defaults = array( 'MyFieldWithDefault' => 'Default Value', ); } class DataObjectTest_SubTeam extends DataObjectTest_Team implements TestOnly { static $db = array( 'SubclassDatabaseField' => 'Varchar' ); } class OtherSubclassWithSameField extends DataObjectTest_Team implements TestOnly { static $db = array( 'SubclassDatabaseField' => 'Varchar', ); } class DataObjectTest_FieldlessTable extends DataObject implements TestOnly { } class DataObjectTest_FieldlessSubTable extends DataObjectTest_Team implements TestOnly { } class DataObjectTest_Team_Decorator extends DataObjectDecorator implements TestOnly { function extraStatics() { return array( 'db' => array( 'DecoratedDatabaseField' => 'Varchar' ), 'has_one' => array( 'DecoratedHasOneRelationship' => 'DataObjectTest_Player' ) ); } function getDecoratedDynamicField() { return "decorated dynamic field"; } } class DataObjectTest_ValidatedObject extends DataObject implements TestOnly { static $db = array( 'Name' => 'Varchar(50)' ); protected function validate() { if(!empty($this->Name)) { return new ValidationResult(); } else { return new ValidationResult(false, "This object needs a name. Otherwise it will have an identity crisis!"); } } } class DataObjectTest_Company extends DataObject { public static $has_one = array ( 'CEO' => 'DataObjectTest_CEO', 'PreviousCEO' => 'DataObjectTest_CEO' ); public static $has_many = array ( 'CurrentStaff' => 'DataObjectTest_Staff.CurrentCompany', 'PreviousStaff' => 'DataObjectTest_Staff.PreviousCompany' ); } class DataObjectTest_Staff extends DataObject { public static $has_one = array ( 'CurrentCompany' => 'DataObjectTest_Company', 'PreviousCompany' => 'DataObjectTest_Company' ); } class DataObjectTest_CEO extends DataObjectTest_Staff { public static $belongs_to = array ( 'Company' => 'DataObjectTest_Company.CEO', 'PreviousCompany' => 'DataObjectTest_Company.PreviousCEO' ); } DataObject::add_extension('DataObjectTest_Team', 'DataObjectTest_Team_Decorator'); ?>
benbruscella/vpcounselling.com
sapphire/tests/DataObjectTest.php
PHP
bsd-3-clause
41,032
// Copyright 2015 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. #ifndef CHROME_BROWSER_UI_COCOA_PASSWORDS_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ #define CHROME_BROWSER_UI_COCOA_PASSWORDS_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" #import "chrome/browser/ui/cocoa/passwords/base_passwords_content_view_controller.h" #import "chrome/browser/ui/cocoa/passwords/credential_item_view.h" @class AccountAvatarFetcherManager; @class BubbleCombobox; class ManagePasswordsBubbleModel; @class ManagePasswordCredentialItemViewController; // A custom cell that displays a credential item in an NSTableView. @interface CredentialItemCell : NSCell - (id)initWithView:(CredentialItemView*)view; @property(nonatomic, readonly) CredentialItemView* view; @end // Manages a view that shows a list of credentials that can be used for // authentication to a site. @interface ManagePasswordsBubbleAccountChooserViewController : ManagePasswordsBubbleContentViewController<CredentialItemDelegate, NSTableViewDataSource, NSTableViewDelegate> { @private ManagePasswordsBubbleModel* model_; // Weak. NSButton* cancelButton_; // Weak. BubbleCombobox* moreButton_; // Weak. NSTableView* credentialsView_; // Weak. base::scoped_nsobject<NSArray> credentialItems_; base::scoped_nsobject<AccountAvatarFetcherManager> avatarManager_; } // Initializes a new account chooser and populates it with the credentials // stored in |model|. Designated initializer. - (id)initWithModel:(ManagePasswordsBubbleModel*)model delegate:(id<ManagePasswordsBubbleContentViewDelegate>)delegate; @end #endif // CHROME_BROWSER_UI_COCOA_PASSWORDS_ACCOUNT_CHOOSER_VIEW_CONTROLLER_H_
hujiajie/chromium-crosswalk
chrome/browser/ui/cocoa/passwords/account_chooser_view_controller.h
C
bsd-3-clause
1,917
<!doctype html> <meta charset="utf-8" /> <title>textarea POST empty content</title> <p> Click the submit button. The following page should return “PASS”. </p> <form action="../res/empty_post.php" method="post"> <p> <textarea name="test"></textarea> <input name="submit" type="submit" /> </p> </form>
frivoal/presto-testo
core/standards/wf1/interactive/textarea-002.html
HTML
bsd-3-clause
315
/* $OpenBSD: getentropy_freebsd.c,v 1.3 2016/08/07 03:27:21 tb Exp $ */ /* * Copyright (c) 2014 Pawel Jakub Dawidek <pjd@FreeBSD.org> * Copyright (c) 2014 Brent Cook <bcook@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Emulation of getentropy(2) as documented at: * http://man.openbsd.org/getentropy.2 */ #include <sys/types.h> #include <sys/sysctl.h> #include <errno.h> #include <stddef.h> /* * Derived from lib/libc/gen/arc4random.c from FreeBSD. */ static size_t getentropy_sysctl(u_char *buf, size_t size) { int mib[2]; size_t len, done; mib[0] = CTL_KERN; mib[1] = KERN_ARND; done = 0; do { len = size; if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) return (done); done += len; buf += len; size -= len; } while (size > 0); return (done); } int getentropy(void *buf, size_t len) { if (len <= 256 && getentropy_sysctl(buf, len) == len) return (0); errno = EIO; return (-1); }
GaloisInc/hacrypto
src/C/libressl/libressl-2.7.2/crypto/compat/getentropy_freebsd.c
C
bsd-3-clause
1,621
var _CURRENT_FORM; var _FIRST_ERRORED_FIELD = null; function initialiseForm(form, fromAnOnBlur) { _CURRENT_FORM = form; _FIRST_ERRORED_FIELD = null; if(fromAnOnBlur) { limitValidationErrorsTo(fromAnOnBlur); } else { clearValidationErrorLimit(); } _HAS_HAD_FORM_ERROR = false; clearValidationErrorCache(); } function hasHadFormError() { return _HAS_HAD_FORM_ERROR || !_ERROR_CACHE; } function focusOnFirstErroredField() { try { _FIRST_ERRORED_FIELD.focus(); } catch(er) { } } /** * Returns group with the correct classname */ function findIndexOf(group,index) { var i; for(i = 0; i < group.length; i++) { if(group[i].className.indexOf(index) > -1) { return group[i]; } } return null; } function clearErrorMessage(holderDiv){ //merged by nlou 23/08/2007, r#40674 if(holderDiv.tagName == 'TD'){//for tablefield. $$('span.message', holderDiv).each(function(el){ Element.hide(el); } ); }else{ $$('span.message', holderDiv.parentNode).each(function(el) { Element.hide(el); }); } $$('div.validationError', holderDiv.parentNode).each(function(el) { Element.removeClassName(el,'validationError'); }); } function clearAllErrorMessages() { $$('span.message').each(function(el) { Element.hide(el); }); $$('div.validationError').each(function(el) { Element.removeClassName(el,'validationError'); }); } function require(fieldName,cachedError) { el = _CURRENT_FORM.elements[fieldName]; // see if the field is an optionset if(el == null) { var descendants = _CURRENT_FORM.getElementsByTagName('*'); el = $(fieldName); if(el == null) return true; if(Element.hasClassName(el, 'optionset')) { el.type = 'optionset'; var options = el.getElementsByTagName('input'); for(var i = 0; i < options.length; i++) { if(options[i].checked) if(el.value != null) el.value += ',' + options[i].value; else el.value = options[i].value; } } } if(el != null) { // Sets up radio and checkbox validation if(el.type == 'checkbox' || el.type == 'radio') { var set = el.checked; }//merged by nlou 23/08/2007, r#40674 else if(el.type == 'select-one'){ if(el.value == ''||el.value == '0'){ var set = ''; }else{ var set = el.value; } }else{ var set = el.value; } var baseEl; var fieldHolder = el; // Sometimes require events are triggered of // associative elements like labels ;-p if(el.type) { if(el.parentNode.className.indexOf('form') != -1) set = true; baseEl = el; } else { if(_CURRENT_FORM.elements[fieldName]) { //Some elements are nested and need to be "got" var i, hasValue = false; if(_CURRENT_FORM.elements[fieldName].length > 1) { for(i=0; i < el.length; i++) { if(el[i].checked && el[i].value) { hasValue = true; break; } } if(hasValue) set = true; else set = ""; baseEl = el[0].parentNode.parentNode; } else { set = ""; baseEl = el.parentNode; } } else { set = true; } } // This checks to see if the input has a value, and the field is not a readonly. if( ( typeof set == 'undefined' || (typeof(set) == 'string' && set.match(/^\s*$/)) ) ) { //fieldgroup validation var fieldLabel = findParentLabel(baseEl); // Some fields do-not have labels, in // which case we need a blank one if(fieldLabel == null || fieldLabel == "") { fieldlabel = "this field"; } var errorMessage = ss.i18n.sprintf(ss.i18n._t('VALIDATOR.FIELDREQUIRED', 'Please fill out "%s", it is required.'), fieldLabel); if(baseEl.requiredErrorMsg) errorMessage = baseEl.requiredErrorMsg; else if(_CURRENT_FORM.requiredErrorMsg) errorMessage = _CURRENT_FORM.requiredErrorMsg; validationError(baseEl, errorMessage.replace('$FieldLabel', fieldLabel),"required",cachedError); return false; } else { if(!hasHadFormError()) { if(baseEl) fieldHolder = baseEl.parentNode; clearErrorMessage(fieldHolder); } return true; } } return true; } /** * Returns the label of the blockset which contains the classname left */ function findParentLabel(el) { // If the el's type is HTML then were at the uppermost parent, so return // null. its handled by the validator function anyway :-) if(el) { if(el.className == "undefined") { return null; } else { if(el.className) { if(el.className.indexOf('field') == 0) { labels = el.getElementsByTagName('label'); if(labels){ var left = findIndexOf(labels,'left'); var right = findIndexOf(labels,'right'); if(left) { return strip_tags(left.innerHTML); } else if(right) { return strip_tags(right.innerHTML); } else { return findParentLabel(el.parentNode); } } }//merged by nlou 23/08/2007, r#40674 else if(el.className.indexOf('tablecolumn') != -1){ return el.className.substring(0, el.className.indexOf('tablecolumn')-1); }else{ return findParentLabel(el.parentNode); } } else { // Try to find a label with a for value of this field. if(el.id) { var labels = $$('label[for=' + el.id + ']'); if(labels && labels.length > 0) return labels[0].innerHTML; } return findParentLabel(el.parentNode); } } } // backup return "this"; } /** * Adds a validation error to an element */ function validationError(field,message, messageClass, cacheError) { if(typeof(field) == 'string') { field = $(field); } if(cacheError) { _ERROR_CACHE[_ERROR_CACHE.length] = { "field": field, "message": message, "messageClass": messageClass } return; } // The validation function should only be called if you've just left a field, // or the field is being validated on final submission if(_LIMIT_VALIDATION_ERRORS && _LIMIT_VALIDATION_ERRORS != field) { // clearErrorMessage(field.parentNode); return; } _HAS_HAD_FORM_ERROR = true; // See if the tag has a reference to the validationMessage (quicker than the one below) var validationMessage = field.validationMessage; // Cycle through the elements to see if it has a span // (for a validation or required messages) if(!validationMessage) { //Get the parent holder of the element var FieldHolder = field.parentNode; var allSpans = FieldHolder.getElementsByTagName('span'); validationMessage = findIndexOf(allSpans,'message'); } // If we didn't find it, create it if(!validationMessage) { validationMessage = document.createElement('span'); FieldHolder.appendChild(validationMessage); } // Keep a reference to it field.validationMessage = validationMessage; // Keep a reference to the first errored field if(field && !_FIRST_ERRORED_FIELD) _FIRST_ERRORED_FIELD = field; // Set the attributes validationMessage.className = "message " + messageClass; validationMessage.innerHTML = message; validationMessage.style.display = "block"; // Set Classname on holder var holder = document.getParentOfElement(field,'div','field'); Element.addClassName(holder, 'validationError'); } /** * Set a limitation so that only validation errors for the given element will actually be shown */ var _LIMIT_VALIDATION_ERRORS = null; function limitValidationErrorsTo(field) { _LIMIT_VALIDATION_ERRORS = field; } function clearValidationErrorLimit() { _LIMIT_VALIDATION_ERRORS = null; } function clearValidationErrorCache() { _ERROR_CACHE = new Array(); } function showCachedValidationErrors() { for(i = 0; i < _ERROR_CACHE.length; i++) { validationError(_ERROR_CACHE[i]["field"], _ERROR_CACHE[i]["message"], _ERROR_CACHE[i]["messageClass"], false); } } function strip_tags(text) { return text.replace(/<[^>]+>/g,''); }
melechi/s3.net.au
sapphire/javascript/Validator.js
JavaScript
bsd-3-clause
7,731
"""Test inter-conversion of different polynomial classes. This tests the convert and cast methods of all the polynomial classes. """ import operator as op from numbers import Number import pytest import numpy as np from numpy.polynomial import ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE) from numpy.testing import ( assert_almost_equal, assert_raises, assert_equal, assert_, ) from numpy.polynomial.polyutils import RankWarning # # fixtures # classes = ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE ) classids = tuple(cls.__name__ for cls in classes) @pytest.fixture(params=classes, ids=classids) def Poly(request): return request.param # # helper functions # random = np.random.random def assert_poly_almost_equal(p1, p2, msg=""): try: assert_(np.all(p1.domain == p2.domain)) assert_(np.all(p1.window == p2.window)) assert_almost_equal(p1.coef, p2.coef) except AssertionError: msg = f"Result: {p1}\nTarget: {p2}" raise AssertionError(msg) # # Test conversion methods that depend on combinations of two classes. # Poly1 = Poly Poly2 = Poly def test_conversion(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = Poly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = p1.convert(kind=Poly2, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) def test_cast(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = Poly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = Poly2.cast(p1, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) # # test methods that depend on one class # def test_identity(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 x = np.linspace(d[0], d[1], 11) p = Poly.identity(domain=d, window=w) assert_equal(p.domain, d) assert_equal(p.window, w) assert_almost_equal(p(x), x) def test_basis(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly.basis(5, domain=d, window=w) assert_equal(p.domain, d) assert_equal(p.window, w) assert_equal(p.coef, [0]*5 + [1]) def test_fromroots(Poly): # check that requested roots are zeros of a polynomial # of correct degree, domain, and window. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 r = random((5,)) p1 = Poly.fromroots(r, domain=d, window=w) assert_equal(p1.degree(), len(r)) assert_equal(p1.domain, d) assert_equal(p1.window, w) assert_almost_equal(p1(r), 0) # check that polynomial is monic pdom = Polynomial.domain pwin = Polynomial.window p2 = Polynomial.cast(p1, domain=pdom, window=pwin) assert_almost_equal(p2.coef[-1], 1) def test_bad_conditioned_fit(Poly): x = [0., 0., 1.] y = [1., 2., 3.] # check RankWarning is raised with pytest.warns(RankWarning) as record: Poly.fit(x, y, 2) assert record[0].message.args[0] == "The fit may be poorly conditioned" def test_fit(Poly): def f(x): return x*(x - 1)*(x - 2) x = np.linspace(0, 3) y = f(x) # check default value of domain and window p = Poly.fit(x, y, 3) assert_almost_equal(p.domain, [0, 3]) assert_almost_equal(p(x), y) assert_equal(p.degree(), 3) # check with given domains and window d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly.fit(x, y, 3, domain=d, window=w) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, d) assert_almost_equal(p.window, w) p = Poly.fit(x, y, [0, 1, 2, 3], domain=d, window=w) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, d) assert_almost_equal(p.window, w) # check with class domain default p = Poly.fit(x, y, 3, []) assert_equal(p.domain, Poly.domain) assert_equal(p.window, Poly.window) p = Poly.fit(x, y, [0, 1, 2, 3], []) assert_equal(p.domain, Poly.domain) assert_equal(p.window, Poly.window) # check that fit accepts weights. w = np.zeros_like(x) z = y + random(y.shape)*.25 w[::2] = 1 p1 = Poly.fit(x[::2], z[::2], 3) p2 = Poly.fit(x, z, 3, w=w) p3 = Poly.fit(x, z, [0, 1, 2, 3], w=w) assert_almost_equal(p1(x), p2(x)) assert_almost_equal(p2(x), p3(x)) def test_equal(Poly): p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3]) p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3]) p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3]) p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2]) assert_(p1 == p1) assert_(not p1 == p2) assert_(not p1 == p3) assert_(not p1 == p4) def test_not_equal(Poly): p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3]) p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3]) p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3]) p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2]) assert_(not p1 != p1) assert_(p1 != p2) assert_(p1 != p3) assert_(p1 != p4) def test_add(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 + p2 assert_poly_almost_equal(p2 + p1, p3) assert_poly_almost_equal(p1 + c2, p3) assert_poly_almost_equal(c2 + p1, p3) assert_poly_almost_equal(p1 + tuple(c2), p3) assert_poly_almost_equal(tuple(c2) + p1, p3) assert_poly_almost_equal(p1 + np.array(c2), p3) assert_poly_almost_equal(np.array(c2) + p1, p3) assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.add, p1, Chebyshev([0])) else: assert_raises(TypeError, op.add, p1, Polynomial([0])) def test_sub(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 - p2 assert_poly_almost_equal(p2 - p1, -p3) assert_poly_almost_equal(p1 - c2, p3) assert_poly_almost_equal(c2 - p1, -p3) assert_poly_almost_equal(p1 - tuple(c2), p3) assert_poly_almost_equal(tuple(c2) - p1, -p3) assert_poly_almost_equal(p1 - np.array(c2), p3) assert_poly_almost_equal(np.array(c2) - p1, -p3) assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.sub, p1, Chebyshev([0])) else: assert_raises(TypeError, op.sub, p1, Polynomial([0])) def test_mul(Poly): c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 * p2 assert_poly_almost_equal(p2 * p1, p3) assert_poly_almost_equal(p1 * c2, p3) assert_poly_almost_equal(c2 * p1, p3) assert_poly_almost_equal(p1 * tuple(c2), p3) assert_poly_almost_equal(tuple(c2) * p1, p3) assert_poly_almost_equal(p1 * np.array(c2), p3) assert_poly_almost_equal(np.array(c2) * p1, p3) assert_poly_almost_equal(p1 * 2, p1 * Poly([2])) assert_poly_almost_equal(2 * p1, p1 * Poly([2])) assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mul, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mul, p1, Polynomial([0])) def test_floordiv(Poly): c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 // p2, p1) assert_poly_almost_equal(p4 // c2, p1) assert_poly_almost_equal(c4 // p2, p1) assert_poly_almost_equal(p4 // tuple(c2), p1) assert_poly_almost_equal(tuple(c4) // p2, p1) assert_poly_almost_equal(p4 // np.array(c2), p1) assert_poly_almost_equal(np.array(c4) // p2, p1) assert_poly_almost_equal(2 // p2, Poly([0])) assert_poly_almost_equal(p2 // 2, 0.5*p2) assert_raises( TypeError, op.floordiv, p1, Poly([0], domain=Poly.domain + 1)) assert_raises( TypeError, op.floordiv, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.floordiv, p1, Chebyshev([0])) else: assert_raises(TypeError, op.floordiv, p1, Polynomial([0])) def test_truediv(Poly): # true division is valid only if the denominator is a Number and # not a python bool. p1 = Poly([1,2,3]) p2 = p1 * 5 for stype in np.ScalarType: if not issubclass(stype, Number) or issubclass(stype, bool): continue s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for stype in (int, float): s = stype(5) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for stype in [complex]: s = stype(5, 0) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) for s in [tuple(), list(), dict(), bool(), np.array([1])]: assert_raises(TypeError, op.truediv, p2, s) assert_raises(TypeError, op.truediv, s, p2) for ptype in classes: assert_raises(TypeError, op.truediv, p2, ptype(1)) def test_mod(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 % p2, p3) assert_poly_almost_equal(p4 % c2, p3) assert_poly_almost_equal(c4 % p2, p3) assert_poly_almost_equal(p4 % tuple(c2), p3) assert_poly_almost_equal(tuple(c4) % p2, p3) assert_poly_almost_equal(p4 % np.array(c2), p3) assert_poly_almost_equal(np.array(c4) % p2, p3) assert_poly_almost_equal(2 % p2, Poly([2])) assert_poly_almost_equal(p2 % 2, Poly([0])) assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mod, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mod, p1, Polynomial([0])) def test_divmod(Poly): # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) quo, rem = divmod(p4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, c2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(c4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, tuple(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(tuple(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, np.array(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(np.array(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p2, 2) assert_poly_almost_equal(quo, 0.5*p2) assert_poly_almost_equal(rem, Poly([0])) quo, rem = divmod(2, p2) assert_poly_almost_equal(quo, Poly([0])) assert_poly_almost_equal(rem, Poly([2])) assert_raises(TypeError, divmod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, divmod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, divmod, p1, Chebyshev([0])) else: assert_raises(TypeError, divmod, p1, Polynomial([0])) def test_roots(Poly): d = Poly.domain * 1.25 + .25 w = Poly.window tgt = np.linspace(d[0], d[1], 5) res = np.sort(Poly.fromroots(tgt, domain=d, window=w).roots()) assert_almost_equal(res, tgt) # default domain and window res = np.sort(Poly.fromroots(tgt).roots()) assert_almost_equal(res, tgt) def test_degree(Poly): p = Poly.basis(5) assert_equal(p.degree(), 5) def test_copy(Poly): p1 = Poly.basis(5) p2 = p1.copy() assert_(p1 == p2) assert_(p1 is not p2) assert_(p1.coef is not p2.coef) assert_(p1.domain is not p2.domain) assert_(p1.window is not p2.window) def test_integ(Poly): P = Polynomial # Check defaults p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ()) p2 = P.cast(p0.integ(2)) assert_poly_almost_equal(p1, P([0, 2, 3, 4])) assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1])) # Check with k p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ(k=1)) p2 = P.cast(p0.integ(2, k=[1, 1])) assert_poly_almost_equal(p1, P([1, 2, 3, 4])) assert_poly_almost_equal(p2, P([1, 1, 1, 1, 1])) # Check with lbnd p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ(lbnd=1)) p2 = P.cast(p0.integ(2, lbnd=1)) assert_poly_almost_equal(p1, P([-9, 2, 3, 4])) assert_poly_almost_equal(p2, P([6, -9, 1, 1, 1])) # Check scaling d = 2*Poly.domain p0 = Poly.cast(P([1*2, 2*3, 3*4]), domain=d) p1 = P.cast(p0.integ()) p2 = P.cast(p0.integ(2)) assert_poly_almost_equal(p1, P([0, 2, 3, 4])) assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1])) def test_deriv(Poly): # Check that the derivative is the inverse of integration. It is # assumes that the integration has been checked elsewhere. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p1 = Poly([1, 2, 3], domain=d, window=w) p2 = p1.integ(2, k=[1, 2]) p3 = p1.integ(1, k=[1]) assert_almost_equal(p2.deriv(1).coef, p3.coef) assert_almost_equal(p2.deriv(2).coef, p1.coef) # default domain and window p1 = Poly([1, 2, 3]) p2 = p1.integ(2, k=[1, 2]) p3 = p1.integ(1, k=[1]) assert_almost_equal(p2.deriv(1).coef, p3.coef) assert_almost_equal(p2.deriv(2).coef, p1.coef) def test_linspace(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly([1, 2, 3], domain=d, window=w) # check default domain xtgt = np.linspace(d[0], d[1], 20) ytgt = p(xtgt) xres, yres = p.linspace(20) assert_almost_equal(xres, xtgt) assert_almost_equal(yres, ytgt) # check specified domain xtgt = np.linspace(0, 2, 20) ytgt = p(xtgt) xres, yres = p.linspace(20, domain=[0, 2]) assert_almost_equal(xres, xtgt) assert_almost_equal(yres, ytgt) def test_pow(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 tgt = Poly([1], domain=d, window=w) tst = Poly([1, 2, 3], domain=d, window=w) for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst # default domain and window tgt = Poly([1]) tst = Poly([1, 2, 3]) for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst # check error for invalid powers assert_raises(ValueError, op.pow, tgt, 1.5) assert_raises(ValueError, op.pow, tgt, -1) def test_call(Poly): P = Polynomial d = Poly.domain x = np.linspace(d[0], d[1], 11) # Check defaults p = Poly.cast(P([1, 2, 3])) tgt = 1 + x*(2 + 3*x) res = p(x) assert_almost_equal(res, tgt) def test_cutdeg(Poly): p = Poly([1, 2, 3]) assert_raises(ValueError, p.cutdeg, .5) assert_raises(ValueError, p.cutdeg, -1) assert_equal(len(p.cutdeg(3)), 3) assert_equal(len(p.cutdeg(2)), 3) assert_equal(len(p.cutdeg(1)), 2) assert_equal(len(p.cutdeg(0)), 1) def test_truncate(Poly): p = Poly([1, 2, 3]) assert_raises(ValueError, p.truncate, .5) assert_raises(ValueError, p.truncate, 0) assert_equal(len(p.truncate(4)), 3) assert_equal(len(p.truncate(3)), 3) assert_equal(len(p.truncate(2)), 2) assert_equal(len(p.truncate(1)), 1) def test_trim(Poly): c = [1, 1e-6, 1e-12, 0] p = Poly(c) assert_equal(p.trim().coef, c[:3]) assert_equal(p.trim(1e-10).coef, c[:2]) assert_equal(p.trim(1e-5).coef, c[:1]) def test_mapparms(Poly): # check with defaults. Should be identity. d = Poly.domain w = Poly.window p = Poly([1], domain=d, window=w) assert_almost_equal([0, 1], p.mapparms()) # w = 2*d + 1 p = Poly([1], domain=d, window=w) assert_almost_equal([1, 2], p.mapparms()) def test_ufunc_override(Poly): p = Poly([1, 2, 3]) x = np.ones(3) assert_raises(TypeError, np.add, p, x) assert_raises(TypeError, np.add, x, p) # # Test class method that only exists for some classes # class TestInterpolate: def f(self, x): return x * (x - 1) * (x - 2) def test_raises(self): assert_raises(ValueError, Chebyshev.interpolate, self.f, -1) assert_raises(TypeError, Chebyshev.interpolate, self.f, 10.) def test_dimensions(self): for deg in range(1, 5): assert_(Chebyshev.interpolate(self.f, deg).degree() == deg) def test_approximation(self): def powx(x, p): return x**p x = np.linspace(0, 2, 10) for deg in range(0, 10): for t in range(0, deg + 1): p = Chebyshev.interpolate(powx, deg, domain=[0, 2], args=(t,)) assert_almost_equal(p(x), powx(x, t), decimal=11)
anntzer/numpy
numpy/polynomial/tests/test_classes.py
Python
bsd-3-clause
18,331
//===- AsmParser.cpp - Parser for Assembly Files --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements the parser for assembly files. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/AsmCond.h" #include "llvm/MC/MCParser/AsmLexer.h" #include "llvm/MC/MCParser/MCAsmParser.h" #include "llvm/MC/MCParser/MCParsedAsmOperand.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCTargetAsmParser.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include <cctype> #include <deque> #include <set> #include <string> #include <vector> using namespace llvm; static cl::opt<bool> FatalAssemblerWarnings("fatal-assembler-warnings", cl::desc("Consider warnings as error")); MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {} namespace { /// \brief Helper types for tracking macro definitions. typedef std::vector<AsmToken> MCAsmMacroArgument; typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments; struct MCAsmMacroParameter { StringRef Name; MCAsmMacroArgument Value; bool Required; bool Vararg; MCAsmMacroParameter() : Required(false), Vararg(false) {} }; typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters; struct MCAsmMacro { StringRef Name; StringRef Body; MCAsmMacroParameters Parameters; public: MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) : Name(N), Body(B), Parameters(P) {} }; /// \brief Helper class for storing information about an active macro /// instantiation. struct MacroInstantiation { /// The macro being instantiated. const MCAsmMacro *TheMacro; /// The macro instantiation with substitutions. MemoryBuffer *Instantiation; /// The location of the instantiation. SMLoc InstantiationLoc; /// The buffer where parsing should resume upon instantiation completion. int ExitBuffer; /// The location where parsing should resume upon instantiation completion. SMLoc ExitLoc; public: MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL, MemoryBuffer *I); }; struct ParseStatementInfo { /// \brief The parsed operands from the last parsed statement. SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands; /// \brief The opcode from the last parsed instruction. unsigned Opcode; /// \brief Was there an error parsing the inline assembly? bool ParseError; SmallVectorImpl<AsmRewrite> *AsmRewrites; ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {} ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites) : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {} }; /// \brief The concrete assembly parser instance. class AsmParser : public MCAsmParser { AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION; void operator=(const AsmParser &) LLVM_DELETED_FUNCTION; private: AsmLexer Lexer; MCContext &Ctx; MCStreamer &Out; const MCAsmInfo &MAI; SourceMgr &SrcMgr; SourceMgr::DiagHandlerTy SavedDiagHandler; void *SavedDiagContext; MCAsmParserExtension *PlatformParser; /// This is the current buffer index we're lexing from as managed by the /// SourceMgr object. unsigned CurBuffer; AsmCond TheCondState; std::vector<AsmCond> TheCondStack; /// \brief maps directive names to handler methods in parser /// extensions. Extensions register themselves in this map by calling /// addDirectiveHandler. StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap; /// \brief Map of currently defined macros. StringMap<MCAsmMacro*> MacroMap; /// \brief Stack of active macro instantiations. std::vector<MacroInstantiation*> ActiveMacros; /// \brief List of bodies of anonymous macros. std::deque<MCAsmMacro> MacroLikeBodies; /// Boolean tracking whether macro substitution is enabled. unsigned MacrosEnabledFlag : 1; /// Flag tracking whether any errors have been encountered. unsigned HadError : 1; /// The values from the last parsed cpp hash file line comment if any. StringRef CppHashFilename; int64_t CppHashLineNumber; SMLoc CppHashLoc; unsigned CppHashBuf; /// When generating dwarf for assembly source files we need to calculate the /// logical line number based on the last parsed cpp hash file line comment /// and current line. Since this is slow and messes up the SourceMgr's /// cache we save the last info we queried with SrcMgr.FindLineNumber(). SMLoc LastQueryIDLoc; unsigned LastQueryBuffer; unsigned LastQueryLine; /// AssemblerDialect. ~OU means unset value and use value provided by MAI. unsigned AssemblerDialect; /// \brief is Darwin compatibility enabled? bool IsDarwin; /// \brief Are we parsing ms-style inline assembly? bool ParsingInlineAsm; public: AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, const MCAsmInfo &MAI); virtual ~AsmParser(); bool Run(bool NoInitialTextSection, bool NoFinalize = false) override; void addDirectiveHandler(StringRef Directive, ExtensionDirectiveHandler Handler) override { ExtensionDirectiveMap[Directive] = Handler; } public: /// @name MCAsmParser Interface /// { SourceMgr &getSourceManager() override { return SrcMgr; } MCAsmLexer &getLexer() override { return Lexer; } MCContext &getContext() override { return Ctx; } MCStreamer &getStreamer() override { return Out; } unsigned getAssemblerDialect() override { if (AssemblerDialect == ~0U) return MAI.getAssemblerDialect(); else return AssemblerDialect; } void setAssemblerDialect(unsigned i) override { AssemblerDialect = i; } void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) override; bool Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) override; bool Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) override; const AsmToken &Lex() override; void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; } bool isParsingInlineAsm() override { return ParsingInlineAsm; } bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs, SmallVectorImpl<std::pair<void *,bool> > &OpDecls, SmallVectorImpl<std::string> &Constraints, SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) override; bool parseExpression(const MCExpr *&Res); bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override; bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override; bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override; bool parseAbsoluteExpression(int64_t &Res) override; /// \brief Parse an identifier or string (as a quoted identifier) /// and set \p Res to the identifier contents. bool parseIdentifier(StringRef &Res) override; void eatToEndOfStatement() override; void checkForValidSection() override; /// } private: bool parseStatement(ParseStatementInfo &Info); void eatToEndOfLine(); bool parseCppHashLineFilenameComment(const SMLoc &L); void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, ArrayRef<MCAsmMacroParameter> Parameters); bool expandMacro(raw_svector_ostream &OS, StringRef Body, ArrayRef<MCAsmMacroParameter> Parameters, ArrayRef<MCAsmMacroArgument> A, const SMLoc &L); /// \brief Are macros enabled in the parser? bool areMacrosEnabled() {return MacrosEnabledFlag;} /// \brief Control a flag in the parser that enables or disables macros. void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;} /// \brief Lookup a previously defined macro. /// \param Name Macro name. /// \returns Pointer to macro. NULL if no such macro was defined. const MCAsmMacro* lookupMacro(StringRef Name); /// \brief Define a new macro with the given name and information. void defineMacro(StringRef Name, const MCAsmMacro& Macro); /// \brief Undefine a macro. If no such macro was defined, it's a no-op. void undefineMacro(StringRef Name); /// \brief Are we inside a macro instantiation? bool isInsideMacroInstantiation() {return !ActiveMacros.empty();} /// \brief Handle entry to macro instantiation. /// /// \param M The macro. /// \param NameLoc Instantiation location. bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc); /// \brief Handle exit from macro instantiation. void handleMacroExit(); /// \brief Extract AsmTokens for a macro argument. bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg); /// \brief Parse all macro arguments for a given macro. bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A); void printMacroInstantiations(); void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, ArrayRef<SMRange> Ranges = None) const { SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges); } static void DiagHandler(const SMDiagnostic &Diag, void *Context); /// \brief Enter the specified file. This returns true on failure. bool enterIncludeFile(const std::string &Filename); /// \brief Process the specified file for the .incbin directive. /// This returns true on failure. bool processIncbinFile(const std::string &Filename); /// \brief Reset the current lexer position to that given by \p Loc. The /// current token is not set; clients should ensure Lex() is called /// subsequently. /// /// \param InBuffer If not 0, should be the known buffer id that contains the /// location. void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0); /// \brief Parse up to the end of statement and a return the contents from the /// current token until the end of the statement; the current token on exit /// will be either the EndOfStatement or EOF. StringRef parseStringToEndOfStatement() override; /// \brief Parse until the end of a statement or a comma is encountered, /// return the contents from the current token up to the end or comma. StringRef parseStringToComma(); bool parseAssignment(StringRef Name, bool allow_redef, bool NoDeadStrip = false); bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc); bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc); bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc); bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc); // Generic (target and platform independent) directive parsing. enum DirectiveKind { DK_NO_DIRECTIVE, // Placeholder DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT, DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA, DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW, DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR, DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK, DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE, DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT, DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC, DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF, DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS, DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA, DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER, DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA, DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE, DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED, DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE, DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM, DK_SLEB128, DK_ULEB128, DK_ERR, DK_ERROR, DK_END }; /// \brief Maps directive name --> DirectiveKind enum, for /// directives parsed by this class. StringMap<DirectiveKind> DirectiveKindMap; // ".ascii", ".asciz", ".string" bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated); bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ... bool parseDirectiveOctaValue(); // ".octa" bool parseDirectiveRealValue(const fltSemantics &); // ".single", ... bool parseDirectiveFill(); // ".fill" bool parseDirectiveZero(); // ".zero" // ".set", ".equ", ".equiv" bool parseDirectiveSet(StringRef IDVal, bool allow_redef); bool parseDirectiveOrg(); // ".org" // ".align{,32}", ".p2align{,w,l}" bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize); // ".file", ".line", ".loc", ".stabs" bool parseDirectiveFile(SMLoc DirectiveLoc); bool parseDirectiveLine(); bool parseDirectiveLoc(); bool parseDirectiveStabs(); // .cfi directives bool parseDirectiveCFIRegister(SMLoc DirectiveLoc); bool parseDirectiveCFIWindowSave(); bool parseDirectiveCFISections(); bool parseDirectiveCFIStartProc(); bool parseDirectiveCFIEndProc(); bool parseDirectiveCFIDefCfaOffset(); bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc); bool parseDirectiveCFIAdjustCfaOffset(); bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc); bool parseDirectiveCFIOffset(SMLoc DirectiveLoc); bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc); bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality); bool parseDirectiveCFIRememberState(); bool parseDirectiveCFIRestoreState(); bool parseDirectiveCFISameValue(SMLoc DirectiveLoc); bool parseDirectiveCFIRestore(SMLoc DirectiveLoc); bool parseDirectiveCFIEscape(); bool parseDirectiveCFISignalFrame(); bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc); // macro directives bool parseDirectivePurgeMacro(SMLoc DirectiveLoc); bool parseDirectiveEndMacro(StringRef Directive); bool parseDirectiveMacro(SMLoc DirectiveLoc); bool parseDirectiveMacrosOnOff(StringRef Directive); // ".bundle_align_mode" bool parseDirectiveBundleAlignMode(); // ".bundle_lock" bool parseDirectiveBundleLock(); // ".bundle_unlock" bool parseDirectiveBundleUnlock(); // ".space", ".skip" bool parseDirectiveSpace(StringRef IDVal); // .sleb128 (Signed=true) and .uleb128 (Signed=false) bool parseDirectiveLEB128(bool Signed); /// \brief Parse a directive like ".globl" which /// accepts a single symbol (which should be a label or an external). bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr); bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm" bool parseDirectiveAbort(); // ".abort" bool parseDirectiveInclude(); // ".include" bool parseDirectiveIncbin(); // ".incbin" // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne" bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind); // ".ifb" or ".ifnb", depending on ExpectBlank. bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank); // ".ifc" or ".ifnc", depending on ExpectEqual. bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual); // ".ifeqs" bool parseDirectiveIfeqs(SMLoc DirectiveLoc); // ".ifdef" or ".ifndef", depending on expect_defined bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined); bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif" bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else" bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif bool parseEscapedString(std::string &Data) override; const MCExpr *applyModifierToExpr(const MCExpr *E, MCSymbolRefExpr::VariantKind Variant); // Macro-like directives MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc); void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, raw_svector_ostream &OS); bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive); bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp" bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc" bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr" // "_emit" or "__emit" bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info, size_t Len); // "align" bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info); // "end" bool parseDirectiveEnd(SMLoc DirectiveLoc); // ".err" or ".error" bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage); void initializeDirectiveKindMap(); }; } namespace llvm { extern MCAsmParserExtension *createDarwinAsmParser(); extern MCAsmParserExtension *createELFAsmParser(); extern MCAsmParserExtension *createCOFFAsmParser(); } enum { DEFAULT_ADDRSPACE = 0 }; AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out, const MCAsmInfo &_MAI) : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM), PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()), MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) { // Save the old handler. SavedDiagHandler = SrcMgr.getDiagHandler(); SavedDiagContext = SrcMgr.getDiagContext(); // Set our own handler which calls the saved handler. SrcMgr.setDiagHandler(DiagHandler, this); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); // Initialize the platform / file format parser. switch (_Ctx.getObjectFileInfo()->getObjectFileType()) { case MCObjectFileInfo::IsCOFF: PlatformParser = createCOFFAsmParser(); PlatformParser->Initialize(*this); break; case MCObjectFileInfo::IsMachO: PlatformParser = createDarwinAsmParser(); PlatformParser->Initialize(*this); IsDarwin = true; break; case MCObjectFileInfo::IsELF: PlatformParser = createELFAsmParser(); PlatformParser->Initialize(*this); break; } initializeDirectiveKindMap(); } AsmParser::~AsmParser() { assert((HadError || ActiveMacros.empty()) && "Unexpected active macro instantiation!"); // Destroy any macros. for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(), ie = MacroMap.end(); it != ie; ++it) delete it->getValue(); delete PlatformParser; } void AsmParser::printMacroInstantiations() { // Print the active macro instantiation stack. for (std::vector<MacroInstantiation *>::const_reverse_iterator it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it) printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note, "while in macro instantiation"); } void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) { printMessage(L, SourceMgr::DK_Note, Msg, Ranges); printMacroInstantiations(); } bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) { if (FatalAssemblerWarnings) return Error(L, Msg, Ranges); printMessage(L, SourceMgr::DK_Warning, Msg, Ranges); printMacroInstantiations(); return false; } bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) { HadError = true; printMessage(L, SourceMgr::DK_Error, Msg, Ranges); printMacroInstantiations(); return true; } bool AsmParser::enterIncludeFile(const std::string &Filename) { std::string IncludedFile; unsigned NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); if (!NewBuf) return true; CurBuffer = NewBuf; Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); return false; } /// Process the specified .incbin file by searching for it in the include paths /// then just emitting the byte contents of the file to the streamer. This /// returns true on failure. bool AsmParser::processIncbinFile(const std::string &Filename) { std::string IncludedFile; unsigned NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); if (!NewBuf) return true; // Pick up the bytes from the file and emit them. getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer()); return false; } void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) { CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), Loc.getPointer()); } const AsmToken &AsmParser::Lex() { const AsmToken *tok = &Lexer.Lex(); if (tok->is(AsmToken::Eof)) { // If this is the end of an included file, pop the parent file off the // include stack. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); if (ParentIncludeLoc != SMLoc()) { jumpToLoc(ParentIncludeLoc); tok = &Lexer.Lex(); } } if (tok->is(AsmToken::Error)) Error(Lexer.getErrLoc(), Lexer.getErr()); return *tok; } bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) { // Create the initial section, if requested. if (!NoInitialTextSection) Out.InitSections(); // Prime the lexer. Lex(); HadError = false; AsmCond StartingCondState = TheCondState; // If we are generating dwarf for assembly source files save the initial text // section and generate a .file directive. if (getContext().getGenDwarfForAssembly()) { MCSymbol *SectionStartSym = getContext().CreateTempSymbol(); getStreamer().EmitLabel(SectionStartSym); auto InsertResult = getContext().addGenDwarfSection( getStreamer().getCurrentSection().first); assert(InsertResult.second && ".text section should not have debug info yet"); InsertResult.first->second.first = SectionStartSym; getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective( 0, StringRef(), getContext().getMainFileName())); } // While we have input, parse each statement. while (Lexer.isNot(AsmToken::Eof)) { ParseStatementInfo Info; if (!parseStatement(Info)) continue; // We had an error, validate that one was emitted and recover by skipping to // the next line. assert(HadError && "Parse statement returned an error, but none emitted!"); eatToEndOfStatement(); } if (TheCondState.TheCond != StartingCondState.TheCond || TheCondState.Ignore != StartingCondState.Ignore) return TokError("unmatched .ifs or .elses"); // Check to see there are no empty DwarfFile slots. const auto &LineTables = getContext().getMCDwarfLineTables(); if (!LineTables.empty()) { unsigned Index = 0; for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) { if (File.Name.empty() && Index != 0) TokError("unassigned file number: " + Twine(Index) + " for .file directives"); ++Index; } } // Check to see that all assembler local symbols were actually defined. // Targets that don't do subsections via symbols may not want this, though, // so conservatively exclude them. Only do this if we're finalizing, though, // as otherwise we won't necessarilly have seen everything yet. if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) { const MCContext::SymbolTable &Symbols = getContext().getSymbols(); for (MCContext::SymbolTable::const_iterator i = Symbols.begin(), e = Symbols.end(); i != e; ++i) { MCSymbol *Sym = i->getValue(); // Variable symbols may not be marked as defined, so check those // explicitly. If we know it's a variable, we have a definition for // the purposes of this check. if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) // FIXME: We would really like to refer back to where the symbol was // first referenced for a source location. We need to add something // to track that. Currently, we just point to the end of the file. printMessage( getLexer().getLoc(), SourceMgr::DK_Error, "assembler local symbol '" + Sym->getName() + "' not defined"); } } // Finalize the output stream if there are no errors and if the client wants // us to. if (!HadError && !NoFinalize) Out.Finish(); return HadError; } void AsmParser::checkForValidSection() { if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) { TokError("expected section directive before assembly directive"); Out.InitSections(); } } /// \brief Throw away the rest of the line for testing purposes. void AsmParser::eatToEndOfStatement() { while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) Lex(); // Eat EOL. if (Lexer.is(AsmToken::EndOfStatement)) Lex(); } StringRef AsmParser::parseStringToEndOfStatement() { const char *Start = getTok().getLoc().getPointer(); while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) Lex(); const char *End = getTok().getLoc().getPointer(); return StringRef(Start, End - Start); } StringRef AsmParser::parseStringToComma() { const char *Start = getTok().getLoc().getPointer(); while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof)) Lex(); const char *End = getTok().getLoc().getPointer(); return StringRef(Start, End - Start); } /// \brief Parse a paren expression and return it. /// NOTE: This assumes the leading '(' has already been consumed. /// /// parenexpr ::= expr) /// bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) { if (parseExpression(Res)) return true; if (Lexer.isNot(AsmToken::RParen)) return TokError("expected ')' in parentheses expression"); EndLoc = Lexer.getTok().getEndLoc(); Lex(); return false; } /// \brief Parse a bracket expression and return it. /// NOTE: This assumes the leading '[' has already been consumed. /// /// bracketexpr ::= expr] /// bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) { if (parseExpression(Res)) return true; if (Lexer.isNot(AsmToken::RBrac)) return TokError("expected ']' in brackets expression"); EndLoc = Lexer.getTok().getEndLoc(); Lex(); return false; } /// \brief Parse a primary expression and return it. /// primaryexpr ::= (parenexpr /// primaryexpr ::= symbol /// primaryexpr ::= number /// primaryexpr ::= '.' /// primaryexpr ::= ~,+,- primaryexpr bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) { SMLoc FirstTokenLoc = getLexer().getLoc(); AsmToken::TokenKind FirstTokenKind = Lexer.getKind(); switch (FirstTokenKind) { default: return TokError("unknown token in expression"); // If we have an error assume that we've already handled it. case AsmToken::Error: return true; case AsmToken::Exclaim: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::CreateLNot(Res, getContext()); return false; case AsmToken::Dollar: case AsmToken::At: case AsmToken::String: case AsmToken::Identifier: { StringRef Identifier; if (parseIdentifier(Identifier)) { if (FirstTokenKind == AsmToken::Dollar) { if (Lexer.getMAI().getDollarIsPC()) { // This is a '$' reference, which references the current PC. Emit a // temporary label to the streamer and refer to it. MCSymbol *Sym = Ctx.CreateTempSymbol(); Out.EmitLabel(Sym); Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext()); EndLoc = FirstTokenLoc; return false; } return Error(FirstTokenLoc, "invalid token in expression"); } } // Parse symbol variant std::pair<StringRef, StringRef> Split; if (!MAI.useParensForSymbolVariant()) { if (FirstTokenKind == AsmToken::String) { if (Lexer.is(AsmToken::At)) { Lexer.Lex(); // eat @ SMLoc AtLoc = getLexer().getLoc(); StringRef VName; if (parseIdentifier(VName)) return Error(AtLoc, "expected symbol variant after '@'"); Split = std::make_pair(Identifier, VName); } } else { Split = Identifier.split('@'); } } else if (Lexer.is(AsmToken::LParen)) { Lexer.Lex(); // eat ( StringRef VName; parseIdentifier(VName); if (Lexer.isNot(AsmToken::RParen)) { return Error(Lexer.getTok().getLoc(), "unexpected token in variant, expected ')'"); } Lexer.Lex(); // eat ) Split = std::make_pair(Identifier, VName); } EndLoc = SMLoc::getFromPointer(Identifier.end()); // This is a symbol reference. StringRef SymbolName = Identifier; MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; // Lookup the symbol variant if used. if (Split.second.size()) { Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); if (Variant != MCSymbolRefExpr::VK_Invalid) { SymbolName = Split.first; } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) { Variant = MCSymbolRefExpr::VK_None; } else { return Error(SMLoc::getFromPointer(Split.second.begin()), "invalid variant '" + Split.second + "'"); } } MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName); // If this is an absolute variable reference, substitute it now to preserve // semantics in the face of reassignment. if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) { if (Variant) return Error(EndLoc, "unexpected modifier on variable reference"); Res = Sym->getVariableValue(); return false; } // Otherwise create a symbol ref. Res = MCSymbolRefExpr::Create(Sym, Variant, getContext()); return false; } case AsmToken::BigNum: return TokError("literal value out of range for directive"); case AsmToken::Integer: { SMLoc Loc = getTok().getLoc(); int64_t IntVal = getTok().getIntVal(); Res = MCConstantExpr::Create(IntVal, getContext()); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat token. // Look for 'b' or 'f' following an Integer as a directional label if (Lexer.getKind() == AsmToken::Identifier) { StringRef IDVal = getTok().getString(); // Lookup the symbol variant if used. std::pair<StringRef, StringRef> Split = IDVal.split('@'); MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; if (Split.first.size() != IDVal.size()) { Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); if (Variant == MCSymbolRefExpr::VK_Invalid) return TokError("invalid variant '" + Split.second + "'"); IDVal = Split.first; } if (IDVal == "f" || IDVal == "b") { MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b"); Res = MCSymbolRefExpr::Create(Sym, Variant, getContext()); if (IDVal == "b" && Sym->isUndefined()) return Error(Loc, "invalid reference to undefined symbol"); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat identifier. } } return false; } case AsmToken::Real: { APFloat RealVal(APFloat::IEEEdouble, getTok().getString()); uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue(); Res = MCConstantExpr::Create(IntVal, getContext()); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat token. return false; } case AsmToken::Dot: { // This is a '.' reference, which references the current PC. Emit a // temporary label to the streamer and refer to it. MCSymbol *Sym = Ctx.CreateTempSymbol(); Out.EmitLabel(Sym); Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext()); EndLoc = Lexer.getTok().getEndLoc(); Lex(); // Eat identifier. return false; } case AsmToken::LParen: Lex(); // Eat the '('. return parseParenExpr(Res, EndLoc); case AsmToken::LBrac: if (!PlatformParser->HasBracketExpressions()) return TokError("brackets expression not supported on this target"); Lex(); // Eat the '['. return parseBracketExpr(Res, EndLoc); case AsmToken::Minus: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::CreateMinus(Res, getContext()); return false; case AsmToken::Plus: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::CreatePlus(Res, getContext()); return false; case AsmToken::Tilde: Lex(); // Eat the operator. if (parsePrimaryExpr(Res, EndLoc)) return true; Res = MCUnaryExpr::CreateNot(Res, getContext()); return false; } } bool AsmParser::parseExpression(const MCExpr *&Res) { SMLoc EndLoc; return parseExpression(Res, EndLoc); } const MCExpr * AsmParser::applyModifierToExpr(const MCExpr *E, MCSymbolRefExpr::VariantKind Variant) { // Ask the target implementation about this expression first. const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx); if (NewE) return NewE; // Recurse over the given expression, rebuilding it to apply the given variant // if there is exactly one symbol. switch (E->getKind()) { case MCExpr::Target: case MCExpr::Constant: return nullptr; case MCExpr::SymbolRef: { const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E); if (SRE->getKind() != MCSymbolRefExpr::VK_None) { TokError("invalid variant on expression '" + getTok().getIdentifier() + "' (already modified)"); return E; } return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext()); } case MCExpr::Unary: { const MCUnaryExpr *UE = cast<MCUnaryExpr>(E); const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant); if (!Sub) return nullptr; return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext()); } case MCExpr::Binary: { const MCBinaryExpr *BE = cast<MCBinaryExpr>(E); const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant); const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant); if (!LHS && !RHS) return nullptr; if (!LHS) LHS = BE->getLHS(); if (!RHS) RHS = BE->getRHS(); return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext()); } } llvm_unreachable("Invalid expression kind!"); } /// \brief Parse an expression and return it. /// /// expr ::= expr &&,|| expr -> lowest. /// expr ::= expr |,^,&,! expr /// expr ::= expr ==,!=,<>,<,<=,>,>= expr /// expr ::= expr <<,>> expr /// expr ::= expr +,- expr /// expr ::= expr *,/,% expr -> highest. /// expr ::= primaryexpr /// bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) { // Parse the expression. Res = nullptr; if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc)) return true; // As a special case, we support 'a op b @ modifier' by rewriting the // expression to include the modifier. This is inefficient, but in general we // expect users to use 'a@modifier op b'. if (Lexer.getKind() == AsmToken::At) { Lex(); if (Lexer.isNot(AsmToken::Identifier)) return TokError("unexpected symbol modifier following '@'"); MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier()); if (Variant == MCSymbolRefExpr::VK_Invalid) return TokError("invalid variant '" + getTok().getIdentifier() + "'"); const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant); if (!ModifiedRes) { return TokError("invalid modifier '" + getTok().getIdentifier() + "' (no symbols present)"); } Res = ModifiedRes; Lex(); } // Try to constant fold it up front, if possible. int64_t Value; if (Res->EvaluateAsAbsolute(Value)) Res = MCConstantExpr::Create(Value, getContext()); return false; } bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) { Res = nullptr; return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc); } bool AsmParser::parseAbsoluteExpression(int64_t &Res) { const MCExpr *Expr; SMLoc StartLoc = Lexer.getLoc(); if (parseExpression(Expr)) return true; if (!Expr->EvaluateAsAbsolute(Res)) return Error(StartLoc, "expected absolute expression"); return false; } static unsigned getBinOpPrecedence(AsmToken::TokenKind K, MCBinaryExpr::Opcode &Kind) { switch (K) { default: return 0; // not a binop. // Lowest Precedence: &&, || case AsmToken::AmpAmp: Kind = MCBinaryExpr::LAnd; return 1; case AsmToken::PipePipe: Kind = MCBinaryExpr::LOr; return 1; // Low Precedence: |, &, ^ // // FIXME: gas seems to support '!' as an infix operator? case AsmToken::Pipe: Kind = MCBinaryExpr::Or; return 2; case AsmToken::Caret: Kind = MCBinaryExpr::Xor; return 2; case AsmToken::Amp: Kind = MCBinaryExpr::And; return 2; // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >= case AsmToken::EqualEqual: Kind = MCBinaryExpr::EQ; return 3; case AsmToken::ExclaimEqual: case AsmToken::LessGreater: Kind = MCBinaryExpr::NE; return 3; case AsmToken::Less: Kind = MCBinaryExpr::LT; return 3; case AsmToken::LessEqual: Kind = MCBinaryExpr::LTE; return 3; case AsmToken::Greater: Kind = MCBinaryExpr::GT; return 3; case AsmToken::GreaterEqual: Kind = MCBinaryExpr::GTE; return 3; // Intermediate Precedence: <<, >> case AsmToken::LessLess: Kind = MCBinaryExpr::Shl; return 4; case AsmToken::GreaterGreater: Kind = MCBinaryExpr::Shr; return 4; // High Intermediate Precedence: +, - case AsmToken::Plus: Kind = MCBinaryExpr::Add; return 5; case AsmToken::Minus: Kind = MCBinaryExpr::Sub; return 5; // Highest Precedence: *, /, % case AsmToken::Star: Kind = MCBinaryExpr::Mul; return 6; case AsmToken::Slash: Kind = MCBinaryExpr::Div; return 6; case AsmToken::Percent: Kind = MCBinaryExpr::Mod; return 6; } } /// \brief Parse all binary operators with precedence >= 'Precedence'. /// Res contains the LHS of the expression on input. bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc) { while (1) { MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add; unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind); // If the next token is lower precedence than we are allowed to eat, return // successfully with what we ate already. if (TokPrec < Precedence) return false; Lex(); // Eat the next primary expression. const MCExpr *RHS; if (parsePrimaryExpr(RHS, EndLoc)) return true; // If BinOp binds less tightly with RHS than the operator after RHS, let // the pending operator take RHS as its LHS. MCBinaryExpr::Opcode Dummy; unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy); if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc)) return true; // Merge LHS and RHS according to operator. Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext()); } } /// ParseStatement: /// ::= EndOfStatement /// ::= Label* Directive ...Operands... EndOfStatement /// ::= Label* Identifier OperandList* EndOfStatement bool AsmParser::parseStatement(ParseStatementInfo &Info) { if (Lexer.is(AsmToken::EndOfStatement)) { Out.AddBlankLine(); Lex(); return false; } // Statements always start with an identifier or are a full line comment. AsmToken ID = getTok(); SMLoc IDLoc = ID.getLoc(); StringRef IDVal; int64_t LocalLabelVal = -1; // A full line comment is a '#' as the first token. if (Lexer.is(AsmToken::Hash)) return parseCppHashLineFilenameComment(IDLoc); // Allow an integer followed by a ':' as a directional local label. if (Lexer.is(AsmToken::Integer)) { LocalLabelVal = getTok().getIntVal(); if (LocalLabelVal < 0) { if (!TheCondState.Ignore) return TokError("unexpected token at start of statement"); IDVal = ""; } else { IDVal = getTok().getString(); Lex(); // Consume the integer token to be used as an identifier token. if (Lexer.getKind() != AsmToken::Colon) { if (!TheCondState.Ignore) return TokError("unexpected token at start of statement"); } } } else if (Lexer.is(AsmToken::Dot)) { // Treat '.' as a valid identifier in this context. Lex(); IDVal = "."; } else if (parseIdentifier(IDVal)) { if (!TheCondState.Ignore) return TokError("unexpected token at start of statement"); IDVal = ""; } // Handle conditional assembly here before checking for skipping. We // have to do this so that .endif isn't skipped in a ".if 0" block for // example. StringMap<DirectiveKind>::const_iterator DirKindIt = DirectiveKindMap.find(IDVal); DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE : DirKindIt->getValue(); switch (DirKind) { default: break; case DK_IF: case DK_IFEQ: case DK_IFGE: case DK_IFGT: case DK_IFLE: case DK_IFLT: case DK_IFNE: return parseDirectiveIf(IDLoc, DirKind); case DK_IFB: return parseDirectiveIfb(IDLoc, true); case DK_IFNB: return parseDirectiveIfb(IDLoc, false); case DK_IFC: return parseDirectiveIfc(IDLoc, true); case DK_IFEQS: return parseDirectiveIfeqs(IDLoc); case DK_IFNC: return parseDirectiveIfc(IDLoc, false); case DK_IFDEF: return parseDirectiveIfdef(IDLoc, true); case DK_IFNDEF: case DK_IFNOTDEF: return parseDirectiveIfdef(IDLoc, false); case DK_ELSEIF: return parseDirectiveElseIf(IDLoc); case DK_ELSE: return parseDirectiveElse(IDLoc); case DK_ENDIF: return parseDirectiveEndIf(IDLoc); } // Ignore the statement if in the middle of inactive conditional // (e.g. ".if 0"). if (TheCondState.Ignore) { eatToEndOfStatement(); return false; } // FIXME: Recurse on local labels? // See what kind of statement we have. switch (Lexer.getKind()) { case AsmToken::Colon: { checkForValidSection(); // identifier ':' -> Label. Lex(); // Diagnose attempt to use '.' as a label. if (IDVal == ".") return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label"); // Diagnose attempt to use a variable as a label. // // FIXME: Diagnostics. Note the location of the definition as a label. // FIXME: This doesn't diagnose assignment to a symbol which has been // implicitly marked as external. MCSymbol *Sym; if (LocalLabelVal == -1) Sym = getContext().GetOrCreateSymbol(IDVal); else Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal); if (!Sym->isUndefined() || Sym->isVariable()) return Error(IDLoc, "invalid symbol redefinition"); // Emit the label. if (!ParsingInlineAsm) Out.EmitLabel(Sym); // If we are generating dwarf for assembly source files then gather the // info to make a dwarf label entry for this label if needed. if (getContext().getGenDwarfForAssembly()) MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(), IDLoc); getTargetParser().onLabelParsed(Sym); // Consume any end of statement token, if present, to avoid spurious // AddBlankLine calls(). if (Lexer.is(AsmToken::EndOfStatement)) { Lex(); if (Lexer.is(AsmToken::Eof)) return false; } return false; } case AsmToken::Equal: // identifier '=' ... -> assignment statement Lex(); return parseAssignment(IDVal, true); default: // Normal instruction or directive. break; } // If macros are enabled, check to see if this is a macro instantiation. if (areMacrosEnabled()) if (const MCAsmMacro *M = lookupMacro(IDVal)) { return handleMacroEntry(M, IDLoc); } // Otherwise, we have a normal instruction or directive. // Directives start with "." if (IDVal[0] == '.' && IDVal != ".") { // There are several entities interested in parsing directives: // // 1. The target-specific assembly parser. Some directives are target // specific or may potentially behave differently on certain targets. // 2. Asm parser extensions. For example, platform-specific parsers // (like the ELF parser) register themselves as extensions. // 3. The generic directive parser implemented by this class. These are // all the directives that behave in a target and platform independent // manner, or at least have a default behavior that's shared between // all targets and platforms. // First query the target-specific parser. It will return 'true' if it // isn't interested in this directive. if (!getTargetParser().ParseDirective(ID)) return false; // Next, check the extension directive map to see if any extension has // registered itself to parse this directive. std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = ExtensionDirectiveMap.lookup(IDVal); if (Handler.first) return (*Handler.second)(Handler.first, IDVal, IDLoc); // Finally, if no one else is interested in this directive, it must be // generic and familiar to this class. switch (DirKind) { default: break; case DK_SET: case DK_EQU: return parseDirectiveSet(IDVal, true); case DK_EQUIV: return parseDirectiveSet(IDVal, false); case DK_ASCII: return parseDirectiveAscii(IDVal, false); case DK_ASCIZ: case DK_STRING: return parseDirectiveAscii(IDVal, true); case DK_BYTE: return parseDirectiveValue(1); case DK_SHORT: case DK_VALUE: case DK_2BYTE: return parseDirectiveValue(2); case DK_LONG: case DK_INT: case DK_4BYTE: return parseDirectiveValue(4); case DK_QUAD: case DK_8BYTE: return parseDirectiveValue(8); case DK_OCTA: return parseDirectiveOctaValue(); case DK_SINGLE: case DK_FLOAT: return parseDirectiveRealValue(APFloat::IEEEsingle); case DK_DOUBLE: return parseDirectiveRealValue(APFloat::IEEEdouble); case DK_ALIGN: { bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); return parseDirectiveAlign(IsPow2, /*ExprSize=*/1); } case DK_ALIGN32: { bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); return parseDirectiveAlign(IsPow2, /*ExprSize=*/4); } case DK_BALIGN: return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1); case DK_BALIGNW: return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2); case DK_BALIGNL: return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4); case DK_P2ALIGN: return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1); case DK_P2ALIGNW: return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2); case DK_P2ALIGNL: return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4); case DK_ORG: return parseDirectiveOrg(); case DK_FILL: return parseDirectiveFill(); case DK_ZERO: return parseDirectiveZero(); case DK_EXTERN: eatToEndOfStatement(); // .extern is the default, ignore it. return false; case DK_GLOBL: case DK_GLOBAL: return parseDirectiveSymbolAttribute(MCSA_Global); case DK_LAZY_REFERENCE: return parseDirectiveSymbolAttribute(MCSA_LazyReference); case DK_NO_DEAD_STRIP: return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip); case DK_SYMBOL_RESOLVER: return parseDirectiveSymbolAttribute(MCSA_SymbolResolver); case DK_PRIVATE_EXTERN: return parseDirectiveSymbolAttribute(MCSA_PrivateExtern); case DK_REFERENCE: return parseDirectiveSymbolAttribute(MCSA_Reference); case DK_WEAK_DEFINITION: return parseDirectiveSymbolAttribute(MCSA_WeakDefinition); case DK_WEAK_REFERENCE: return parseDirectiveSymbolAttribute(MCSA_WeakReference); case DK_WEAK_DEF_CAN_BE_HIDDEN: return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate); case DK_COMM: case DK_COMMON: return parseDirectiveComm(/*IsLocal=*/false); case DK_LCOMM: return parseDirectiveComm(/*IsLocal=*/true); case DK_ABORT: return parseDirectiveAbort(); case DK_INCLUDE: return parseDirectiveInclude(); case DK_INCBIN: return parseDirectiveIncbin(); case DK_CODE16: case DK_CODE16GCC: return TokError(Twine(IDVal) + " not supported yet"); case DK_REPT: return parseDirectiveRept(IDLoc, IDVal); case DK_IRP: return parseDirectiveIrp(IDLoc); case DK_IRPC: return parseDirectiveIrpc(IDLoc); case DK_ENDR: return parseDirectiveEndr(IDLoc); case DK_BUNDLE_ALIGN_MODE: return parseDirectiveBundleAlignMode(); case DK_BUNDLE_LOCK: return parseDirectiveBundleLock(); case DK_BUNDLE_UNLOCK: return parseDirectiveBundleUnlock(); case DK_SLEB128: return parseDirectiveLEB128(true); case DK_ULEB128: return parseDirectiveLEB128(false); case DK_SPACE: case DK_SKIP: return parseDirectiveSpace(IDVal); case DK_FILE: return parseDirectiveFile(IDLoc); case DK_LINE: return parseDirectiveLine(); case DK_LOC: return parseDirectiveLoc(); case DK_STABS: return parseDirectiveStabs(); case DK_CFI_SECTIONS: return parseDirectiveCFISections(); case DK_CFI_STARTPROC: return parseDirectiveCFIStartProc(); case DK_CFI_ENDPROC: return parseDirectiveCFIEndProc(); case DK_CFI_DEF_CFA: return parseDirectiveCFIDefCfa(IDLoc); case DK_CFI_DEF_CFA_OFFSET: return parseDirectiveCFIDefCfaOffset(); case DK_CFI_ADJUST_CFA_OFFSET: return parseDirectiveCFIAdjustCfaOffset(); case DK_CFI_DEF_CFA_REGISTER: return parseDirectiveCFIDefCfaRegister(IDLoc); case DK_CFI_OFFSET: return parseDirectiveCFIOffset(IDLoc); case DK_CFI_REL_OFFSET: return parseDirectiveCFIRelOffset(IDLoc); case DK_CFI_PERSONALITY: return parseDirectiveCFIPersonalityOrLsda(true); case DK_CFI_LSDA: return parseDirectiveCFIPersonalityOrLsda(false); case DK_CFI_REMEMBER_STATE: return parseDirectiveCFIRememberState(); case DK_CFI_RESTORE_STATE: return parseDirectiveCFIRestoreState(); case DK_CFI_SAME_VALUE: return parseDirectiveCFISameValue(IDLoc); case DK_CFI_RESTORE: return parseDirectiveCFIRestore(IDLoc); case DK_CFI_ESCAPE: return parseDirectiveCFIEscape(); case DK_CFI_SIGNAL_FRAME: return parseDirectiveCFISignalFrame(); case DK_CFI_UNDEFINED: return parseDirectiveCFIUndefined(IDLoc); case DK_CFI_REGISTER: return parseDirectiveCFIRegister(IDLoc); case DK_CFI_WINDOW_SAVE: return parseDirectiveCFIWindowSave(); case DK_MACROS_ON: case DK_MACROS_OFF: return parseDirectiveMacrosOnOff(IDVal); case DK_MACRO: return parseDirectiveMacro(IDLoc); case DK_ENDM: case DK_ENDMACRO: return parseDirectiveEndMacro(IDVal); case DK_PURGEM: return parseDirectivePurgeMacro(IDLoc); case DK_END: return parseDirectiveEnd(IDLoc); case DK_ERR: return parseDirectiveError(IDLoc, false); case DK_ERROR: return parseDirectiveError(IDLoc, true); } return Error(IDLoc, "unknown directive"); } // __asm _emit or __asm __emit if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" || IDVal == "_EMIT" || IDVal == "__EMIT")) return parseDirectiveMSEmit(IDLoc, Info, IDVal.size()); // __asm align if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN")) return parseDirectiveMSAlign(IDLoc, Info); checkForValidSection(); // Canonicalize the opcode to lower case. std::string OpcodeStr = IDVal.lower(); ParseInstructionInfo IInfo(Info.AsmRewrites); bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc, Info.ParsedOperands); Info.ParseError = HadError; // Dump the parsed representation, if requested. if (getShowParsedOperands()) { SmallString<256> Str; raw_svector_ostream OS(Str); OS << "parsed instruction: ["; for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) { if (i != 0) OS << ", "; Info.ParsedOperands[i]->print(OS); } OS << "]"; printMessage(IDLoc, SourceMgr::DK_Note, OS.str()); } // If we are generating dwarf for the current section then generate a .loc // directive for the instruction. if (!HadError && getContext().getGenDwarfForAssembly() && getContext().getGenDwarfSectionSyms().count( getStreamer().getCurrentSection().first)) { unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer); // If we previously parsed a cpp hash file line comment then make sure the // current Dwarf File is for the CppHashFilename if not then emit the // Dwarf File table for it and adjust the line number for the .loc. if (CppHashFilename.size() != 0) { unsigned FileNumber = getStreamer().EmitDwarfFileDirective( 0, StringRef(), CppHashFilename); getContext().setGenDwarfFileNumber(FileNumber); // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's // cache with the different Loc from the call above we save the last // info we queried here with SrcMgr.FindLineNumber(). unsigned CppHashLocLineNo; if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf) CppHashLocLineNo = LastQueryLine; else { CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf); LastQueryLine = CppHashLocLineNo; LastQueryIDLoc = CppHashLoc; LastQueryBuffer = CppHashBuf; } Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo); } getStreamer().EmitDwarfLocDirective( getContext().getGenDwarfFileNumber(), Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0, StringRef()); } // If parsing succeeded, match the instruction. if (!HadError) { unsigned ErrorInfo; getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo, ParsingInlineAsm); } // Don't skip the rest of the line, the instruction parser is responsible for // that. return false; } /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line /// since they may not be able to be tokenized to get to the end of line token. void AsmParser::eatToEndOfLine() { if (!Lexer.is(AsmToken::EndOfStatement)) Lexer.LexUntilEndOfLine(); // Eat EOL. Lex(); } /// parseCppHashLineFilenameComment as this: /// ::= # number "filename" /// or just as a full line comment if it doesn't have a number and a string. bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) { Lex(); // Eat the hash token. if (getLexer().isNot(AsmToken::Integer)) { // Consume the line since in cases it is not a well-formed line directive, // as if were simply a full line comment. eatToEndOfLine(); return false; } int64_t LineNumber = getTok().getIntVal(); Lex(); if (getLexer().isNot(AsmToken::String)) { eatToEndOfLine(); return false; } StringRef Filename = getTok().getString(); // Get rid of the enclosing quotes. Filename = Filename.substr(1, Filename.size() - 2); // Save the SMLoc, Filename and LineNumber for later use by diagnostics. CppHashLoc = L; CppHashFilename = Filename; CppHashLineNumber = LineNumber; CppHashBuf = CurBuffer; // Ignore any trailing characters, they're just comment. eatToEndOfLine(); return false; } /// \brief will use the last parsed cpp hash line filename comment /// for the Filename and LineNo if any in the diagnostic. void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) { const AsmParser *Parser = static_cast<const AsmParser *>(Context); raw_ostream &OS = errs(); const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr(); const SMLoc &DiagLoc = Diag.getLoc(); unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); unsigned CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc); // Like SourceMgr::printMessage() we need to print the include stack if any // before printing the message. unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); if (!Parser->SavedDiagHandler && DiagCurBuffer && DiagCurBuffer != DiagSrcMgr.getMainFileID()) { SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer); DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS); } // If we have not parsed a cpp hash line filename comment or the source // manager changed or buffer changed (like in a nested include) then just // print the normal diagnostic using its Filename and LineNo. if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr || DiagBuf != CppHashBuf) { if (Parser->SavedDiagHandler) Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext); else Diag.print(nullptr, OS); return; } // Use the CppHashFilename and calculate a line number based on the // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for // the diagnostic. const std::string &Filename = Parser->CppHashFilename; int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf); int CppHashLocLineNo = Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf); int LineNo = Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo); SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo, Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(), Diag.getLineContents(), Diag.getRanges()); if (Parser->SavedDiagHandler) Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext); else NewDiag.print(nullptr, OS); } // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The // difference being that that function accepts '@' as part of identifiers and // we can't do that. AsmLexer.cpp should probably be changed to handle // '@' as a special case when needed. static bool isIdentifierChar(char c) { return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' || c == '.'; } bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, ArrayRef<MCAsmMacroParameter> Parameters, ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) { unsigned NParameters = Parameters.size(); bool HasVararg = NParameters ? Parameters.back().Vararg : false; if ((!IsDarwin || NParameters != 0) && NParameters != A.size()) return Error(L, "Wrong number of arguments"); // A macro without parameters is handled differently on Darwin: // gas accepts no arguments and does no substitutions while (!Body.empty()) { // Scan for the next substitution. std::size_t End = Body.size(), Pos = 0; for (; Pos != End; ++Pos) { // Check for a substitution or escape. if (IsDarwin && !NParameters) { // This macro has no parameters, look for $0, $1, etc. if (Body[Pos] != '$' || Pos + 1 == End) continue; char Next = Body[Pos + 1]; if (Next == '$' || Next == 'n' || isdigit(static_cast<unsigned char>(Next))) break; } else { // This macro has parameters, look for \foo, \bar, etc. if (Body[Pos] == '\\' && Pos + 1 != End) break; } } // Add the prefix. OS << Body.slice(0, Pos); // Check if we reached the end. if (Pos == End) break; if (IsDarwin && !NParameters) { switch (Body[Pos + 1]) { // $$ => $ case '$': OS << '$'; break; // $n => number of arguments case 'n': OS << A.size(); break; // $[0-9] => argument default: { // Missing arguments are ignored. unsigned Index = Body[Pos + 1] - '0'; if (Index >= A.size()) break; // Otherwise substitute with the token values, with spaces eliminated. for (MCAsmMacroArgument::const_iterator it = A[Index].begin(), ie = A[Index].end(); it != ie; ++it) OS << it->getString(); break; } } Pos += 2; } else { unsigned I = Pos + 1; while (isIdentifierChar(Body[I]) && I + 1 != End) ++I; const char *Begin = Body.data() + Pos + 1; StringRef Argument(Begin, I - (Pos + 1)); unsigned Index = 0; for (; Index < NParameters; ++Index) if (Parameters[Index].Name == Argument) break; if (Index == NParameters) { if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') Pos += 3; else { OS << '\\' << Argument; Pos = I; } } else { bool VarargParameter = HasVararg && Index == (NParameters - 1); for (MCAsmMacroArgument::const_iterator it = A[Index].begin(), ie = A[Index].end(); it != ie; ++it) // We expect no quotes around the string's contents when // parsing for varargs. if (it->getKind() != AsmToken::String || VarargParameter) OS << it->getString(); else OS << it->getStringContents(); Pos += 1 + Argument.size(); } } // Update the scan point. Body = Body.substr(Pos); } return false; } MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL, MemoryBuffer *I) : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL) {} static bool isOperator(AsmToken::TokenKind kind) { switch (kind) { default: return false; case AsmToken::Plus: case AsmToken::Minus: case AsmToken::Tilde: case AsmToken::Slash: case AsmToken::Star: case AsmToken::Dot: case AsmToken::Equal: case AsmToken::EqualEqual: case AsmToken::Pipe: case AsmToken::PipePipe: case AsmToken::Caret: case AsmToken::Amp: case AsmToken::AmpAmp: case AsmToken::Exclaim: case AsmToken::ExclaimEqual: case AsmToken::Percent: case AsmToken::Less: case AsmToken::LessEqual: case AsmToken::LessLess: case AsmToken::LessGreater: case AsmToken::Greater: case AsmToken::GreaterEqual: case AsmToken::GreaterGreater: return true; } } namespace { class AsmLexerSkipSpaceRAII { public: AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) { Lexer.setSkipSpace(SkipSpace); } ~AsmLexerSkipSpaceRAII() { Lexer.setSkipSpace(true); } private: AsmLexer &Lexer; }; } bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { if (Vararg) { if (Lexer.isNot(AsmToken::EndOfStatement)) { StringRef Str = parseStringToEndOfStatement(); MA.push_back(AsmToken(AsmToken::String, Str)); } return false; } unsigned ParenLevel = 0; unsigned AddTokens = 0; // Darwin doesn't use spaces to delmit arguments. AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); for (;;) { if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) return TokError("unexpected token in macro instantiation"); if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) break; if (Lexer.is(AsmToken::Space)) { Lex(); // Eat spaces // Spaces can delimit parameters, but could also be part an expression. // If the token after a space is an operator, add the token and the next // one into this argument if (!IsDarwin) { if (isOperator(Lexer.getKind())) { // Check to see whether the token is used as an operator, // or part of an identifier const char *NextChar = getTok().getEndLoc().getPointer(); if (*NextChar == ' ') AddTokens = 2; } if (!AddTokens && ParenLevel == 0) { break; } } } // handleMacroEntry relies on not advancing the lexer here // to be able to fill in the remaining default parameter values if (Lexer.is(AsmToken::EndOfStatement)) break; // Adjust the current parentheses level. if (Lexer.is(AsmToken::LParen)) ++ParenLevel; else if (Lexer.is(AsmToken::RParen) && ParenLevel) --ParenLevel; // Append the token to the current argument list. MA.push_back(getTok()); if (AddTokens) AddTokens--; Lex(); } if (ParenLevel != 0) return TokError("unbalanced parentheses in macro argument"); return false; } // Parse the macro instantiation arguments. bool AsmParser::parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) { const unsigned NParameters = M ? M->Parameters.size() : 0; bool NamedParametersFound = false; SmallVector<SMLoc, 4> FALocs; A.resize(NParameters); FALocs.resize(NParameters); // Parse two kinds of macro invocations: // - macros defined without any parameters accept an arbitrary number of them // - macros defined with parameters accept at most that many of them bool HasVararg = NParameters ? M->Parameters.back().Vararg : false; for (unsigned Parameter = 0; !NParameters || Parameter < NParameters; ++Parameter) { SMLoc IDLoc = Lexer.getLoc(); MCAsmMacroParameter FA; if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) { if (parseIdentifier(FA.Name)) { Error(IDLoc, "invalid argument identifier for formal argument"); eatToEndOfStatement(); return true; } if (!Lexer.is(AsmToken::Equal)) { TokError("expected '=' after formal parameter identifier"); eatToEndOfStatement(); return true; } Lex(); NamedParametersFound = true; } if (NamedParametersFound && FA.Name.empty()) { Error(IDLoc, "cannot mix positional and keyword arguments"); eatToEndOfStatement(); return true; } bool Vararg = HasVararg && Parameter == (NParameters - 1); if (parseMacroArgument(FA.Value, Vararg)) return true; unsigned PI = Parameter; if (!FA.Name.empty()) { unsigned FAI = 0; for (FAI = 0; FAI < NParameters; ++FAI) if (M->Parameters[FAI].Name == FA.Name) break; if (FAI >= NParameters) { assert(M && "expected macro to be defined"); Error(IDLoc, "parameter named '" + FA.Name + "' does not exist for macro '" + M->Name + "'"); return true; } PI = FAI; } if (!FA.Value.empty()) { if (A.size() <= PI) A.resize(PI + 1); A[PI] = FA.Value; if (FALocs.size() <= PI) FALocs.resize(PI + 1); FALocs[PI] = Lexer.getLoc(); } // At the end of the statement, fill in remaining arguments that have // default values. If there aren't any, then the next argument is // required but missing if (Lexer.is(AsmToken::EndOfStatement)) { bool Failure = false; for (unsigned FAI = 0; FAI < NParameters; ++FAI) { if (A[FAI].empty()) { if (M->Parameters[FAI].Required) { Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(), "missing value for required parameter " "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'"); Failure = true; } if (!M->Parameters[FAI].Value.empty()) A[FAI] = M->Parameters[FAI].Value; } } return Failure; } if (Lexer.is(AsmToken::Comma)) Lex(); } return TokError("too many positional arguments"); } const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) { StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name); return (I == MacroMap.end()) ? nullptr : I->getValue(); } void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) { MacroMap[Name] = new MCAsmMacro(Macro); } void AsmParser::undefineMacro(StringRef Name) { StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name); if (I != MacroMap.end()) { delete I->getValue(); MacroMap.erase(I); } } bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) { // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate // this, although we should protect against infinite loops. if (ActiveMacros.size() == 20) return TokError("macros cannot be nested more than 20 levels deep"); MCAsmMacroArguments A; if (parseMacroArguments(M, A)) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; StringRef Body = M->Body; raw_svector_ostream OS(Buf); if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc())) return true; // We include the .endmacro in the buffer as our cue to exit the macro // instantiation. OS << ".endmacro\n"; MemoryBuffer *Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); // Create the macro instantiation object and add to the current macro // instantiation stack. MacroInstantiation *MI = new MacroInstantiation( M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation); ActiveMacros.push_back(MI); // Jump to the macro instantiation and prime the lexer. CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc()); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); Lex(); return false; } void AsmParser::handleMacroExit() { // Jump to the EndOfStatement we should return to, and consume it. jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer); Lex(); // Pop the instantiation entry. delete ActiveMacros.back(); ActiveMacros.pop_back(); } static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) { switch (Value->getKind()) { case MCExpr::Binary: { const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value); return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS()); } case MCExpr::Target: case MCExpr::Constant: return false; case MCExpr::SymbolRef: { const MCSymbol &S = static_cast<const MCSymbolRefExpr *>(Value)->getSymbol(); if (S.isVariable()) return isUsedIn(Sym, S.getVariableValue()); return &S == Sym; } case MCExpr::Unary: return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr()); } llvm_unreachable("Unknown expr kind!"); } bool AsmParser::parseAssignment(StringRef Name, bool allow_redef, bool NoDeadStrip) { // FIXME: Use better location, we should use proper tokens. SMLoc EqualLoc = Lexer.getLoc(); const MCExpr *Value; if (parseExpression(Value)) return true; // Note: we don't count b as used in "a = b". This is to allow // a = b // b = c if (Lexer.isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in assignment"); // Eat the end of statement marker. Lex(); // Validate that the LHS is allowed to be a variable (either it has not been // used as a symbol, or it is an absolute symbol). MCSymbol *Sym = getContext().LookupSymbol(Name); if (Sym) { // Diagnose assignment to a label. // // FIXME: Diagnostics. Note the location of the definition as a label. // FIXME: Diagnose assignment to protected identifier (e.g., register name). if (isUsedIn(Sym, Value)) return Error(EqualLoc, "Recursive use of '" + Name + "'"); else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable()) ; // Allow redefinitions of undefined symbols only used in directives. else if (Sym->isVariable() && !Sym->isUsed() && allow_redef) ; // Allow redefinitions of variables that haven't yet been used. else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef)) return Error(EqualLoc, "redefinition of '" + Name + "'"); else if (!Sym->isVariable()) return Error(EqualLoc, "invalid assignment to '" + Name + "'"); else if (!isa<MCConstantExpr>(Sym->getVariableValue())) return Error(EqualLoc, "invalid reassignment of non-absolute variable '" + Name + "'"); // Don't count these checks as uses. Sym->setUsed(false); } else if (Name == ".") { if (Out.EmitValueToOffset(Value, 0)) { Error(EqualLoc, "expected absolute expression"); eatToEndOfStatement(); } return false; } else Sym = getContext().GetOrCreateSymbol(Name); // Do the assignment. Out.EmitAssignment(Sym, Value); if (NoDeadStrip) Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip); return false; } /// parseIdentifier: /// ::= identifier /// ::= string bool AsmParser::parseIdentifier(StringRef &Res) { // The assembler has relaxed rules for accepting identifiers, in particular we // allow things like '.globl $foo' and '.def @feat.00', which would normally be // separate tokens. At this level, we have already lexed so we cannot (currently) // handle this as a context dependent token, instead we detect adjacent tokens // and return the combined identifier. if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) { SMLoc PrefixLoc = getLexer().getLoc(); // Consume the prefix character, and check for a following identifier. Lex(); if (Lexer.isNot(AsmToken::Identifier)) return true; // We have a '$' or '@' followed by an identifier, make sure they are adjacent. if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer()) return true; // Construct the joined identifier and consume the token. Res = StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1); Lex(); return false; } if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) return true; Res = getTok().getIdentifier(); Lex(); // Consume the identifier token. return false; } /// parseDirectiveSet: /// ::= .equ identifier ',' expression /// ::= .equiv identifier ',' expression /// ::= .set identifier ',' expression bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) { StringRef Name; if (parseIdentifier(Name)) return TokError("expected identifier after '" + Twine(IDVal) + "'"); if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '" + Twine(IDVal) + "'"); Lex(); return parseAssignment(Name, allow_redef, true); } bool AsmParser::parseEscapedString(std::string &Data) { assert(getLexer().is(AsmToken::String) && "Unexpected current token!"); Data = ""; StringRef Str = getTok().getStringContents(); for (unsigned i = 0, e = Str.size(); i != e; ++i) { if (Str[i] != '\\') { Data += Str[i]; continue; } // Recognize escaped characters. Note that this escape semantics currently // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes. ++i; if (i == e) return TokError("unexpected backslash at end of string"); // Recognize octal sequences. if ((unsigned)(Str[i] - '0') <= 7) { // Consume up to three octal characters. unsigned Value = Str[i] - '0'; if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { ++i; Value = Value * 8 + (Str[i] - '0'); if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { ++i; Value = Value * 8 + (Str[i] - '0'); } } if (Value > 255) return TokError("invalid octal escape sequence (out of range)"); Data += (unsigned char)Value; continue; } // Otherwise recognize individual escapes. switch (Str[i]) { default: // Just reject invalid escape sequences for now. return TokError("invalid escape sequence (unrecognized character)"); case 'b': Data += '\b'; break; case 'f': Data += '\f'; break; case 'n': Data += '\n'; break; case 'r': Data += '\r'; break; case 't': Data += '\t'; break; case '"': Data += '"'; break; case '\\': Data += '\\'; break; } } return false; } /// parseDirectiveAscii: /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ] bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) { if (getLexer().isNot(AsmToken::EndOfStatement)) { checkForValidSection(); for (;;) { if (getLexer().isNot(AsmToken::String)) return TokError("expected string in '" + Twine(IDVal) + "' directive"); std::string Data; if (parseEscapedString(Data)) return true; getStreamer().EmitBytes(Data); if (ZeroTerminated) getStreamer().EmitBytes(StringRef("\0", 1)); Lex(); if (getLexer().is(AsmToken::EndOfStatement)) break; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); Lex(); } } Lex(); return false; } /// parseDirectiveValue /// ::= (.byte | .short | ... ) [ expression (, expression)* ] bool AsmParser::parseDirectiveValue(unsigned Size) { if (getLexer().isNot(AsmToken::EndOfStatement)) { checkForValidSection(); for (;;) { const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (parseExpression(Value)) return true; // Special case constant expressions to match code generator. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { assert(Size <= 8 && "Invalid size"); uint64_t IntValue = MCE->getValue(); if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) return Error(ExprLoc, "literal value out of range for directive"); getStreamer().EmitIntValue(IntValue, Size); } else getStreamer().EmitValue(Value, Size, ExprLoc); if (getLexer().is(AsmToken::EndOfStatement)) break; // FIXME: Improve diagnostic. if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); } } Lex(); return false; } /// ParseDirectiveOctaValue /// ::= .octa [ hexconstant (, hexconstant)* ] bool AsmParser::parseDirectiveOctaValue() { if (getLexer().isNot(AsmToken::EndOfStatement)) { checkForValidSection(); for (;;) { if (Lexer.getKind() == AsmToken::Error) return true; if (Lexer.getKind() != AsmToken::Integer && Lexer.getKind() != AsmToken::BigNum) return TokError("unknown token in expression"); SMLoc ExprLoc = getLexer().getLoc(); APInt IntValue = getTok().getAPIntVal(); Lex(); uint64_t hi, lo; if (IntValue.isIntN(64)) { hi = 0; lo = IntValue.getZExtValue(); } else if (IntValue.isIntN(128)) { // It might actually have more than 128 bits, but the top ones are zero. hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); lo = IntValue.getLoBits(64).getZExtValue(); } else return Error(ExprLoc, "literal value out of range for directive"); if (MAI.isLittleEndian()) { getStreamer().EmitIntValue(lo, 8); getStreamer().EmitIntValue(hi, 8); } else { getStreamer().EmitIntValue(hi, 8); getStreamer().EmitIntValue(lo, 8); } if (getLexer().is(AsmToken::EndOfStatement)) break; // FIXME: Improve diagnostic. if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); } } Lex(); return false; } /// parseDirectiveRealValue /// ::= (.single | .double) [ expression (, expression)* ] bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) { if (getLexer().isNot(AsmToken::EndOfStatement)) { checkForValidSection(); for (;;) { // We don't truly support arithmetic on floating point expressions, so we // have to manually parse unary prefixes. bool IsNeg = false; if (getLexer().is(AsmToken::Minus)) { Lex(); IsNeg = true; } else if (getLexer().is(AsmToken::Plus)) Lex(); if (getLexer().isNot(AsmToken::Integer) && getLexer().isNot(AsmToken::Real) && getLexer().isNot(AsmToken::Identifier)) return TokError("unexpected token in directive"); // Convert to an APFloat. APFloat Value(Semantics); StringRef IDVal = getTok().getString(); if (getLexer().is(AsmToken::Identifier)) { if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf")) Value = APFloat::getInf(Semantics); else if (!IDVal.compare_lower("nan")) Value = APFloat::getNaN(Semantics, false, ~0); else return TokError("invalid floating point literal"); } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) == APFloat::opInvalidOp) return TokError("invalid floating point literal"); if (IsNeg) Value.changeSign(); // Consume the numeric token. Lex(); // Emit the value as an integer. APInt AsInt = Value.bitcastToAPInt(); getStreamer().EmitIntValue(AsInt.getLimitedValue(), AsInt.getBitWidth() / 8); if (getLexer().is(AsmToken::EndOfStatement)) break; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); } } Lex(); return false; } /// parseDirectiveZero /// ::= .zero expression bool AsmParser::parseDirectiveZero() { checkForValidSection(); int64_t NumBytes; if (parseAbsoluteExpression(NumBytes)) return true; int64_t Val = 0; if (getLexer().is(AsmToken::Comma)) { Lex(); if (parseAbsoluteExpression(Val)) return true; } if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.zero' directive"); Lex(); getStreamer().EmitFill(NumBytes, Val); return false; } /// parseDirectiveFill /// ::= .fill expression [ , expression [ , expression ] ] bool AsmParser::parseDirectiveFill() { checkForValidSection(); SMLoc RepeatLoc = getLexer().getLoc(); int64_t NumValues; if (parseAbsoluteExpression(NumValues)) return true; if (NumValues < 0) { Warning(RepeatLoc, "'.fill' directive with negative repeat count has no effect"); NumValues = 0; } int64_t FillSize = 1; int64_t FillExpr = 0; SMLoc SizeLoc, ExprLoc; if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '.fill' directive"); Lex(); SizeLoc = getLexer().getLoc(); if (parseAbsoluteExpression(FillSize)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '.fill' directive"); Lex(); ExprLoc = getLexer().getLoc(); if (parseAbsoluteExpression(FillExpr)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.fill' directive"); Lex(); } } if (FillSize < 0) { Warning(SizeLoc, "'.fill' directive with negative size has no effect"); NumValues = 0; } if (FillSize > 8) { Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8"); FillSize = 8; } if (!isUInt<32>(FillExpr) && FillSize > 4) Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits"); int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize; FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8); for (uint64_t i = 0, e = NumValues; i != e; ++i) { getStreamer().EmitIntValue(FillExpr, NonZeroFillSize); getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize); } return false; } /// parseDirectiveOrg /// ::= .org expression [ , expression ] bool AsmParser::parseDirectiveOrg() { checkForValidSection(); const MCExpr *Offset; SMLoc Loc = getTok().getLoc(); if (parseExpression(Offset)) return true; // Parse optional fill expression. int64_t FillExpr = 0; if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '.org' directive"); Lex(); if (parseAbsoluteExpression(FillExpr)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.org' directive"); } Lex(); // Only limited forms of relocatable expressions are accepted here, it // has to be relative to the current section. The streamer will return // 'true' if the expression wasn't evaluatable. if (getStreamer().EmitValueToOffset(Offset, FillExpr)) return Error(Loc, "expected assembly-time absolute expression"); return false; } /// parseDirectiveAlign /// ::= {.align, ...} expression [ , expression [ , expression ]] bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) { checkForValidSection(); SMLoc AlignmentLoc = getLexer().getLoc(); int64_t Alignment; if (parseAbsoluteExpression(Alignment)) return true; SMLoc MaxBytesLoc; bool HasFillExpr = false; int64_t FillExpr = 0; int64_t MaxBytesToFill = 0; if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); // The fill expression can be omitted while specifying a maximum number of // alignment bytes, e.g: // .align 3,,4 if (getLexer().isNot(AsmToken::Comma)) { HasFillExpr = true; if (parseAbsoluteExpression(FillExpr)) return true; } if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); MaxBytesLoc = getLexer().getLoc(); if (parseAbsoluteExpression(MaxBytesToFill)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in directive"); } } Lex(); if (!HasFillExpr) FillExpr = 0; // Compute alignment in bytes. if (IsPow2) { // FIXME: Diagnose overflow. if (Alignment >= 32) { Error(AlignmentLoc, "invalid alignment value"); Alignment = 31; } Alignment = 1ULL << Alignment; } else { // Reject alignments that aren't a power of two, for gas compatibility. if (!isPowerOf2_64(Alignment)) Error(AlignmentLoc, "alignment must be a power of 2"); } // Diagnose non-sensical max bytes to align. if (MaxBytesLoc.isValid()) { if (MaxBytesToFill < 1) { Error(MaxBytesLoc, "alignment directive can never be satisfied in this " "many bytes, ignoring maximum bytes expression"); MaxBytesToFill = 0; } if (MaxBytesToFill >= Alignment) { Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and " "has no effect"); MaxBytesToFill = 0; } } // Check whether we should use optimal code alignment for this .align // directive. const MCSection *Section = getStreamer().getCurrentSection().first; assert(Section && "must have section to emit alignment"); bool UseCodeAlign = Section->UseCodeAlign(); if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) && ValueSize == 1 && UseCodeAlign) { getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill); } else { // FIXME: Target specific behavior about how the "extra" bytes are filled. getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill); } return false; } /// parseDirectiveFile /// ::= .file [number] filename /// ::= .file number directory filename bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) { // FIXME: I'm not sure what this is. int64_t FileNumber = -1; SMLoc FileNumberLoc = getLexer().getLoc(); if (getLexer().is(AsmToken::Integer)) { FileNumber = getTok().getIntVal(); Lex(); if (FileNumber < 1) return TokError("file number less than one"); } if (getLexer().isNot(AsmToken::String)) return TokError("unexpected token in '.file' directive"); // Usually the directory and filename together, otherwise just the directory. // Allow the strings to have escaped octal character sequence. std::string Path = getTok().getString(); if (parseEscapedString(Path)) return true; Lex(); StringRef Directory; StringRef Filename; std::string FilenameData; if (getLexer().is(AsmToken::String)) { if (FileNumber == -1) return TokError("explicit path specified, but no file number"); if (parseEscapedString(FilenameData)) return true; Filename = FilenameData; Directory = Path; Lex(); } else { Filename = Path; } if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.file' directive"); if (FileNumber == -1) getStreamer().EmitFileDirective(Filename); else { if (getContext().getGenDwarfForAssembly() == true) Error(DirectiveLoc, "input can't have .file dwarf directives when -g is " "used to generate dwarf debug info for assembly code"); if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) == 0) Error(FileNumberLoc, "file number already allocated"); } return false; } /// parseDirectiveLine /// ::= .line [number] bool AsmParser::parseDirectiveLine() { if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Integer)) return TokError("unexpected token in '.line' directive"); int64_t LineNumber = getTok().getIntVal(); (void)LineNumber; Lex(); // FIXME: Do something with the .line. } if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.line' directive"); return false; } /// parseDirectiveLoc /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] /// The first number is a file number, must have been previously assigned with /// a .file directive, the second number is the line number and optionally the /// third number is a column position (zero if not specified). The remaining /// optional items are .loc sub-directives. bool AsmParser::parseDirectiveLoc() { if (getLexer().isNot(AsmToken::Integer)) return TokError("unexpected token in '.loc' directive"); int64_t FileNumber = getTok().getIntVal(); if (FileNumber < 1) return TokError("file number less than one in '.loc' directive"); if (!getContext().isValidDwarfFileNumber(FileNumber)) return TokError("unassigned file number in '.loc' directive"); Lex(); int64_t LineNumber = 0; if (getLexer().is(AsmToken::Integer)) { LineNumber = getTok().getIntVal(); if (LineNumber < 0) return TokError("line number less than zero in '.loc' directive"); Lex(); } int64_t ColumnPos = 0; if (getLexer().is(AsmToken::Integer)) { ColumnPos = getTok().getIntVal(); if (ColumnPos < 0) return TokError("column position less than zero in '.loc' directive"); Lex(); } unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; unsigned Isa = 0; int64_t Discriminator = 0; if (getLexer().isNot(AsmToken::EndOfStatement)) { for (;;) { if (getLexer().is(AsmToken::EndOfStatement)) break; StringRef Name; SMLoc Loc = getTok().getLoc(); if (parseIdentifier(Name)) return TokError("unexpected token in '.loc' directive"); if (Name == "basic_block") Flags |= DWARF2_FLAG_BASIC_BLOCK; else if (Name == "prologue_end") Flags |= DWARF2_FLAG_PROLOGUE_END; else if (Name == "epilogue_begin") Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; else if (Name == "is_stmt") { Loc = getTok().getLoc(); const MCExpr *Value; if (parseExpression(Value)) return true; // The expression must be the constant 0 or 1. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { int Value = MCE->getValue(); if (Value == 0) Flags &= ~DWARF2_FLAG_IS_STMT; else if (Value == 1) Flags |= DWARF2_FLAG_IS_STMT; else return Error(Loc, "is_stmt value not 0 or 1"); } else { return Error(Loc, "is_stmt value not the constant value of 0 or 1"); } } else if (Name == "isa") { Loc = getTok().getLoc(); const MCExpr *Value; if (parseExpression(Value)) return true; // The expression must be a constant greater or equal to 0. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { int Value = MCE->getValue(); if (Value < 0) return Error(Loc, "isa number less than zero"); Isa = Value; } else { return Error(Loc, "isa number not a constant value"); } } else if (Name == "discriminator") { if (parseAbsoluteExpression(Discriminator)) return true; } else { return Error(Loc, "unknown sub-directive in '.loc' directive"); } if (getLexer().is(AsmToken::EndOfStatement)) break; } } getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, Isa, Discriminator, StringRef()); return false; } /// parseDirectiveStabs /// ::= .stabs string, number, number, number bool AsmParser::parseDirectiveStabs() { return TokError("unsupported directive '.stabs'"); } /// parseDirectiveCFISections /// ::= .cfi_sections section [, section] bool AsmParser::parseDirectiveCFISections() { StringRef Name; bool EH = false; bool Debug = false; if (parseIdentifier(Name)) return TokError("Expected an identifier"); if (Name == ".eh_frame") EH = true; else if (Name == ".debug_frame") Debug = true; if (getLexer().is(AsmToken::Comma)) { Lex(); if (parseIdentifier(Name)) return TokError("Expected an identifier"); if (Name == ".eh_frame") EH = true; else if (Name == ".debug_frame") Debug = true; } getStreamer().EmitCFISections(EH, Debug); return false; } /// parseDirectiveCFIStartProc /// ::= .cfi_startproc [simple] bool AsmParser::parseDirectiveCFIStartProc() { StringRef Simple; if (getLexer().isNot(AsmToken::EndOfStatement)) if (parseIdentifier(Simple) || Simple != "simple") return TokError("unexpected token in .cfi_startproc directive"); getStreamer().EmitCFIStartProc(!Simple.empty()); return false; } /// parseDirectiveCFIEndProc /// ::= .cfi_endproc bool AsmParser::parseDirectiveCFIEndProc() { getStreamer().EmitCFIEndProc(); return false; } /// \brief parse register name or number. bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc) { unsigned RegNo; if (getLexer().isNot(AsmToken::Integer)) { if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) return true; Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); } else return parseAbsoluteExpression(Register); return false; } /// parseDirectiveCFIDefCfa /// ::= .cfi_def_cfa register, offset bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); int64_t Offset = 0; if (parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIDefCfa(Register, Offset); return false; } /// parseDirectiveCFIDefCfaOffset /// ::= .cfi_def_cfa_offset offset bool AsmParser::parseDirectiveCFIDefCfaOffset() { int64_t Offset = 0; if (parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIDefCfaOffset(Offset); return false; } /// parseDirectiveCFIRegister /// ::= .cfi_register register, register bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { int64_t Register1 = 0; if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc)) return true; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); int64_t Register2 = 0; if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc)) return true; getStreamer().EmitCFIRegister(Register1, Register2); return false; } /// parseDirectiveCFIWindowSave /// ::= .cfi_window_save bool AsmParser::parseDirectiveCFIWindowSave() { getStreamer().EmitCFIWindowSave(); return false; } /// parseDirectiveCFIAdjustCfaOffset /// ::= .cfi_adjust_cfa_offset adjustment bool AsmParser::parseDirectiveCFIAdjustCfaOffset() { int64_t Adjustment = 0; if (parseAbsoluteExpression(Adjustment)) return true; getStreamer().EmitCFIAdjustCfaOffset(Adjustment); return false; } /// parseDirectiveCFIDefCfaRegister /// ::= .cfi_def_cfa_register register bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFIDefCfaRegister(Register); return false; } /// parseDirectiveCFIOffset /// ::= .cfi_offset register, offset bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { int64_t Register = 0; int64_t Offset = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); if (parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIOffset(Register, Offset); return false; } /// parseDirectiveCFIRelOffset /// ::= .cfi_rel_offset register, offset bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); int64_t Offset = 0; if (parseAbsoluteExpression(Offset)) return true; getStreamer().EmitCFIRelOffset(Register, Offset); return false; } static bool isValidEncoding(int64_t Encoding) { if (Encoding & ~0xff) return false; if (Encoding == dwarf::DW_EH_PE_omit) return true; const unsigned Format = Encoding & 0xf; if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) return false; const unsigned Application = Encoding & 0x70; if (Application != dwarf::DW_EH_PE_absptr && Application != dwarf::DW_EH_PE_pcrel) return false; return true; } /// parseDirectiveCFIPersonalityOrLsda /// IsPersonality true for cfi_personality, false for cfi_lsda /// ::= .cfi_personality encoding, [symbol_name] /// ::= .cfi_lsda encoding, [symbol_name] bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { int64_t Encoding = 0; if (parseAbsoluteExpression(Encoding)) return true; if (Encoding == dwarf::DW_EH_PE_omit) return false; if (!isValidEncoding(Encoding)) return TokError("unsupported encoding."); if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); StringRef Name; if (parseIdentifier(Name)) return TokError("expected identifier in directive"); MCSymbol *Sym = getContext().GetOrCreateSymbol(Name); if (IsPersonality) getStreamer().EmitCFIPersonality(Sym, Encoding); else getStreamer().EmitCFILsda(Sym, Encoding); return false; } /// parseDirectiveCFIRememberState /// ::= .cfi_remember_state bool AsmParser::parseDirectiveCFIRememberState() { getStreamer().EmitCFIRememberState(); return false; } /// parseDirectiveCFIRestoreState /// ::= .cfi_remember_state bool AsmParser::parseDirectiveCFIRestoreState() { getStreamer().EmitCFIRestoreState(); return false; } /// parseDirectiveCFISameValue /// ::= .cfi_same_value register bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFISameValue(Register); return false; } /// parseDirectiveCFIRestore /// ::= .cfi_restore register bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFIRestore(Register); return false; } /// parseDirectiveCFIEscape /// ::= .cfi_escape expression[,...] bool AsmParser::parseDirectiveCFIEscape() { std::string Values; int64_t CurrValue; if (parseAbsoluteExpression(CurrValue)) return true; Values.push_back((uint8_t)CurrValue); while (getLexer().is(AsmToken::Comma)) { Lex(); if (parseAbsoluteExpression(CurrValue)) return true; Values.push_back((uint8_t)CurrValue); } getStreamer().EmitCFIEscape(Values); return false; } /// parseDirectiveCFISignalFrame /// ::= .cfi_signal_frame bool AsmParser::parseDirectiveCFISignalFrame() { if (getLexer().isNot(AsmToken::EndOfStatement)) return Error(getLexer().getLoc(), "unexpected token in '.cfi_signal_frame'"); getStreamer().EmitCFISignalFrame(); return false; } /// parseDirectiveCFIUndefined /// ::= .cfi_undefined register bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { int64_t Register = 0; if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) return true; getStreamer().EmitCFIUndefined(Register); return false; } /// parseDirectiveMacrosOnOff /// ::= .macros_on /// ::= .macros_off bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) { if (getLexer().isNot(AsmToken::EndOfStatement)) return Error(getLexer().getLoc(), "unexpected token in '" + Directive + "' directive"); setMacrosEnabled(Directive == ".macros_on"); return false; } /// parseDirectiveMacro /// ::= .macro name[,] [parameters] bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) { StringRef Name; if (parseIdentifier(Name)) return TokError("expected identifier in '.macro' directive"); if (getLexer().is(AsmToken::Comma)) Lex(); MCAsmMacroParameters Parameters; while (getLexer().isNot(AsmToken::EndOfStatement)) { if (Parameters.size() && Parameters.back().Vararg) return Error(Lexer.getLoc(), "Vararg parameter '" + Parameters.back().Name + "' should be last one in the list of parameters."); MCAsmMacroParameter Parameter; if (parseIdentifier(Parameter.Name)) return TokError("expected identifier in '.macro' directive"); if (Lexer.is(AsmToken::Colon)) { Lex(); // consume ':' SMLoc QualLoc; StringRef Qualifier; QualLoc = Lexer.getLoc(); if (parseIdentifier(Qualifier)) return Error(QualLoc, "missing parameter qualifier for " "'" + Parameter.Name + "' in macro '" + Name + "'"); if (Qualifier == "req") Parameter.Required = true; else if (Qualifier == "vararg" && !IsDarwin) Parameter.Vararg = true; else return Error(QualLoc, Qualifier + " is not a valid parameter qualifier " "for '" + Parameter.Name + "' in macro '" + Name + "'"); } if (getLexer().is(AsmToken::Equal)) { Lex(); SMLoc ParamLoc; ParamLoc = Lexer.getLoc(); if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) return true; if (Parameter.Required) Warning(ParamLoc, "pointless default value for required parameter " "'" + Parameter.Name + "' in macro '" + Name + "'"); } Parameters.push_back(Parameter); if (getLexer().is(AsmToken::Comma)) Lex(); } // Eat the end of statement. Lex(); AsmToken EndToken, StartToken = getTok(); unsigned MacroDepth = 0; // Lex the macro definition. for (;;) { // Check whether we have reached the end of the file. if (getLexer().is(AsmToken::Eof)) return Error(DirectiveLoc, "no matching '.endmacro' in definition"); // Otherwise, check whether we have reach the .endmacro. if (getLexer().is(AsmToken::Identifier)) { if (getTok().getIdentifier() == ".endm" || getTok().getIdentifier() == ".endmacro") { if (MacroDepth == 0) { // Outermost macro. EndToken = getTok(); Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '" + EndToken.getIdentifier() + "' directive"); break; } else { // Otherwise we just found the end of an inner macro. --MacroDepth; } } else if (getTok().getIdentifier() == ".macro") { // We allow nested macros. Those aren't instantiated until the outermost // macro is expanded so just ignore them for now. ++MacroDepth; } } // Otherwise, scan til the end of the statement. eatToEndOfStatement(); } if (lookupMacro(Name)) { return Error(DirectiveLoc, "macro '" + Name + "' is already defined"); } const char *BodyStart = StartToken.getLoc().getPointer(); const char *BodyEnd = EndToken.getLoc().getPointer(); StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); checkForBadMacro(DirectiveLoc, Name, Body, Parameters); defineMacro(Name, MCAsmMacro(Name, Body, Parameters)); return false; } /// checkForBadMacro /// /// With the support added for named parameters there may be code out there that /// is transitioning from positional parameters. In versions of gas that did /// not support named parameters they would be ignored on the macro definition. /// But to support both styles of parameters this is not possible so if a macro /// definition has named parameters but does not use them and has what appears /// to be positional parameters, strings like $1, $2, ... and $n, then issue a /// warning that the positional parameter found in body which have no effect. /// Hoping the developer will either remove the named parameters from the macro /// definition so the positional parameters get used if that was what was /// intended or change the macro to use the named parameters. It is possible /// this warning will trigger when the none of the named parameters are used /// and the strings like $1 are infact to simply to be passed trough unchanged. void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, ArrayRef<MCAsmMacroParameter> Parameters) { // If this macro is not defined with named parameters the warning we are // checking for here doesn't apply. unsigned NParameters = Parameters.size(); if (NParameters == 0) return; bool NamedParametersFound = false; bool PositionalParametersFound = false; // Look at the body of the macro for use of both the named parameters and what // are likely to be positional parameters. This is what expandMacro() is // doing when it finds the parameters in the body. while (!Body.empty()) { // Scan for the next possible parameter. std::size_t End = Body.size(), Pos = 0; for (; Pos != End; ++Pos) { // Check for a substitution or escape. // This macro is defined with parameters, look for \foo, \bar, etc. if (Body[Pos] == '\\' && Pos + 1 != End) break; // This macro should have parameters, but look for $0, $1, ..., $n too. if (Body[Pos] != '$' || Pos + 1 == End) continue; char Next = Body[Pos + 1]; if (Next == '$' || Next == 'n' || isdigit(static_cast<unsigned char>(Next))) break; } // Check if we reached the end. if (Pos == End) break; if (Body[Pos] == '$') { switch (Body[Pos + 1]) { // $$ => $ case '$': break; // $n => number of arguments case 'n': PositionalParametersFound = true; break; // $[0-9] => argument default: { PositionalParametersFound = true; break; } } Pos += 2; } else { unsigned I = Pos + 1; while (isIdentifierChar(Body[I]) && I + 1 != End) ++I; const char *Begin = Body.data() + Pos + 1; StringRef Argument(Begin, I - (Pos + 1)); unsigned Index = 0; for (; Index < NParameters; ++Index) if (Parameters[Index].Name == Argument) break; if (Index == NParameters) { if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') Pos += 3; else { Pos = I; } } else { NamedParametersFound = true; Pos += 1 + Argument.size(); } } // Update the scan point. Body = Body.substr(Pos); } if (!NamedParametersFound && PositionalParametersFound) Warning(DirectiveLoc, "macro defined with named parameters which are not " "used in macro body, possible positional parameter " "found in body which will have no effect"); } /// parseDirectiveEndMacro /// ::= .endm /// ::= .endmacro bool AsmParser::parseDirectiveEndMacro(StringRef Directive) { if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '" + Directive + "' directive"); // If we are inside a macro instantiation, terminate the current // instantiation. if (isInsideMacroInstantiation()) { handleMacroExit(); return false; } // Otherwise, this .endmacro is a stray entry in the file; well formed // .endmacro directives are handled during the macro definition parsing. return TokError("unexpected '" + Directive + "' in file, " "no current macro definition"); } /// parseDirectivePurgeMacro /// ::= .purgem bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { StringRef Name; if (parseIdentifier(Name)) return TokError("expected identifier in '.purgem' directive"); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.purgem' directive"); if (!lookupMacro(Name)) return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); undefineMacro(Name); return false; } /// parseDirectiveBundleAlignMode /// ::= {.bundle_align_mode} expression bool AsmParser::parseDirectiveBundleAlignMode() { checkForValidSection(); // Expect a single argument: an expression that evaluates to a constant // in the inclusive range 0-30. SMLoc ExprLoc = getLexer().getLoc(); int64_t AlignSizePow2; if (parseAbsoluteExpression(AlignSizePow2)) return true; else if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token after expression in" " '.bundle_align_mode' directive"); else if (AlignSizePow2 < 0 || AlignSizePow2 > 30) return Error(ExprLoc, "invalid bundle alignment size (expected between 0 and 30)"); Lex(); // Because of AlignSizePow2's verified range we can safely truncate it to // unsigned. getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2)); return false; } /// parseDirectiveBundleLock /// ::= {.bundle_lock} [align_to_end] bool AsmParser::parseDirectiveBundleLock() { checkForValidSection(); bool AlignToEnd = false; if (getLexer().isNot(AsmToken::EndOfStatement)) { StringRef Option; SMLoc Loc = getTok().getLoc(); const char *kInvalidOptionError = "invalid option for '.bundle_lock' directive"; if (parseIdentifier(Option)) return Error(Loc, kInvalidOptionError); if (Option != "align_to_end") return Error(Loc, kInvalidOptionError); else if (getLexer().isNot(AsmToken::EndOfStatement)) return Error(Loc, "unexpected token after '.bundle_lock' directive option"); AlignToEnd = true; } Lex(); getStreamer().EmitBundleLock(AlignToEnd); return false; } /// parseDirectiveBundleLock /// ::= {.bundle_lock} bool AsmParser::parseDirectiveBundleUnlock() { checkForValidSection(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.bundle_unlock' directive"); Lex(); getStreamer().EmitBundleUnlock(); return false; } /// parseDirectiveSpace /// ::= (.skip | .space) expression [ , expression ] bool AsmParser::parseDirectiveSpace(StringRef IDVal) { checkForValidSection(); int64_t NumBytes; if (parseAbsoluteExpression(NumBytes)) return true; int64_t FillExpr = 0; if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); Lex(); if (parseAbsoluteExpression(FillExpr)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); } Lex(); if (NumBytes <= 0) return TokError("invalid number of bytes in '" + Twine(IDVal) + "' directive"); // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0. getStreamer().EmitFill(NumBytes, FillExpr); return false; } /// parseDirectiveLEB128 /// ::= (.sleb128 | .uleb128) expression bool AsmParser::parseDirectiveLEB128(bool Signed) { checkForValidSection(); const MCExpr *Value; if (parseExpression(Value)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in directive"); if (Signed) getStreamer().EmitSLEB128Value(Value); else getStreamer().EmitULEB128Value(Value); return false; } /// parseDirectiveSymbolAttribute /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { if (getLexer().isNot(AsmToken::EndOfStatement)) { for (;;) { StringRef Name; SMLoc Loc = getTok().getLoc(); if (parseIdentifier(Name)) return Error(Loc, "expected identifier in directive"); MCSymbol *Sym = getContext().GetOrCreateSymbol(Name); // Assembler local symbols don't make any sense here. Complain loudly. if (Sym->isTemporary()) return Error(Loc, "non-local symbol required in directive"); if (!getStreamer().EmitSymbolAttribute(Sym, Attr)) return Error(Loc, "unable to emit symbol attribute"); if (getLexer().is(AsmToken::EndOfStatement)) break; if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); } } Lex(); return false; } /// parseDirectiveComm /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] bool AsmParser::parseDirectiveComm(bool IsLocal) { checkForValidSection(); SMLoc IDLoc = getLexer().getLoc(); StringRef Name; if (parseIdentifier(Name)) return TokError("expected identifier in directive"); // Handle the identifier as the key symbol. MCSymbol *Sym = getContext().GetOrCreateSymbol(Name); if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in directive"); Lex(); int64_t Size; SMLoc SizeLoc = getLexer().getLoc(); if (parseAbsoluteExpression(Size)) return true; int64_t Pow2Alignment = 0; SMLoc Pow2AlignmentLoc; if (getLexer().is(AsmToken::Comma)) { Lex(); Pow2AlignmentLoc = getLexer().getLoc(); if (parseAbsoluteExpression(Pow2Alignment)) return true; LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); if (IsLocal && LCOMM == LCOMM::NoAlignment) return Error(Pow2AlignmentLoc, "alignment not supported on this target"); // If this target takes alignments in bytes (not log) validate and convert. if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || (IsLocal && LCOMM == LCOMM::ByteAlignment)) { if (!isPowerOf2_64(Pow2Alignment)) return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); Pow2Alignment = Log2_64(Pow2Alignment); } } if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.comm' or '.lcomm' directive"); Lex(); // NOTE: a size of zero for a .comm should create a undefined symbol // but a size of .lcomm creates a bss symbol of size zero. if (Size < 0) return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't " "be less than zero"); // NOTE: The alignment in the directive is a power of 2 value, the assembler // may internally end up wanting an alignment in bytes. // FIXME: Diagnose overflow. if (Pow2Alignment < 0) return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive " "alignment, can't be less than zero"); if (!Sym->isUndefined()) return Error(IDLoc, "invalid symbol redefinition"); // Create the Symbol as a common or local common with Size and Pow2Alignment if (IsLocal) { getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); return false; } getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment); return false; } /// parseDirectiveAbort /// ::= .abort [... message ...] bool AsmParser::parseDirectiveAbort() { // FIXME: Use loc from directive. SMLoc Loc = getLexer().getLoc(); StringRef Str = parseStringToEndOfStatement(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.abort' directive"); Lex(); if (Str.empty()) Error(Loc, ".abort detected. Assembly stopping."); else Error(Loc, ".abort '" + Str + "' detected. Assembly stopping."); // FIXME: Actually abort assembly here. return false; } /// parseDirectiveInclude /// ::= .include "filename" bool AsmParser::parseDirectiveInclude() { if (getLexer().isNot(AsmToken::String)) return TokError("expected string in '.include' directive"); // Allow the strings to have escaped octal character sequence. std::string Filename; if (parseEscapedString(Filename)) return true; SMLoc IncludeLoc = getLexer().getLoc(); Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.include' directive"); // Attempt to switch the lexer to the included file before consuming the end // of statement to avoid losing it when we switch. if (enterIncludeFile(Filename)) { Error(IncludeLoc, "Could not find include file '" + Filename + "'"); return true; } return false; } /// parseDirectiveIncbin /// ::= .incbin "filename" bool AsmParser::parseDirectiveIncbin() { if (getLexer().isNot(AsmToken::String)) return TokError("expected string in '.incbin' directive"); // Allow the strings to have escaped octal character sequence. std::string Filename; if (parseEscapedString(Filename)) return true; SMLoc IncbinLoc = getLexer().getLoc(); Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.incbin' directive"); // Attempt to process the included file. if (processIncbinFile(Filename)) { Error(IncbinLoc, "Could not find incbin file '" + Filename + "'"); return true; } return false; } /// parseDirectiveIf /// ::= .if{,eq,ge,gt,le,lt,ne} expression bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { int64_t ExprValue; if (parseAbsoluteExpression(ExprValue)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.if' directive"); Lex(); switch (DirKind) { default: llvm_unreachable("unsupported directive"); case DK_IF: case DK_IFNE: break; case DK_IFEQ: ExprValue = ExprValue == 0; break; case DK_IFGE: ExprValue = ExprValue >= 0; break; case DK_IFGT: ExprValue = ExprValue > 0; break; case DK_IFLE: ExprValue = ExprValue <= 0; break; case DK_IFLT: ExprValue = ExprValue < 0; break; } TheCondState.CondMet = ExprValue; TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveIfb /// ::= .ifb string bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { StringRef Str = parseStringToEndOfStatement(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.ifb' directive"); Lex(); TheCondState.CondMet = ExpectBlank == Str.empty(); TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveIfc /// ::= .ifc string1, string2 /// ::= .ifnc string1, string2 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) { TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { StringRef Str1 = parseStringToComma(); if (getLexer().isNot(AsmToken::Comma)) return TokError("unexpected token in '.ifc' directive"); Lex(); StringRef Str2 = parseStringToEndOfStatement(); if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.ifc' directive"); Lex(); TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim()); TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveIfeqs /// ::= .ifeqs string1, string2 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) { if (Lexer.isNot(AsmToken::String)) { TokError("expected string parameter for '.ifeqs' directive"); eatToEndOfStatement(); return true; } StringRef String1 = getTok().getStringContents(); Lex(); if (Lexer.isNot(AsmToken::Comma)) { TokError("expected comma after first string for '.ifeqs' directive"); eatToEndOfStatement(); return true; } Lex(); if (Lexer.isNot(AsmToken::String)) { TokError("expected string parameter for '.ifeqs' directive"); eatToEndOfStatement(); return true; } StringRef String2 = getTok().getStringContents(); Lex(); TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; TheCondState.CondMet = String1 == String2; TheCondState.Ignore = !TheCondState.CondMet; return false; } /// parseDirectiveIfdef /// ::= .ifdef symbol bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { StringRef Name; TheCondStack.push_back(TheCondState); TheCondState.TheCond = AsmCond::IfCond; if (TheCondState.Ignore) { eatToEndOfStatement(); } else { if (parseIdentifier(Name)) return TokError("expected identifier after '.ifdef'"); Lex(); MCSymbol *Sym = getContext().LookupSymbol(Name); if (expect_defined) TheCondState.CondMet = (Sym && !Sym->isUndefined()); else TheCondState.CondMet = (!Sym || Sym->isUndefined()); TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveElseIf /// ::= .elseif expression bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) { if (TheCondState.TheCond != AsmCond::IfCond && TheCondState.TheCond != AsmCond::ElseIfCond) Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or " " an .elseif"); TheCondState.TheCond = AsmCond::ElseIfCond; bool LastIgnoreState = false; if (!TheCondStack.empty()) LastIgnoreState = TheCondStack.back().Ignore; if (LastIgnoreState || TheCondState.CondMet) { TheCondState.Ignore = true; eatToEndOfStatement(); } else { int64_t ExprValue; if (parseAbsoluteExpression(ExprValue)) return true; if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.elseif' directive"); Lex(); TheCondState.CondMet = ExprValue; TheCondState.Ignore = !TheCondState.CondMet; } return false; } /// parseDirectiveElse /// ::= .else bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) { if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.else' directive"); Lex(); if (TheCondState.TheCond != AsmCond::IfCond && TheCondState.TheCond != AsmCond::ElseIfCond) Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an " ".elseif"); TheCondState.TheCond = AsmCond::ElseCond; bool LastIgnoreState = false; if (!TheCondStack.empty()) LastIgnoreState = TheCondStack.back().Ignore; if (LastIgnoreState || TheCondState.CondMet) TheCondState.Ignore = true; else TheCondState.Ignore = false; return false; } /// parseDirectiveEnd /// ::= .end bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.end' directive"); Lex(); while (Lexer.isNot(AsmToken::Eof)) Lex(); return false; } /// parseDirectiveError /// ::= .err /// ::= .error [string] bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) { if (!TheCondStack.empty()) { if (TheCondStack.back().Ignore) { eatToEndOfStatement(); return false; } } if (!WithMessage) return Error(L, ".err encountered"); StringRef Message = ".error directive invoked in source file"; if (Lexer.isNot(AsmToken::EndOfStatement)) { if (Lexer.isNot(AsmToken::String)) { TokError(".error argument must be a string"); eatToEndOfStatement(); return true; } Message = getTok().getStringContents(); Lex(); } Error(L, Message); return true; } /// parseDirectiveEndIf /// ::= .endif bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { if (getLexer().isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '.endif' directive"); Lex(); if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or " ".else"); if (!TheCondStack.empty()) { TheCondState = TheCondStack.back(); TheCondStack.pop_back(); } return false; } void AsmParser::initializeDirectiveKindMap() { DirectiveKindMap[".set"] = DK_SET; DirectiveKindMap[".equ"] = DK_EQU; DirectiveKindMap[".equiv"] = DK_EQUIV; DirectiveKindMap[".ascii"] = DK_ASCII; DirectiveKindMap[".asciz"] = DK_ASCIZ; DirectiveKindMap[".string"] = DK_STRING; DirectiveKindMap[".byte"] = DK_BYTE; DirectiveKindMap[".short"] = DK_SHORT; DirectiveKindMap[".value"] = DK_VALUE; DirectiveKindMap[".2byte"] = DK_2BYTE; DirectiveKindMap[".long"] = DK_LONG; DirectiveKindMap[".int"] = DK_INT; DirectiveKindMap[".4byte"] = DK_4BYTE; DirectiveKindMap[".quad"] = DK_QUAD; DirectiveKindMap[".8byte"] = DK_8BYTE; DirectiveKindMap[".octa"] = DK_OCTA; DirectiveKindMap[".single"] = DK_SINGLE; DirectiveKindMap[".float"] = DK_FLOAT; DirectiveKindMap[".double"] = DK_DOUBLE; DirectiveKindMap[".align"] = DK_ALIGN; DirectiveKindMap[".align32"] = DK_ALIGN32; DirectiveKindMap[".balign"] = DK_BALIGN; DirectiveKindMap[".balignw"] = DK_BALIGNW; DirectiveKindMap[".balignl"] = DK_BALIGNL; DirectiveKindMap[".p2align"] = DK_P2ALIGN; DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW; DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL; DirectiveKindMap[".org"] = DK_ORG; DirectiveKindMap[".fill"] = DK_FILL; DirectiveKindMap[".zero"] = DK_ZERO; DirectiveKindMap[".extern"] = DK_EXTERN; DirectiveKindMap[".globl"] = DK_GLOBL; DirectiveKindMap[".global"] = DK_GLOBAL; DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE; DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP; DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER; DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN; DirectiveKindMap[".reference"] = DK_REFERENCE; DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION; DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE; DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN; DirectiveKindMap[".comm"] = DK_COMM; DirectiveKindMap[".common"] = DK_COMMON; DirectiveKindMap[".lcomm"] = DK_LCOMM; DirectiveKindMap[".abort"] = DK_ABORT; DirectiveKindMap[".include"] = DK_INCLUDE; DirectiveKindMap[".incbin"] = DK_INCBIN; DirectiveKindMap[".code16"] = DK_CODE16; DirectiveKindMap[".code16gcc"] = DK_CODE16GCC; DirectiveKindMap[".rept"] = DK_REPT; DirectiveKindMap[".rep"] = DK_REPT; DirectiveKindMap[".irp"] = DK_IRP; DirectiveKindMap[".irpc"] = DK_IRPC; DirectiveKindMap[".endr"] = DK_ENDR; DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE; DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK; DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK; DirectiveKindMap[".if"] = DK_IF; DirectiveKindMap[".ifeq"] = DK_IFEQ; DirectiveKindMap[".ifge"] = DK_IFGE; DirectiveKindMap[".ifgt"] = DK_IFGT; DirectiveKindMap[".ifle"] = DK_IFLE; DirectiveKindMap[".iflt"] = DK_IFLT; DirectiveKindMap[".ifne"] = DK_IFNE; DirectiveKindMap[".ifb"] = DK_IFB; DirectiveKindMap[".ifnb"] = DK_IFNB; DirectiveKindMap[".ifc"] = DK_IFC; DirectiveKindMap[".ifeqs"] = DK_IFEQS; DirectiveKindMap[".ifnc"] = DK_IFNC; DirectiveKindMap[".ifdef"] = DK_IFDEF; DirectiveKindMap[".ifndef"] = DK_IFNDEF; DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF; DirectiveKindMap[".elseif"] = DK_ELSEIF; DirectiveKindMap[".else"] = DK_ELSE; DirectiveKindMap[".end"] = DK_END; DirectiveKindMap[".endif"] = DK_ENDIF; DirectiveKindMap[".skip"] = DK_SKIP; DirectiveKindMap[".space"] = DK_SPACE; DirectiveKindMap[".file"] = DK_FILE; DirectiveKindMap[".line"] = DK_LINE; DirectiveKindMap[".loc"] = DK_LOC; DirectiveKindMap[".stabs"] = DK_STABS; DirectiveKindMap[".sleb128"] = DK_SLEB128; DirectiveKindMap[".uleb128"] = DK_ULEB128; DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; DirectiveKindMap[".macros_on"] = DK_MACROS_ON; DirectiveKindMap[".macros_off"] = DK_MACROS_OFF; DirectiveKindMap[".macro"] = DK_MACRO; DirectiveKindMap[".endm"] = DK_ENDM; DirectiveKindMap[".endmacro"] = DK_ENDMACRO; DirectiveKindMap[".purgem"] = DK_PURGEM; DirectiveKindMap[".err"] = DK_ERR; DirectiveKindMap[".error"] = DK_ERROR; } MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { AsmToken EndToken, StartToken = getTok(); unsigned NestLevel = 0; for (;;) { // Check whether we have reached the end of the file. if (getLexer().is(AsmToken::Eof)) { Error(DirectiveLoc, "no matching '.endr' in definition"); return nullptr; } if (Lexer.is(AsmToken::Identifier) && (getTok().getIdentifier() == ".rept")) { ++NestLevel; } // Otherwise, check whether we have reached the .endr. if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { if (NestLevel == 0) { EndToken = getTok(); Lex(); if (Lexer.isNot(AsmToken::EndOfStatement)) { TokError("unexpected token in '.endr' directive"); return nullptr; } break; } --NestLevel; } // Otherwise, scan till the end of the statement. eatToEndOfStatement(); } const char *BodyStart = StartToken.getLoc().getPointer(); const char *BodyEnd = EndToken.getLoc().getPointer(); StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); // We Are Anonymous. MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None)); return &MacroLikeBodies.back(); } void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, raw_svector_ostream &OS) { OS << ".endr\n"; MemoryBuffer *Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); // Create the macro instantiation object and add to the current macro // instantiation stack. MacroInstantiation *MI = new MacroInstantiation( M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation); ActiveMacros.push_back(MI); // Jump to the macro instantiation and prime the lexer. CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc()); Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); Lex(); } /// parseDirectiveRept /// ::= .rep | .rept count bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { const MCExpr *CountExpr; SMLoc CountLoc = getTok().getLoc(); if (parseExpression(CountExpr)) return true; int64_t Count; if (!CountExpr->EvaluateAsAbsolute(Count)) { eatToEndOfStatement(); return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); } if (Count < 0) return Error(CountLoc, "Count is negative"); if (Lexer.isNot(AsmToken::EndOfStatement)) return TokError("unexpected token in '" + Dir + "' directive"); // Eat the end of statement. Lex(); // Lex the rept definition. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); if (!M) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; raw_svector_ostream OS(Buf); while (Count--) { if (expandMacro(OS, M->Body, None, None, getTok().getLoc())) return true; } instantiateMacroLikeBody(M, DirectiveLoc, OS); return false; } /// parseDirectiveIrp /// ::= .irp symbol,values bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { MCAsmMacroParameter Parameter; if (parseIdentifier(Parameter.Name)) return TokError("expected identifier in '.irp' directive"); if (Lexer.isNot(AsmToken::Comma)) return TokError("expected comma in '.irp' directive"); Lex(); MCAsmMacroArguments A; if (parseMacroArguments(nullptr, A)) return true; // Eat the end of statement. Lex(); // Lex the irp definition. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); if (!M) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; raw_svector_ostream OS(Buf); for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) { if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc())) return true; } instantiateMacroLikeBody(M, DirectiveLoc, OS); return false; } /// parseDirectiveIrpc /// ::= .irpc symbol,values bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { MCAsmMacroParameter Parameter; if (parseIdentifier(Parameter.Name)) return TokError("expected identifier in '.irpc' directive"); if (Lexer.isNot(AsmToken::Comma)) return TokError("expected comma in '.irpc' directive"); Lex(); MCAsmMacroArguments A; if (parseMacroArguments(nullptr, A)) return true; if (A.size() != 1 || A.front().size() != 1) return TokError("unexpected token in '.irpc' directive"); // Eat the end of statement. Lex(); // Lex the irpc definition. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); if (!M) return true; // Macro instantiation is lexical, unfortunately. We construct a new buffer // to hold the macro body with substitutions. SmallString<256> Buf; raw_svector_ostream OS(Buf); StringRef Values = A.front().front().getString(); for (std::size_t I = 0, End = Values.size(); I != End; ++I) { MCAsmMacroArgument Arg; Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1))); if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc())) return true; } instantiateMacroLikeBody(M, DirectiveLoc, OS); return false; } bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { if (ActiveMacros.empty()) return TokError("unmatched '.endr' directive"); // The only .repl that should get here are the ones created by // instantiateMacroLikeBody. assert(getLexer().is(AsmToken::EndOfStatement)); handleMacroExit(); return false; } bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, size_t Len) { const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (parseExpression(Value)) return true; const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); if (!MCE) return Error(ExprLoc, "unexpected expression in _emit"); uint64_t IntValue = MCE->getValue(); if (!isUIntN(8, IntValue) && !isIntN(8, IntValue)) return Error(ExprLoc, "literal value out of range for directive"); Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len)); return false; } bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { const MCExpr *Value; SMLoc ExprLoc = getLexer().getLoc(); if (parseExpression(Value)) return true; const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); if (!MCE) return Error(ExprLoc, "unexpected expression in align"); uint64_t IntValue = MCE->getValue(); if (!isPowerOf2_64(IntValue)) return Error(ExprLoc, "literal value not a power of two greater then zero"); Info.AsmRewrites->push_back( AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue))); return false; } // We are comparing pointers, but the pointers are relative to a single string. // Thus, this should always be deterministic. static int rewritesSort(const AsmRewrite *AsmRewriteA, const AsmRewrite *AsmRewriteB) { if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) return -1; if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) return 1; // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output // rewrite to the same location. Make sure the SizeDirective rewrite is // performed first, then the Imm/ImmPrefix and finally the Input/Output. This // ensures the sort algorithm is stable. if (AsmRewritePrecedence[AsmRewriteA->Kind] > AsmRewritePrecedence[AsmRewriteB->Kind]) return -1; if (AsmRewritePrecedence[AsmRewriteA->Kind] < AsmRewritePrecedence[AsmRewriteB->Kind]) return 1; llvm_unreachable("Unstable rewrite sort."); } bool AsmParser::parseMSInlineAsm( void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls, SmallVectorImpl<std::string> &Constraints, SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { SmallVector<void *, 4> InputDecls; SmallVector<void *, 4> OutputDecls; SmallVector<bool, 4> InputDeclsAddressOf; SmallVector<bool, 4> OutputDeclsAddressOf; SmallVector<std::string, 4> InputConstraints; SmallVector<std::string, 4> OutputConstraints; SmallVector<unsigned, 4> ClobberRegs; SmallVector<AsmRewrite, 4> AsmStrRewrites; // Prime the lexer. Lex(); // While we have input, parse each statement. unsigned InputIdx = 0; unsigned OutputIdx = 0; while (getLexer().isNot(AsmToken::Eof)) { ParseStatementInfo Info(&AsmStrRewrites); if (parseStatement(Info)) return true; if (Info.ParseError) return true; if (Info.Opcode == ~0U) continue; const MCInstrDesc &Desc = MII->get(Info.Opcode); // Build the list of clobbers, outputs and inputs. for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; // Immediate. if (Operand.isImm()) continue; // Register operand. if (Operand.isReg() && !Operand.needAddressOf() && !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { unsigned NumDefs = Desc.getNumDefs(); // Clobber. if (NumDefs && Operand.getMCOperandNum() < NumDefs) ClobberRegs.push_back(Operand.getReg()); continue; } // Expr/Input or Output. StringRef SymName = Operand.getSymName(); if (SymName.empty()) continue; void *OpDecl = Operand.getOpDecl(); if (!OpDecl) continue; bool isOutput = (i == 1) && Desc.mayStore(); SMLoc Start = SMLoc::getFromPointer(SymName.data()); if (isOutput) { ++InputIdx; OutputDecls.push_back(OpDecl); OutputDeclsAddressOf.push_back(Operand.needAddressOf()); OutputConstraints.push_back('=' + Operand.getConstraint().str()); AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size())); } else { InputDecls.push_back(OpDecl); InputDeclsAddressOf.push_back(Operand.needAddressOf()); InputConstraints.push_back(Operand.getConstraint().str()); AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size())); } } // Consider implicit defs to be clobbers. Think of cpuid and push. ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(), Desc.getNumImplicitDefs()); ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end()); } // Set the number of Outputs and Inputs. NumOutputs = OutputDecls.size(); NumInputs = InputDecls.size(); // Set the unique clobbers. array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), ClobberRegs.end()); Clobbers.assign(ClobberRegs.size(), std::string()); for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { raw_string_ostream OS(Clobbers[I]); IP->printRegName(OS, ClobberRegs[I]); } // Merge the various outputs and inputs. Output are expected first. if (NumOutputs || NumInputs) { unsigned NumExprs = NumOutputs + NumInputs; OpDecls.resize(NumExprs); Constraints.resize(NumExprs); for (unsigned i = 0; i < NumOutputs; ++i) { OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); Constraints[i] = OutputConstraints[i]; } for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); Constraints[j] = InputConstraints[i]; } } // Build the IR assembly string. std::string AsmStringIR; raw_string_ostream OS(AsmStringIR); StringRef ASMString = SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); const char *AsmStart = ASMString.begin(); const char *AsmEnd = ASMString.end(); array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); for (const AsmRewrite &AR : AsmStrRewrites) { AsmRewriteKind Kind = AR.Kind; if (Kind == AOK_Delete) continue; const char *Loc = AR.Loc.getPointer(); assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); // Emit everything up to the immediate/expression. if (unsigned Len = Loc - AsmStart) OS << StringRef(AsmStart, Len); // Skip the original expression. if (Kind == AOK_Skip) { AsmStart = Loc + AR.Len; continue; } unsigned AdditionalSkip = 0; // Rewrite expressions in $N notation. switch (Kind) { default: break; case AOK_Imm: OS << "$$" << AR.Val; break; case AOK_ImmPrefix: OS << "$$"; break; case AOK_Input: OS << '$' << InputIdx++; break; case AOK_Output: OS << '$' << OutputIdx++; break; case AOK_SizeDirective: switch (AR.Val) { default: break; case 8: OS << "byte ptr "; break; case 16: OS << "word ptr "; break; case 32: OS << "dword ptr "; break; case 64: OS << "qword ptr "; break; case 80: OS << "xword ptr "; break; case 128: OS << "xmmword ptr "; break; case 256: OS << "ymmword ptr "; break; } break; case AOK_Emit: OS << ".byte"; break; case AOK_Align: { unsigned Val = AR.Val; OS << ".align " << Val; // Skip the original immediate. assert(Val < 10 && "Expected alignment less then 2^10."); AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; break; } case AOK_DotOperator: // Insert the dot if the user omitted it. OS.flush(); if (AsmStringIR.back() != '.') OS << '.'; OS << AR.Val; break; } // Skip the original expression. AsmStart = Loc + AR.Len + AdditionalSkip; } // Emit the remainder of the asm string. if (AsmStart != AsmEnd) OS << StringRef(AsmStart, AsmEnd - AsmStart); AsmString = OS.str(); return false; } /// \brief Create an MCAsmParser instance. MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C, MCStreamer &Out, const MCAsmInfo &MAI) { return new AsmParser(SM, C, Out, MAI); }
dededong/goblin-core
riscv/llvm/3.5/llvm-3.5.0.src/lib/MC/MCParser/AsmParser.cpp
C++
bsd-3-clause
148,779
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_RUNTIME_RENDERER_XWALK_CONTENT_RENDERER_CLIENT_H_ #define XWALK_RUNTIME_RENDERER_XWALK_CONTENT_RENDERER_CLIENT_H_ #include <string> #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "base/files/file.h" #include "base/strings/string16.h" #include "content/public/renderer/content_renderer_client.h" #include "ui/base/page_transition_types.h" #include "xwalk/extensions/renderer/xwalk_extension_renderer_controller.h" #if defined(OS_ANDROID) #include "xwalk/runtime/renderer/android/xwalk_render_process_observer.h" #else #include "xwalk/runtime/renderer/xwalk_render_process_observer_generic.h" #endif namespace visitedlink { class VisitedLinkSlave; } namespace xwalk { class XWalkRenderProcessObserver; // When implementing a derived class, make sure to update // `in_process_browser_test.cc` and `xwalk_main_delegate.cc`. class XWalkContentRendererClient : public content::ContentRendererClient, public extensions::XWalkExtensionRendererController::Delegate { public: static XWalkContentRendererClient* Get(); XWalkContentRendererClient(); ~XWalkContentRendererClient() override; // ContentRendererClient implementation. void RenderThreadStarted() override; void RenderFrameCreated(content::RenderFrame* render_frame) override; void RenderViewCreated(content::RenderView* render_view) override; bool IsExternalPepperPlugin(const std::string& module_name) override; const void* CreatePPAPIInterface( const std::string& interface_name) override; #if defined(OS_ANDROID) unsigned long long VisitedLinkHash(const char* canonical_url, // NOLINT size_t length) override; bool IsLinkVisited(unsigned long long link_hash) override; // NOLINT #endif bool WillSendRequest(blink::WebFrame* frame, ui::PageTransition transition_type, const GURL& url, const GURL& first_party_for_cookies, GURL* new_url) override; protected: scoped_ptr<XWalkRenderProcessObserver> xwalk_render_process_observer_; private: // XWalkExtensionRendererController::Delegate implementation. void DidCreateModuleSystem( extensions::XWalkModuleSystem* module_system) override; scoped_ptr<extensions::XWalkExtensionRendererController> extension_controller_; #if defined(OS_ANDROID) scoped_ptr<visitedlink::VisitedLinkSlave> visited_link_slave_; #endif void GetNavigationErrorStrings( content::RenderView* render_view, blink::WebFrame* frame, const blink::WebURLRequest& failed_request, const blink::WebURLError& error, std::string* error_html, base::string16* error_description) override; DISALLOW_COPY_AND_ASSIGN(XWalkContentRendererClient); }; } // namespace xwalk #endif // XWALK_RUNTIME_RENDERER_XWALK_CONTENT_RENDERER_CLIENT_H_
jpike88/crosswalk
runtime/renderer/xwalk_content_renderer_client.h
C
bsd-3-clause
3,138
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013,2014 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #if defined(STM32PLUS_F4) #include "config/exti.h" using namespace stm32plus; // static initialiser for the hack that forces the IRQ handlers to be linked template<> ExtiPeripheral<EXTI_Line0> *ExtiPeripheral<EXTI_Line0>::_extiInstance=nullptr; #if defined(USE_EXTI0_INTERRUPT) extern "C" { void __attribute__ ((interrupt("IRQ"))) EXTI0_IRQHandler(void) { if(EXTI_GetITStatus(EXTI_Line0)!=RESET) { Exti0::_extiInstance->ExtiInterruptEventSender.raiseEvent(0); EXTI_ClearITPendingBit(EXTI_Line0); } __DSB(); // prevent erroneous recall of this handler due to delayed memory write } } #endif #endif
phynex/stm32plus
lib/src/exti/interrupts/f4/Exti0InterruptHandler.cpp
C++
bsd-3-clause
859
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Pash.Implementation; using System.Management.Automation; using Pash.ParserIntrinsics; using Irony.Parsing; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Management.Pash.Implementation; namespace Pash.Implementation { internal class ScriptBlockProcessor : CommandProcessorBase { private readonly IScriptBlockInfo _scriptBlockInfo; private ExecutionContext _scopedContext; private ExecutionContext _originalContext; private bool _fromFile; private int? _exitCode; private ExecutionVisitor _scopedExecutionVisitor; ScriptBlockParameterBinder _argumentBinder; public ScriptBlockProcessor(IScriptBlockInfo scriptBlockInfo, CommandInfo commandInfo) : base(commandInfo) { _scriptBlockInfo = scriptBlockInfo; _fromFile = commandInfo.CommandType.Equals(CommandTypes.ExternalScript); } private void CreateOwnScope() { _originalContext = ExecutionContext; var executionSessionState = CommandInfo.Module != null ? CommandInfo.Module.SessionState : ExecutionContext.SessionState; _scopedContext = ExecutionContext.Clone(executionSessionState, _scriptBlockInfo.ScopeUsage); _scopedExecutionVisitor = new ExecutionVisitor(_scopedContext, CommandRuntime, false); } private void SwitchToOwnScope() { // globally for access through the runspace ExecutionContext.CurrentRunspace.ExecutionContext = _scopedContext; // privately for access through own reference ExecutionContext = _scopedContext; } private void RestoreOriginalScope() { ExecutionContext.CurrentRunspace.ExecutionContext = _originalContext; ExecutionContext = _originalContext; } /// <summary> /// Create the scope for this script block and binding arguments in it /// </summary> public override void Prepare() { // TODO: check if it makes sense to move the scope handling to the PipelineProcessor! //Let's see on the long run if there is an easier solution for this #ExecutionContextChange CreateOwnScope(); SwitchToOwnScope(); try { MergeParameters(); _argumentBinder = new ScriptBlockParameterBinder(_scriptBlockInfo.GetParameters(), ExecutionContext, _scopedExecutionVisitor); _argumentBinder.BindCommandLineParameters(Parameters); } finally { RestoreOriginalScope(); } } public override void BeginProcessing() { // nothing to do // TODO: process begin clause. remember to switch scope } /// <summary> /// In a script block, we only provide the pipeline as the automatic $input variable, but call it only once /// </summary> public override void ProcessRecords() { // TODO: provide the automatic $input variable // TODO: currently we don't support "cmdlet scripts", i.e. functions that behave like cmdlets. // TODO: Investigate the usage of different function blocks properly before implementing them //set the execution context of the runspace to the new context for execution in it SwitchToOwnScope(); try { _scriptBlockInfo.ScriptBlock.Ast.Visit(_scopedExecutionVisitor); } catch (FlowControlException e) { if (!_fromFile || e is LoopFlowException) { throw; // gets propagated if the script block is not an external script or it's a break/continue } if (e is ExitException) { int exitCode = 0; LanguagePrimitives.TryConvertTo<int>(((ExitException)e).Argument, out exitCode); _exitCode = exitCode; ExecutionContext.SetLastExitCodeVariable(exitCode); } // otherwise (return), we simply stop execution of the script (that's why we're here) and do nothing } finally //make sure we switch back to the original execution context, no matter what happened { RestoreOriginalScope(); } } public override void EndProcessing() { // TODO: process end clause. remember to switch scope ExecutionContext.SetSuccessVariable(_exitCode == null || _exitCode == 0); } public override string ToString() { return this._scriptBlockInfo.ToString(); } /// <summary> /// The parse currently adds each parameter without value and each value without parameter name, because /// it doesn't know at parse time whether the value belongs to the paramater or if the parameter is a switch /// parameter and the value is just a positional parameter. As we now know more abot the parameters, we can /// merge all parameters with the upcoming value if it's not a switch parameter /// </summary> void MergeParameters() { // This implementation has quite some differences to the definition for cmdlets. // For example "fun -a -b" can bind "-b" as value to parameter "-a" if "-b" doesn't exist. // This is different to cmdlet behavior. // Also, we will throw an error if we cannot merge a parameter, i.e. if only the name is defined: "fun -a" var definedParameterNames = (from param in _scriptBlockInfo.GetParameters() select param.Name.VariablePath.UserPath).ToList(); var oldParameters = new Collection<CommandParameter>(new List<CommandParameter>(Parameters)); Parameters.Clear(); int numParams = oldParameters.Count; for (int i = 0; i < numParams; i++) { var current = oldParameters[i]; var peek = (i < numParams - 1) ? oldParameters[i + 1] : null; // if we have a no name, or a value different to null (or explicitly null), just take it // otherwise it would have been merged before if (String.IsNullOrEmpty(current.Name) || current.Value != null || current.HasExplicitArgument) { Parameters.Add(current); continue; } // the current parameter has no argument (and not explicilty set to null), try to merge the next if (peek != null && String.IsNullOrEmpty(peek.Name)) { Parameters.Add(current.Name, peek.Value); i++; //because of merge } // the next parameter might also be '-b' without "b" being a defined parameter, then we take it // as value else if (peek != null && peek.Value == null && !definedParameterNames.Contains(peek.Name)) { Parameters.Add(current.Name, peek.GetDecoratedName()); i++; //because of merge } else if (definedParameterNames.Contains(current.Name)) { // otherwise we don't have a value for this named parameter, throw an error throw new ParameterBindingException("Missing argument for parameter '" + current.Name + "'"); } else { // this happens on an named parameter that is not part of the parameter definition Parameters.Add(current); } } } } }
WimObiwan/Pash
Source/System.Management/Pash/Implementation/ScriptBlockProcessor.cs
C#
bsd-3-clause
8,405
from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth import get_user_model from django.contrib.auth.hashers import get_hasher from django.contrib.auth.models import ( AbstractUser, Group, Permission, User, UserManager, ) from django.contrib.contenttypes.models import ContentType from django.core import mail from django.db.models.signals import post_save from django.test import TestCase, mock, override_settings class NaturalKeysTestCase(TestCase): def test_user_natural_key(self): staff_user = User.objects.create_user(username='staff') self.assertEqual(User.objects.get_by_natural_key('staff'), staff_user) self.assertEqual(staff_user.natural_key(), ('staff',)) def test_group_natural_key(self): users_group = Group.objects.create(name='users') self.assertEqual(Group.objects.get_by_natural_key('users'), users_group) class LoadDataWithoutNaturalKeysTestCase(TestCase): fixtures = ['regular.json'] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username='my_username') group = Group.objects.get(name='my_group') self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysTestCase(TestCase): fixtures = ['natural.json'] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username='my_username') group = Group.objects.get(name='my_group') self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase): multi_db = True def test_load_data_with_user_permissions(self): # Create test contenttypes for both databases default_objects = [ ContentType.objects.db_manager('default').create( model='examplemodela', app_label='app_a', ), ContentType.objects.db_manager('default').create( model='examplemodelb', app_label='app_b', ), ] other_objects = [ ContentType.objects.db_manager('other').create( model='examplemodelb', app_label='app_b', ), ContentType.objects.db_manager('other').create( model='examplemodela', app_label='app_a', ), ] # Now we create the test UserPermission Permission.objects.db_manager("default").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=default_objects[1], ) Permission.objects.db_manager("other").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=other_objects[0], ) perm_default = Permission.objects.get_by_natural_key( 'delete_examplemodelb', 'app_b', 'examplemodelb', ) perm_other = Permission.objects.db_manager('other').get_by_natural_key( 'delete_examplemodelb', 'app_b', 'examplemodelb', ) self.assertEqual(perm_default.content_type_id, default_objects[1].id) self.assertEqual(perm_other.content_type_id, other_objects[0].id) class UserManagerTestCase(TestCase): def test_create_user(self): email_lowercase = 'normal@normal.com' user = User.objects.create_user('user', email_lowercase) self.assertEqual(user.email, email_lowercase) self.assertEqual(user.username, 'user') self.assertFalse(user.has_usable_password()) def test_create_user_email_domain_normalize_rfc3696(self): # According to http://tools.ietf.org/html/rfc3696#section-3 # the "@" symbol can be part of the local part of an email address returned = UserManager.normalize_email(r'Abc\@DEF@EXAMPLE.com') self.assertEqual(returned, r'Abc\@DEF@example.com') def test_create_user_email_domain_normalize(self): returned = UserManager.normalize_email('normal@DOMAIN.COM') self.assertEqual(returned, 'normal@domain.com') def test_create_user_email_domain_normalize_with_whitespace(self): returned = UserManager.normalize_email('email\ with_whitespace@D.COM') self.assertEqual(returned, 'email\ with_whitespace@d.com') def test_empty_username(self): with self.assertRaisesMessage(ValueError, 'The given username must be set'): User.objects.create_user(username='') def test_create_user_is_staff(self): email = 'normal@normal.com' user = User.objects.create_user('user', email, is_staff=True) self.assertEqual(user.email, email) self.assertEqual(user.username, 'user') self.assertTrue(user.is_staff) def test_create_super_user_raises_error_on_false_is_superuser(self): with self.assertRaisesMessage(ValueError, 'Superuser must have is_superuser=True.'): User.objects.create_superuser( username='test', email='test@test.com', password='test', is_superuser=False, ) def test_create_superuser_raises_error_on_false_is_staff(self): with self.assertRaisesMessage(ValueError, 'Superuser must have is_staff=True.'): User.objects.create_superuser( username='test', email='test@test.com', password='test', is_staff=False, ) class AbstractUserTestCase(TestCase): def test_email_user(self): # valid send_mail parameters kwargs = { "fail_silently": False, "auth_user": None, "auth_password": None, "connection": None, "html_message": None, } abstract_user = AbstractUser(email='foo@bar.com') abstract_user.email_user(subject="Subject here", message="This is a message", from_email="from@domain.com", **kwargs) # Test that one message has been sent. self.assertEqual(len(mail.outbox), 1) # Verify that test email contains the correct attributes: message = mail.outbox[0] self.assertEqual(message.subject, "Subject here") self.assertEqual(message.body, "This is a message") self.assertEqual(message.from_email, "from@domain.com") self.assertEqual(message.to, [abstract_user.email]) def test_last_login_default(self): user1 = User.objects.create(username='user1') self.assertIsNone(user1.last_login) user2 = User.objects.create_user(username='user2') self.assertIsNone(user2.last_login) def test_user_double_save(self): """ Calling user.save() twice should trigger password_changed() once. """ user = User.objects.create_user(username='user', password='foo') user.set_password('bar') with mock.patch('django.contrib.auth.password_validation.password_changed') as pw_changed: user.save() self.assertEqual(pw_changed.call_count, 1) user.save() self.assertEqual(pw_changed.call_count, 1) @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) def test_check_password_upgrade(self): """ password_changed() shouldn't be called if User.check_password() triggers a hash iteration upgrade. """ user = User.objects.create_user(username='user', password='foo') initial_password = user.password self.assertTrue(user.check_password('foo')) hasher = get_hasher('default') self.assertEqual('pbkdf2_sha256', hasher.algorithm) old_iterations = hasher.iterations try: # Upgrade the password iterations hasher.iterations = old_iterations + 1 with mock.patch('django.contrib.auth.password_validation.password_changed') as pw_changed: user.check_password('foo') self.assertEqual(pw_changed.call_count, 0) self.assertNotEqual(initial_password, user.password) finally: hasher.iterations = old_iterations class IsActiveTestCase(TestCase): """ Tests the behavior of the guaranteed is_active attribute """ def test_builtin_user_isactive(self): user = User.objects.create(username='foo', email='foo@bar.com') # is_active is true by default self.assertEqual(user.is_active, True) user.is_active = False user.save() user_fetched = User.objects.get(pk=user.pk) # the is_active flag is saved self.assertFalse(user_fetched.is_active) @override_settings(AUTH_USER_MODEL='auth_tests.IsActiveTestUser1') def test_is_active_field_default(self): """ tests that the default value for is_active is provided """ UserModel = get_user_model() user = UserModel(username='foo') self.assertEqual(user.is_active, True) # you can set the attribute - but it will not save user.is_active = False # there should be no problem saving - but the attribute is not saved user.save() user_fetched = UserModel._default_manager.get(pk=user.pk) # the attribute is always true for newly retrieved instance self.assertEqual(user_fetched.is_active, True) class TestCreateSuperUserSignals(TestCase): """ Simple test case for ticket #20541 """ def post_save_listener(self, *args, **kwargs): self.signals_count += 1 def setUp(self): self.signals_count = 0 post_save.connect(self.post_save_listener, sender=User) def tearDown(self): post_save.disconnect(self.post_save_listener, sender=User) def test_create_user(self): User.objects.create_user("JohnDoe") self.assertEqual(self.signals_count, 1) def test_create_superuser(self): User.objects.create_superuser("JohnDoe", "mail@example.com", "1") self.assertEqual(self.signals_count, 1)
vincepandolfo/django
tests/auth_tests/test_models.py
Python
bsd-3-clause
10,053
# frozen_string_literal: true module Spree module Admin class ShippingCategoriesController < ResourceController end end end
pervino/solidus
backend/app/controllers/spree/admin/shipping_categories_controller.rb
Ruby
bsd-3-clause
137
// Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "tools/fiddle/examples.h" // HASH=72d41f890203109a41f589a7403acae9 REG_FIDDLE(Paint_getColor, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkPaint paint; paint.setColor(SK_ColorYELLOW); SkColor y = paint.getColor(); SkDebugf("Yellow is %d%% red, %d%% green, and %d%% blue.\n", (int) (SkColorGetR(y) / 2.55f), (int) (SkColorGetG(y) / 2.55f), (int) (SkColorGetB(y) / 2.55f)); } } // END FIDDLE
youtube/cobalt
third_party/skia_next/third_party/skia/docs/examples/Paint_getColor.cpp
C++
bsd-3-clause
567
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\validators; use Yii; /** * RequiredValidator validates that the specified attribute does not have null or empty value. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class RequiredValidator extends Validator { /** * @var boolean whether to skip this validator if the value being validated is empty. */ public $skipOnEmpty = false; /** * @var mixed the desired value that the attribute must have. * If this is null, the validator will validate that the specified attribute is not empty. * If this is set as a value that is not null, the validator will validate that * the attribute has a value that is the same as this property value. * Defaults to null. * @see strict */ public $requiredValue; /** * @var boolean whether the comparison between the attribute value and [[requiredValue]] is strict. * When this is true, both the values and types must match. * Defaults to false, meaning only the values need to match. * Note that when [[requiredValue]] is null, if this property is true, the validator will check * if the attribute value is null; If this property is false, the validator will call [[isEmpty]] * to check if the attribute value is empty. */ public $strict = false; /** * @var string the user-defined error message. It may contain the following placeholders which * will be replaced accordingly by the validator: * * - `{attribute}`: the label of the attribute being validated * - `{value}`: the value of the attribute being validated * - `{requiredValue}`: the value of [[requiredValue]] */ public $message; /** * @inheritdoc */ public function init() { parent::init(); if ($this->message === null) { $this->message = $this->requiredValue === null ? Yii::t('yii', '{attribute} cannot be blank.') : Yii::t('yii', '{attribute} must be "{requiredValue}".'); } } /** * @inheritdoc */ protected function validateValue($value) { if ($this->requiredValue === null) { if ($this->strict && $value !== null || !$this->strict && !$this->isEmpty(is_string($value) ? trim($value) : $value)) { return null; } } elseif (!$this->strict && $value == $this->requiredValue || $this->strict && $value === $this->requiredValue) { return null; } if ($this->requiredValue === null) { return [$this->message, []]; } else { return [$this->message, [ 'requiredValue' => $this->requiredValue, ]]; } } /** * @inheritdoc */ public function clientValidateAttribute($model, $attribute, $view) { $options = []; if ($this->requiredValue !== null) { $options['message'] = Yii::$app->getI18n()->format($this->message, [ 'requiredValue' => $this->requiredValue, ], Yii::$app->language); $options['requiredValue'] = $this->requiredValue; } else { $options['message'] = $this->message; } if ($this->strict) { $options['strict'] = 1; } $options['message'] = Yii::$app->getI18n()->format($options['message'], [ 'attribute' => $model->getAttributeLabel($attribute), ], Yii::$app->language); ValidationAsset::register($view); return 'yii.validation.required(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; } }
nikn/it-asu.ru
vendor/yiisoft/yii2/validators/RequiredValidator.php
PHP
bsd-3-clause
3,936
// Copyright 2014 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 "third_party/blink/renderer/core/css/style_rule_keyframe.h" #include <memory> #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css/parser/css_parser.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { StyleRuleKeyframe::StyleRuleKeyframe(std::unique_ptr<Vector<double>> keys, CSSPropertyValueSet* properties) : StyleRuleBase(kKeyframe), properties_(properties), keys_(*keys) {} String StyleRuleKeyframe::KeyText() const { DCHECK(!keys_.IsEmpty()); StringBuilder key_text; for (unsigned i = 0; i < keys_.size(); ++i) { if (i) key_text.Append(", "); key_text.AppendNumber(keys_.at(i) * 100); key_text.Append('%'); } return key_text.ReleaseString(); } bool StyleRuleKeyframe::SetKeyText(const String& key_text) { DCHECK(!key_text.IsNull()); std::unique_ptr<Vector<double>> keys = CSSParser::ParseKeyframeKeyList(key_text); if (!keys || keys->IsEmpty()) return false; keys_ = *keys; return true; } const Vector<double>& StyleRuleKeyframe::Keys() const { return keys_; } MutableCSSPropertyValueSet& StyleRuleKeyframe::MutableProperties() { if (!properties_->IsMutable()) properties_ = properties_->MutableCopy(); return *To<MutableCSSPropertyValueSet>(properties_.Get()); } String StyleRuleKeyframe::CssText() const { StringBuilder result; result.Append(KeyText()); result.Append(" { "); String decls = properties_->AsText(); result.Append(decls); if (!decls.IsEmpty()) result.Append(' '); result.Append('}'); return result.ReleaseString(); } void StyleRuleKeyframe::TraceAfterDispatch(blink::Visitor* visitor) const { visitor->Trace(properties_); StyleRuleBase::TraceAfterDispatch(visitor); } } // namespace blink
scheib/chromium
third_party/blink/renderer/core/css/style_rule_keyframe.cc
C++
bsd-3-clause
2,030
// Copyright 2020 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 "components/feed/core/v2/public/feed_api.h" namespace feed { FeedApi::FeedApi() = default; FeedApi::~FeedApi() = default; } // namespace feed
scheib/chromium
components/feed/core/v2/public/feed_api.cc
C++
bsd-3-clause
321
// 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. #ifndef TOOLS_ANDROID_FORWARDER2_SOCKET_H_ #define TOOLS_ANDROID_FORWARDER2_SOCKET_H_ #include <fcntl.h> #include <netinet/in.h> #include <stddef.h> #include <sys/socket.h> #include <sys/un.h> #include <string> #include <vector> namespace forwarder2 { // Wrapper class around unix socket api. Can be used to create, bind or // connect to both Unix domain sockets and TCP sockets. // TODO(pliard): Split this class into TCPSocket and UnixDomainSocket. class Socket { public: Socket(); Socket(const Socket&) = delete; Socket& operator=(const Socket&) = delete; ~Socket(); bool BindUnix(const std::string& path); bool BindTcp(const std::string& host, int port); bool ConnectUnix(const std::string& path); bool ConnectTcp(const std::string& host, int port); // Just a wrapper around unix socket shutdown(), see man 2 shutdown. void Shutdown(); // Just a wrapper around unix socket close(), see man 2 close. void Close(); bool IsClosed() const { return socket_ < 0; } int fd() const { return socket_; } bool Accept(Socket* new_socket); // Returns the port allocated to this socket or zero on error. int GetPort(); // Just a wrapper around unix read() function. // Reads up to buffer_size, but may read less than buffer_size. // Returns the number of bytes read. int Read(void* buffer, size_t buffer_size); // Same as Read() but with a timeout. int ReadWithTimeout(void* buffer, size_t buffer_size, int timeout_secs); // Non-blocking version of Read() above. This must be called after a // successful call to select(). The socket must also be in non-blocking mode // before calling this method. int NonBlockingRead(void* buffer, size_t buffer_size); // Wrapper around send(). int Write(const void* buffer, size_t count); // Same as NonBlockingRead() but for writing. int NonBlockingWrite(const void* buffer, size_t count); // Calls Read() multiple times until num_bytes is written to the provided // buffer. No bounds checking is performed. // Returns number of bytes read, which can be different from num_bytes in case // of errror. int ReadNumBytes(void* buffer, size_t num_bytes); // Same as ReadNumBytes() but with a timeout. int ReadNumBytesWithTimeout(void* buffer, size_t num_bytes, int timeout_secs); // Calls Write() multiple times until num_bytes is written. No bounds checking // is performed. Returns number of bytes written, which can be different from // num_bytes in case of errror. int WriteNumBytes(const void* buffer, size_t num_bytes); // Calls WriteNumBytes for the given std::string. Note that the null // terminator is not written to the socket. int WriteString(const std::string& buffer); bool has_error() const { return socket_error_; } // |event_fd| must be a valid pipe file descriptor created from the // PipeNotifier and must live (not be closed) at least as long as this socket // is alive. void AddEventFd(int event_fd); // Returns whether Accept() or Connect() was interrupted because the socket // received an external event fired through the provided fd. bool DidReceiveEventOnFd(int fd) const; bool DidReceiveEvent() const; static pid_t GetUnixDomainSocketProcessOwner(const std::string& path); private: enum EventType { READ, WRITE }; union SockAddr { // IPv4 sockaddr sockaddr_in addr4; // IPv6 sockaddr sockaddr_in6 addr6; // Unix Domain sockaddr sockaddr_un addr_un; }; struct Event { int fd; bool was_fired; }; bool SetNonBlocking(); // If |host| is empty, use localhost. bool InitTcpSocket(const std::string& host, int port); bool InitUnixSocket(const std::string& path); bool BindAndListen(); bool Connect(); bool Resolve(const std::string& host); bool InitSocketInternal(); void SetSocketError(); // Waits until a read or write i/o event has happened. bool WaitForEvent(EventType type, int timeout_secs); int socket_; int port_; bool socket_error_; // Family of the socket (AF_INET, AF_INET6 or PF_UNIX). int family_; SockAddr addr_; // Points to one of the members of the above union depending on the family. sockaddr* addr_ptr_; // Length of one of the members of the above union depending on the family. socklen_t addr_len_; // Used to listen for external events (e.g. process received a SIGTERM) while // blocking on I/O operations. std::vector<Event> events_; }; } // namespace forwarder #endif // TOOLS_ANDROID_FORWARDER2_SOCKET_H_
chromium/chromium
tools/android/forwarder2/socket.h
C
bsd-3-clause
4,699
// Copyright 2017 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/resource_coordinator/lifecycle_unit.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace resource_coordinator { TEST(LifecycleUnitTest, SortKeyComparison) { constexpr base::TimeTicks kBaseTime; LifecycleUnit::SortKey a(kBaseTime); LifecycleUnit::SortKey b(kBaseTime + base::Hours(1)); LifecycleUnit::SortKey c(kBaseTime + base::Hours(2)); EXPECT_FALSE(a < a); EXPECT_TRUE(a < b); EXPECT_TRUE(a < c); EXPECT_FALSE(b < a); EXPECT_FALSE(b < b); EXPECT_TRUE(b < c); EXPECT_FALSE(c < a); EXPECT_FALSE(c < b); EXPECT_FALSE(c < c); EXPECT_FALSE(a > a); EXPECT_FALSE(a > b); EXPECT_FALSE(a > c); EXPECT_TRUE(b > a); EXPECT_FALSE(b > b); EXPECT_FALSE(b > c); EXPECT_TRUE(c > a); EXPECT_TRUE(c > b); EXPECT_FALSE(c > c); } } // namespace resource_coordinator
ric2b/Vivaldi-browser
chromium/chrome/browser/resource_coordinator/lifecycle_unit_unittest.cc
C++
bsd-3-clause
1,030
// 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. #ifndef CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_REQUESTOR_MOCK_H_ #define CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_REQUESTOR_MOCK_H_ #include <memory> #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "testing/gmock/include/gmock/gmock.h" namespace content { class ClientCertificateDelegate; } namespace net { class SSLCertRequestInfo; class SSLPrivateKey; class X509Certificate; } class SSLClientAuthRequestorMock : public base::RefCountedThreadSafe<SSLClientAuthRequestorMock> { public: explicit SSLClientAuthRequestorMock( const scoped_refptr<net::SSLCertRequestInfo>& cert_request_info); std::unique_ptr<content::ClientCertificateDelegate> CreateDelegate(); void WaitForCompletion(); MOCK_METHOD2(CertificateSelected, void(net::X509Certificate* cert, net::SSLPrivateKey* key)); MOCK_METHOD0(CancelCertificateSelection, void()); scoped_refptr<net::SSLCertRequestInfo> cert_request_info_; protected: friend class base::RefCountedThreadSafe<SSLClientAuthRequestorMock>; virtual ~SSLClientAuthRequestorMock(); private: base::RunLoop run_loop_; }; #endif // CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_REQUESTOR_MOCK_H_
ric2b/Vivaldi-browser
chromium/chrome/browser/ssl/ssl_client_auth_requestor_mock.h
C
bsd-3-clause
1,350
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Constraints; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; use Symfony\Component\PropertyAccess\PropertyPath; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Exception\RuntimeException; use Symfony\Component\Validator\Exception\UnexpectedTypeException; /** * @author Fabien Potencier <fabien@symfony.com> * @author Bernhard Schussek <bschussek@symfony.com> */ class ExpressionValidator extends ConstraintValidator { /** * @var PropertyAccessorInterface */ private $propertyAccessor; /** * @var ExpressionLanguage */ private $expressionLanguage; /** * @param PropertyAccessorInterface|null $propertyAccessor Optional as of Symfony 2.5 * * @throws UnexpectedTypeException If the property accessor is invalid */ public function __construct($propertyAccessor = null) { if (null !== $propertyAccessor && !$propertyAccessor instanceof PropertyAccessorInterface) { throw new UnexpectedTypeException($propertyAccessor, 'null or \Symfony\Component\PropertyAccess\PropertyAccessorInterface'); } $this->propertyAccessor = $propertyAccessor; } /** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof Expression) { throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression'); } $variables = array(); // Symfony 2.5+ if ($this->context instanceof ExecutionContextInterface) { $variables['value'] = $value; $variables['this'] = $this->context->getObject(); } elseif (null === $this->context->getPropertyName()) { $variables['value'] = $value; $variables['this'] = $value; } else { $root = $this->context->getRoot(); $variables['value'] = $value; if (is_object($root)) { // Extract the object that the property belongs to from the object // graph $path = new PropertyPath($this->context->getPropertyPath()); $parentPath = $path->getParent(); $variables['this'] = $parentPath ? $this->getPropertyAccessor()->getValue($root, $parentPath) : $root; } else { $variables['this'] = null; } } if (!$this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) { $this->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->addViolation(); } } private function getExpressionLanguage() { if (null === $this->expressionLanguage) { if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); } $this->expressionLanguage = new ExpressionLanguage(); } return $this->expressionLanguage; } private function getPropertyAccessor() { if (null === $this->propertyAccessor) { if (!class_exists('Symfony\Component\PropertyAccess\PropertyAccess')) { throw new RuntimeException('Unable to use expressions as the Symfony PropertyAccess component is not installed.'); } $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); } return $this->propertyAccessor; } }
KaberMohamed/Symfony2015
vendor_bis/symfony/symfony/src/Symfony/Component/Validator/Constraints/ExpressionValidator.php
PHP
mit
4,126
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.WebSites { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// DeletedWebAppsOperations operations. /// </summary> public partial interface IDeletedWebAppsOperations { /// <summary> /// Get all deleted apps for a subscription. /// </summary> /// <remarks> /// Description for Get all deleted apps for a subscription. /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DeletedSite>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get all deleted apps for a subscription at location /// </summary> /// <remarks> /// Description for Get all deleted apps for a subscription at location /// </remarks> /// <param name='location'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DeletedSite>>> ListByLocationWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get deleted app for a subscription at location. /// </summary> /// <remarks> /// Description for Get deleted app for a subscription at location. /// </remarks> /// <param name='location'> /// </param> /// <param name='deletedSiteId'> /// The numeric ID of the deleted app, e.g. 12345 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<DeletedSite>> GetDeletedWebAppByLocationWithHttpMessagesAsync(string location, string deletedSiteId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get all deleted apps for a subscription. /// </summary> /// <remarks> /// Description for Get all deleted apps for a subscription. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DeletedSite>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get all deleted apps for a subscription at location /// </summary> /// <remarks> /// Description for Get all deleted apps for a subscription at location /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<DeletedSite>>> ListByLocationNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
brjohnstmsft/azure-sdk-for-net
sdk/websites/Microsoft.Azure.Management.WebSites/src/Generated/IDeletedWebAppsOperations.cs
C#
mit
6,915
version https://git-lfs.github.com/spec/v1 oid sha256:6d892a968416beb2a729a7a7c70ce98f5ecc460471aa6fce2bcc1c2d8d880865 size 3104
yogeshsaroya/new-cdnjs
ajax/libs/pace/0.7.1/themes/white/pace-theme-mac-osx.css
CSS
mit
129
<!-- Your new widget html -->
stewartmckee/dashing-rails
lib/generators/templates/widgets/new.html
HTML
mit
30
import {ListWrapper} from '@angular/facade'; import {OpaqueToken} from '@angular/core/src/di'; import {Validator} from '../validator'; import {Statistic} from '../statistic'; import {MeasureValues} from '../measure_values'; /** * A validator that checks the regression slope of a specific metric. * Waits for the regression slope to be >=0. */ export class RegressionSlopeValidator extends Validator { // TODO(tbosch): use static values when our transpiler supports them static get SAMPLE_SIZE(): OpaqueToken { return _SAMPLE_SIZE; } // TODO(tbosch): use static values when our transpiler supports them static get METRIC(): OpaqueToken { return _METRIC; } // TODO(tbosch): use static values when our transpiler supports them static get PROVIDERS(): any[] { return _PROVIDERS; } _sampleSize: number; _metric: string; constructor(sampleSize, metric) { super(); this._sampleSize = sampleSize; this._metric = metric; } describe(): {[key: string]: any} { return {'sampleSize': this._sampleSize, 'regressionSlopeMetric': this._metric}; } validate(completeSample: MeasureValues[]): MeasureValues[] { if (completeSample.length >= this._sampleSize) { var latestSample = ListWrapper.slice(completeSample, completeSample.length - this._sampleSize, completeSample.length); var xValues = []; var yValues = []; for (var i = 0; i < latestSample.length; i++) { // For now, we only use the array index as x value. // TODO(tbosch): think about whether we should use time here instead xValues.push(i); yValues.push(latestSample[i].values[this._metric]); } var regressionSlope = Statistic.calculateRegressionSlope( xValues, Statistic.calculateMean(xValues), yValues, Statistic.calculateMean(yValues)); return regressionSlope >= 0 ? latestSample : null; } else { return null; } } } var _SAMPLE_SIZE = new OpaqueToken('RegressionSlopeValidator.sampleSize'); var _METRIC = new OpaqueToken('RegressionSlopeValidator.metric'); var _PROVIDERS = [ { provide: RegressionSlopeValidator useFactory: (sampleSize, metric) => new RegressionSlopeValidator(sampleSize, metric), deps: [_SAMPLE_SIZE, _METRIC] }, {provide: _SAMPLE_SIZE, useValue: 10}, {provide: _METRIC, useValue: 'scriptTime'} ];
hterkelsen/angular
modules/benchpress/src/validator/regression_slope_validator.ts
TypeScript
mit
2,380
export const EXAMPLE_REPOSITORIES = { clock: { repo: 'https://github.com/meteor/clock' }, leaderboard: { repo: 'https://github.com/meteor/leaderboard' }, localmarket: { repo: 'https://github.com/meteor/localmarket' }, 'simple-todos': { repo: 'https://github.com/meteor/simple-todos' }, 'simple-todos-react': { repo: 'https://github.com/meteor/simple-todos-react' }, 'simple-todos-angular': { repo: 'https://github.com/meteor/simple-todos-angular' }, todos: { repo: 'https://github.com/meteor/todos' }, 'todos-react': { 'repo': 'https://github.com/meteor/todos', 'branch': 'react', }, 'angular2-boilerplate': { repo: 'https://github.com/bsliran/angular2-meteor-base' } };
mjmasn/meteor
tools/cli/example-repositories.js
JavaScript
mit
717
@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0\..\wellknown\cli.js" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node "%~dp0\..\wellknown\cli.js" %* )
cdeerr/esportsMKE
web/node_modules/sequelize/node_modules/.bin/wellknown.cmd
Batchfile
mit
174
<html lang="en"> <head> <title>fmax - Untitled</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Untitled"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Math.html#Math" title="Math"> <link rel="prev" href="fma.html#fma" title="fma"> <link rel="next" href="fmin.html#fmin" title="fmin"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="fmax"></a> Next:&nbsp;<a rel="next" accesskey="n" href="fmin.html#fmin">fmin</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="fma.html#fma">fma</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Math.html#Math">Math</a> <hr> </div> <h3 class="section">1.23 <code>fmax</code>, <code>fmaxf</code>&mdash;maximum</h3> <p><a name="index-fmax-57"></a><a name="index-fmaxf-58"></a><strong>Synopsis</strong> <pre class="example"> #include &lt;math.h&gt; double fmax(double <var>x</var>, double <var>y</var>); float fmaxf(float <var>x</var>, float <var>y</var>); </pre> <p><strong>Description</strong><br> The <code>fmax</code> functions determine the maximum numeric value of their arguments. NaN arguments are treated as missing data: if one argument is a NaN and the other numeric, then the <code>fmax</code> functions choose the numeric value. <pre class="sp"> </pre> <strong>Returns</strong><br> The <code>fmax</code> functions return the maximum numeric value of their arguments. <pre class="sp"> </pre> <strong>Portability</strong><br> ANSI C, POSIX. <pre class="sp"> </pre> </body></html>
ChangsoonKim/STM32F7DiscTutor
toolchain/osx/gcc-arm-none-eabi-6-2017-q1-update/share/doc/gcc-arm-none-eabi/html/libm/fmax.html
HTML
mit
2,234
require File.dirname(__FILE__) + '/../../../../spec_helper' require 'net/http' require File.dirname(__FILE__) + "/shared/request_put" describe "Net::HTTP#put2" do it_behaves_like :net_ftp_request_put, :put2 end
luccastera/rubyspec
library/net/http/http/put2_spec.rb
Ruby
mit
213
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "model_types.h" #include "vcollide.h" #include "vcollide_parse.h" #include "solidsetdefaults.h" #include "bone_setup.h" #include "engine/ivmodelinfo.h" #include "physics.h" #include "c_breakableprop.h" #include "view.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_CLIENTCLASS_DT(C_BreakableProp, DT_BreakableProp, CBreakableProp) END_RECV_TABLE() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_BreakableProp::C_BreakableProp( void ) { m_takedamage = DAMAGE_YES; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BreakableProp::SetFadeMinMax( float fademin, float fademax ) { m_fadeMinDist = fademin; m_fadeMaxDist = fademax; } //----------------------------------------------------------------------------- // Copy fade from another breakable prop //----------------------------------------------------------------------------- void C_BreakableProp::CopyFadeFrom( C_BreakableProp *pSource ) { m_flFadeScale = pSource->m_flFadeScale; }
scen/ionlib
src/sdk/hl2_ob/game/client/c_breakableprop.cpp
C++
mit
1,477
# Bootstrappable Bitcoin Core Builds This directory contains the files necessary to perform bootstrappable Bitcoin Core builds. [Bootstrappability][b17e] furthers our binary security guarantees by allowing us to _audit and reproduce_ our toolchain instead of blindly _trusting_ binary downloads. We achieve bootstrappability by using Guix as a functional package manager. # Requirements Conservatively, you will need an x86_64 machine with: - 16GB of free disk space on the partition that /gnu/store will reside in - 8GB of free disk space **per platform triple** you're planning on building (see the `HOSTS` [environment variable description][env-vars-list]) # Installation and Setup If you don't have Guix installed and set up, please follow the instructions in [INSTALL.md](./INSTALL.md) # Usage If you haven't considered your security model yet, please read [the relevant section](#choosing-your-security-model) before proceeding to perform a build. ## Making the Xcode SDK available for macOS cross-compilation In order to perform a build for macOS (which is included in the default set of platform triples to build), you'll need to extract the macOS SDK tarball using tools found in the [`macdeploy` directory](../macdeploy/README.md). You can then either point to the SDK using the `SDK_PATH` environment variable: ```sh # Extract the SDK tarball to /path/to/parent/dir/of/extracted/SDK/Xcode-<foo>-<bar>-extracted-SDK-with-libcxx-headers tar -C /path/to/parent/dir/of/extracted/SDK -xaf /path/to/Xcode-<foo>-<bar>-extracted-SDK-with-libcxx-headers.tar.gz # Indicate where to locate the SDK tarball export SDK_PATH=/path/to/parent/dir/of/extracted/SDK ``` or extract it into `depends/SDKs`: ```sh mkdir -p depends/SDKs tar -C depends/SDKs -xaf /path/to/SDK/tarball ``` ## Building *The author highly recommends at least reading over the [common usage patterns and examples](#common-guix-build-invocation-patterns-and-examples) section below before starting a build. For a full list of customization options, see the [recognized environment variables][env-vars-list] section.* To build Bitcoin Core reproducibly with all default options, invoke the following from the top of a clean repository: ```sh ./contrib/guix/guix-build ``` ## Codesigning build outputs The `guix-codesign` command attaches codesignatures (produced by codesigners) to existing non-codesigned outputs. Please see the [release process documentation](/doc/release-process.md) for more context. It respects many of the same environment variable flags as `guix-build`, with 2 crucial differences: 1. Since only Windows and macOS build outputs require codesigning, the `HOSTS` environment variable will have a sane default value of `x86_64-w64-mingw32 x86_64-apple-darwin` instead of all the platforms. 2. The `guix-codesign` command ***requires*** a `DETACHED_SIGS_REPO` flag. * _**DETACHED_SIGS_REPO**_ Set the directory where detached codesignatures can be found for the current Bitcoin Core version being built. _REQUIRED environment variable_ An invocation with all default options would look like: ``` env DETACHED_SIGS_REPO=<path/to/bitcoin-detached-sigs> ./contrib/guix/guix-codesign ``` ## Cleaning intermediate work directories By default, `guix-build` leaves all intermediate files or "work directories" (e.g. `depends/work`, `guix-build-*/distsrc-*`) intact at the end of a build so that they are available to the user (to aid in debugging, etc.). However, these directories usually take up a large amount of disk space. Therefore, a `guix-clean` convenience script is provided which cleans the current `git` worktree to save disk space: ``` ./contrib/guix/guix-clean ``` ## Attesting to build outputs Much like how Gitian build outputs are attested to in a `gitian.sigs` repository, Guix build outputs are attested to in the [`guix.sigs` repository](https://github.com/bitcoin-core/guix.sigs). After you've cloned the `guix.sigs` repository, to attest to the current worktree's commit/tag: ``` env GUIX_SIGS_REPO=<path/to/guix.sigs> SIGNER=<gpg-key-name> ./contrib/guix/guix-attest ``` See `./contrib/guix/guix-attest --help` for more information on the various ways `guix-attest` can be invoked. ## Verifying build output attestations After at least one other signer has uploaded their signatures to the `guix.sigs` repository: ``` git -C <path/to/guix.sigs> pull env GUIX_SIGS_REPO=<path/to/guix.sigs> ./contrib/guix/guix-verify ``` ## Common `guix-build` invocation patterns and examples ### Keeping caches and SDKs outside of the worktree If you perform a lot of builds and have a bunch of worktrees, you may find it more efficient to keep the depends tree's download cache, build cache, and SDKs outside of the worktrees to avoid duplicate downloads and unnecessary builds. To help with this situation, the `guix-build` script honours the `SOURCES_PATH`, `BASE_CACHE`, and `SDK_PATH` environment variables and will pass them on to the depends tree so that you can do something like: ```sh env SOURCES_PATH="$HOME/depends-SOURCES_PATH" BASE_CACHE="$HOME/depends-BASE_CACHE" SDK_PATH="$HOME/macOS-SDKs" ./contrib/guix/guix-build ``` Note that the paths that these environment variables point to **must be directories**, and **NOT symlinks to directories**. See the [recognized environment variables][env-vars-list] section for more details. ### Building a subset of platform triples Sometimes you only want to build a subset of the supported platform triples, in which case you can override the default list by setting the space-separated `HOSTS` environment variable: ```sh env HOSTS='x86_64-w64-mingw32 x86_64-apple-darwin' ./contrib/guix/guix-build ``` See the [recognized environment variables][env-vars-list] section for more details. ### Controlling the number of threads used by `guix` build commands Depending on your system's RAM capacity, you may want to decrease the number of threads used to decrease RAM usage or vice versa. By default, the scripts under `./contrib/guix` will invoke all `guix` build commands with `--cores="$JOBS"`. Note that `$JOBS` defaults to `$(nproc)` if not specified. However, astute manual readers will also notice that `guix` build commands also accept a `--max-jobs=` flag (which defaults to 1 if unspecified). Here is the difference between `--cores=` and `--max-jobs=`: > Note: When I say "derivation," think "package" `--cores=` - controls the number of CPU cores to build each derivation. This is the value passed to `make`'s `--jobs=` flag. `--max-jobs=` - controls how many derivations can be built in parallel - defaults to 1 Therefore, the default is for `guix` build commands to build one derivation at a time, utilizing `$JOBS` threads. Specifying the `$JOBS` environment variable will only modify `--cores=`, but you can also modify the value for `--max-jobs=` by specifying `$ADDITIONAL_GUIX_COMMON_FLAGS`. For example, if you have a LOT of memory, you may want to set: ```sh export ADDITIONAL_GUIX_COMMON_FLAGS='--max-jobs=8' ``` Which allows for a maximum of 8 derivations to be built at the same time, each utilizing `$JOBS` threads. Or, if you'd like to avoid spurious build failures caused by issues with parallelism within a single package, but would still like to build multiple packages when the dependency graph allows for it, you may want to try: ```sh export JOBS=1 ADDITIONAL_GUIX_COMMON_FLAGS='--max-jobs=8' ``` See the [recognized environment variables][env-vars-list] section for more details. ## Recognized environment variables * _**HOSTS**_ Override the space-separated list of platform triples for which to perform a bootstrappable build. _(defaults to "x86\_64-linux-gnu arm-linux-gnueabihf aarch64-linux-gnu riscv64-linux-gnu powerpc64-linux-gnu powerpc64le-linux-gnu x86\_64-w64-mingw32 x86\_64-apple-darwin arm64-apple-darwin")_ * _**SOURCES_PATH**_ Set the depends tree download cache for sources. This is passed through to the depends tree. Setting this to the same directory across multiple builds of the depends tree can eliminate unnecessary redownloading of package sources. The path that this environment variable points to **must be a directory**, and **NOT a symlink to a directory**. * _**BASE_CACHE**_ Set the depends tree cache for built packages. This is passed through to the depends tree. Setting this to the same directory across multiple builds of the depends tree can eliminate unnecessary building of packages. The path that this environment variable points to **must be a directory**, and **NOT a symlink to a directory**. * _**SDK_PATH**_ Set the path where _extracted_ SDKs can be found. This is passed through to the depends tree. Note that this is should be set to the _parent_ directory of the actual SDK (e.g. `SDK_PATH=$HOME/Downloads/macOS-SDKs` instead of `$HOME/Downloads/macOS-SDKs/Xcode-12.2-12B45b-extracted-SDK-with-libcxx-headers`). The path that this environment variable points to **must be a directory**, and **NOT a symlink to a directory**. * _**JOBS**_ Override the number of jobs to run simultaneously, you might want to do so on a memory-limited machine. This may be passed to: - `guix` build commands as in `guix environment --cores="$JOBS"` - `make` as in `make --jobs="$JOBS"` - `xargs` as in `xargs -P"$JOBS"` See [here](#controlling-the-number-of-threads-used-by-guix-build-commands) for more details. _(defaults to the value of `nproc` outside the container)_ * _**SOURCE_DATE_EPOCH**_ Override the reference UNIX timestamp used for bit-for-bit reproducibility, the variable name conforms to [standard][r12e/source-date-epoch]. _(defaults to the output of `$(git log --format=%at -1)`)_ * _**V**_ If non-empty, will pass `V=1` to all `make` invocations, making `make` output verbose. Note that any given value is ignored. The variable is only checked for emptiness. More concretely, this means that `V=` (setting `V` to the empty string) is interpreted the same way as not setting `V` at all, and that `V=0` has the same effect as `V=1`. * _**SUBSTITUTE_URLS**_ A whitespace-delimited list of URLs from which to download pre-built packages. A URL is only used if its signing key is authorized (refer to the [substitute servers section](#option-1-building-with-substitutes) for more details). * _**ADDITIONAL_GUIX_COMMON_FLAGS**_ Additional flags to be passed to all `guix` commands. * _**ADDITIONAL_GUIX_TIMEMACHINE_FLAGS**_ Additional flags to be passed to `guix time-machine`. * _**ADDITIONAL_GUIX_ENVIRONMENT_FLAGS**_ Additional flags to be passed to the invocation of `guix environment` inside `guix time-machine`. # Choosing your security model No matter how you installed Guix, you need to decide on your security model for building packages with Guix. Guix allows us to achieve better binary security by using our CPU time to build everything from scratch. However, it doesn't sacrifice user choice in pursuit of this: users can decide whether or not to use **substitutes** (pre-built packages). ## Option 1: Building with substitutes ### Step 1: Authorize the signing keys Depending on the installation procedure you followed, you may have already authorized the Guix build farm key. In particular, the official shell installer script asks you if you want the key installed, and the debian distribution package authorized the key during installation. You can check the current list of authorized keys at `/etc/guix/acl`. At the time of writing, a `/etc/guix/acl` with just the Guix build farm key authorized looks something like: ```lisp (acl (entry (public-key (ecc (curve Ed25519) (q #8D156F295D24B0D9A86FA5741A840FF2D24F60F7B6C4134814AD55625971B394#) ) ) (tag (guix import) ) ) ) ``` If you've determined that the official Guix build farm key hasn't been authorized, and you would like to authorize it, run the following as root: ``` guix archive --authorize < /var/guix/profiles/per-user/root/current-guix/share/guix/ci.guix.gnu.org.pub ``` If `/var/guix/profiles/per-user/root/current-guix/share/guix/ci.guix.gnu.org.pub` doesn't exist, try: ```sh guix archive --authorize < <PREFIX>/share/guix/ci.guix.gnu.org.pub ``` Where `<PREFIX>` is likely: - `/usr` if you installed from a distribution package - `/usr/local` if you installed Guix from source and didn't supply any prefix-modifying flags to Guix's `./configure` For dongcarl's substitute server at https://guix.carldong.io, run as root: ```sh wget -qO- 'https://guix.carldong.io/signing-key.pub' | guix archive --authorize ``` #### Removing authorized keys To remove previously authorized keys, simply edit `/etc/guix/acl` and remove the `(entry (public-key ...))` entry. ### Step 2: Specify the substitute servers Once its key is authorized, the official Guix build farm at https://ci.guix.gnu.org is automatically used unless the `--no-substitutes` flag is supplied. This default list of substitute servers is overridable both on a `guix-daemon` level and when you invoke `guix` commands. See examples below for the various ways of adding dongcarl's substitute server after having [authorized his signing key](#authorize-the-signing-keys). Change the **default list** of substitute servers by starting `guix-daemon` with the `--substitute-urls` option (you will likely need to edit your init script): ```sh guix-daemon <cmd> --substitute-urls='https://guix.carldong.io https://ci.guix.gnu.org' ``` Override the default list of substitute servers by passing the `--substitute-urls` option for invocations of `guix` commands: ```sh guix <cmd> --substitute-urls='https://guix.carldong.io https://ci.guix.gnu.org' ``` For scripts under `./contrib/guix`, set the `SUBSTITUTE_URLS` environment variable: ```sh export SUBSTITUTE_URLS='https://guix.carldong.io https://ci.guix.gnu.org' ``` ## Option 2: Disabling substitutes on an ad-hoc basis If you prefer not to use any substitutes, make sure to supply `--no-substitutes` like in the following snippet. The first build will take a while, but the resulting packages will be cached for future builds. For direct invocations of `guix`: ```sh guix <cmd> --no-substitutes ``` For the scripts under `./contrib/guix/`: ```sh export ADDITIONAL_GUIX_COMMON_FLAGS='--no-substitutes' ``` ## Option 3: Disabling substitutes by default `guix-daemon` accepts a `--no-substitutes` flag, which will make sure that, unless otherwise overridden by a command line invocation, no substitutes will be used. If you start `guix-daemon` using an init script, you can edit said script to supply this flag. # Purging/Uninstalling Guix In the extraordinarily rare case where you messed up your Guix installation in an irreversible way, you may want to completely purge Guix from your system and start over. 1. Uninstall Guix itself according to the way you installed it (e.g. `sudo apt purge guix` for Ubuntu packaging, `sudo make uninstall` for a build from source). 2. Remove all build users and groups You may check for relevant users and groups using: ``` getent passwd | grep guix getent group | grep guix ``` Then, you may remove users and groups using: ``` sudo userdel <user> sudo groupdel <group> ``` 3. Remove all possible Guix-related directories - `/var/guix/` - `/var/log/guix/` - `/gnu/` - `/etc/guix/` - `/home/*/.config/guix/` - `/home/*/.cache/guix/` - `/home/*/.guix-profile/` - `/root/.config/guix/` - `/root/.cache/guix/` - `/root/.guix-profile/` [b17e]: https://bootstrappable.org/ [r12e/source-date-epoch]: https://reproducible-builds.org/docs/source-date-epoch/ [guix/install.sh]: https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh [guix/bin-install]: https://www.gnu.org/software/guix/manual/en/html_node/Binary-Installation.html [guix/env-setup]: https://www.gnu.org/software/guix/manual/en/html_node/Build-Environment-Setup.html [guix/substitutes]: https://www.gnu.org/software/guix/manual/en/html_node/Substitutes.html [guix/substitute-server-auth]: https://www.gnu.org/software/guix/manual/en/html_node/Substitute-Server-Authorization.html [guix/time-machine]: https://guix.gnu.org/manual/en/html_node/Invoking-guix-time_002dmachine.html [debian/guix-bullseye]: https://packages.debian.org/bullseye/guix [ubuntu/guix-hirsute]: https://packages.ubuntu.com/hirsute/guix [fanquake/guix-docker]: https://github.com/fanquake/core-review/tree/master/guix [env-vars-list]: #recognized-environment-variables
sstone/bitcoin
contrib/guix/README.md
Markdown
mit
16,633
// (C) Copyright John Maddock 2007. // Use, modification and distribution are subject to 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) // // This file is machine generated, do not edit by hand // Unrolled polynomial evaluation using second order Horners rule #ifndef BOOST_MATH_TOOLS_POLY_EVAL_11_HPP #define BOOST_MATH_TOOLS_POLY_EVAL_11_HPP namespace boost{ namespace math{ namespace tools{ namespace detail{ template <class T, class V> inline V evaluate_polynomial_c_imp(const T*, const V&, const std::integral_constant<int, 0>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(0); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V&, const std::integral_constant<int, 1>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 2>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(a[1] * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 3>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>((a[2] * x + a[1]) * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 4>*) BOOST_MATH_NOEXCEPT(V) { return static_cast<V>(((a[3] * x + a[2]) * x + a[1]) * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 5>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = static_cast<V>(a[4] * x2 + a[2]); t[1] = static_cast<V>(a[3] * x2 + a[1]); t[0] *= x2; t[0] += static_cast<V>(a[0]); t[1] *= x; return t[0] + t[1]; } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 6>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = a[5] * x2 + a[3]; t[1] = a[4] * x2 + a[2]; t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[0] *= x; return t[0] + t[1]; } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 7>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = static_cast<V>(a[6] * x2 + a[4]); t[1] = static_cast<V>(a[5] * x2 + a[3]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[0] *= x2; t[0] += static_cast<V>(a[0]); t[1] *= x; return t[0] + t[1]; } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 8>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = a[7] * x2 + a[5]; t[1] = a[6] * x2 + a[4]; t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[0] *= x; return t[0] + t[1]; } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 9>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = static_cast<V>(a[8] * x2 + a[6]); t[1] = static_cast<V>(a[7] * x2 + a[5]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[0] *= x2; t[0] += static_cast<V>(a[0]); t[1] *= x; return t[0] + t[1]; } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 10>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = a[9] * x2 + a[7]; t[1] = a[8] * x2 + a[6]; t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[0] *= x; return t[0] + t[1]; } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const std::integral_constant<int, 11>*) BOOST_MATH_NOEXCEPT(V) { V x2 = x * x; V t[2]; t[0] = static_cast<V>(a[10] * x2 + a[8]); t[1] = static_cast<V>(a[9] * x2 + a[7]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[5]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[0] *= x2; t[1] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[0] *= x2; t[0] += static_cast<V>(a[0]); t[1] *= x; return t[0] + t[1]; } }}}} // namespaces #endif // include guard
satya-das/common
third_party/boost_tp/boost/math/tools/detail/polynomial_horner3_11.hpp
C++
mit
4,947
package net.sf.jabref.gui.filelist; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.StringJoiner; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.event.TableModelEvent; import javax.swing.table.AbstractTableModel; import net.sf.jabref.gui.externalfiletype.ExternalFileType; import net.sf.jabref.gui.externalfiletype.ExternalFileTypes; import net.sf.jabref.gui.externalfiletype.UnknownExternalFileType; import net.sf.jabref.logic.util.io.FileUtil; import net.sf.jabref.model.entry.FileField; import net.sf.jabref.model.entry.ParsedFileField; /** * Data structure to contain a list of file links, parseable from a coded string. * Doubles as a table model for the file list editor. */ public class FileListTableModel extends AbstractTableModel { private final List<FileListEntry> list = new ArrayList<>(); @Override public int getRowCount() { synchronized (list) { return list.size(); } } @Override public int getColumnCount() { return 3; } @Override public Class<String> getColumnClass(int columnIndex) { return String.class; } @Override public Object getValueAt(int rowIndex, int columnIndex) { synchronized (list) { FileListEntry entry = list.get(rowIndex); switch (columnIndex) { case 0: return entry.description; case 1: return entry.link; default: return entry.type.isPresent() ? entry.type.get().getName() : ""; } } } public FileListEntry getEntry(int index) { synchronized (list) { return list.get(index); } } public void setEntry(int index, FileListEntry entry) { synchronized (list) { list.set(index, entry); fireTableRowsUpdated(index, index); } } public void removeEntry(int index) { synchronized (list) { list.remove(index); fireTableRowsDeleted(index, index); } } /** * Add an entry to the table model, and fire a change event. The change event * is fired on the event dispatch thread. * @param index The row index to insert the entry at. * @param entry The entry to insert. */ public void addEntry(final int index, final FileListEntry entry) { synchronized (list) { list.add(index, entry); if (SwingUtilities.isEventDispatchThread()) { fireTableRowsInserted(index, index); } else { SwingUtilities.invokeLater(() -> fireTableRowsInserted(index, index)); } } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { // Do nothing } /** * Set up the table contents based on the flat string representation of the file list * @param value The string representation */ public void setContent(String value) { setContent(value, false, true); } public void setContentDontGuessTypes(String value) { setContent(value, false, false); } private FileListEntry setContent(String val, boolean firstOnly, boolean deduceUnknownTypes) { String value = val; if (value == null) { value = ""; } List<ParsedFileField> fields = FileField.parse(value); List<FileListEntry> files = new ArrayList<>(); for(ParsedFileField entry : fields) { if (entry.isEmpty()) { continue; } if (firstOnly) { return decodeEntry(entry, deduceUnknownTypes); } else { files.add(decodeEntry(entry, deduceUnknownTypes)); } } synchronized (list) { list.clear(); list.addAll(files); } fireTableChanged(new TableModelEvent(this)); return null; } /** * Convenience method for finding a label corresponding to the type of the * first file link in the given field content. The difference between using * this method and using setContent() on an instance of FileListTableModel * is a slight optimization: with this method, parsing is discontinued after * the first entry has been found. * @param content The file field content, as fed to this class' setContent() method. * @return A JLabel set up with no text and the icon of the first entry's file type, * or null if no entry was found or the entry had no icon. */ public static JLabel getFirstLabel(String content) { FileListTableModel tm = new FileListTableModel(); FileListEntry entry = tm.setContent(content, true, true); if ((entry == null) || (!entry.type.isPresent())) { return null; } return entry.type.get().getIconLabel(); } private FileListEntry decodeEntry(ParsedFileField entry, boolean deduceUnknownType) { Optional<ExternalFileType> type = ExternalFileTypes.getInstance().getExternalFileTypeByName(entry.getFileType()); if (deduceUnknownType && (type.get() instanceof UnknownExternalFileType)) { // No file type was recognized. Try to find a usable file type based // on mime type: type = ExternalFileTypes.getInstance().getExternalFileTypeByMimeType(entry.getFileType()); if (!type.isPresent()) { // No type could be found from mime type on the extension: Optional<String> extension = FileUtil.getFileExtension(entry.getLink()); if (extension.isPresent()) { Optional<ExternalFileType> typeGuess = ExternalFileTypes.getInstance() .getExternalFileTypeByExt(extension.get()); if (typeGuess.isPresent()) { type = typeGuess; } } } } return new FileListEntry(entry.getDescription(), entry.getLink(), type); } /** * Transform the file list shown in the table into a flat string representable * as a BibTeX field: * @return String representation. */ public String getStringRepresentation() { synchronized (list) { String[][] array = new String[list.size()][]; int i = 0; for (FileListEntry entry : list) { array[i] = entry.getStringArrayRepresentation(); i++; } return FileField.encodeStringArray(array); } } /** * Transform the file list shown in the table into a HTML string representation * suitable for displaying the contents in a tooltip. * @return Tooltip representation. */ public String getToolTipHTMLRepresentation() { StringJoiner sb = new StringJoiner("<br>", "<html>", "</html>"); synchronized (list) { for (FileListEntry entry : list) { sb.add(String.format("%s (%s)", entry.description, entry.link)); } } return sb.toString(); } }
Mr-DLib/jabref
src/main/java/net/sf/jabref/gui/filelist/FileListTableModel.java
Java
mit
7,241
/* * $Id: JavaFunction.java,v 1.6 2006-12-22 14:06:40 thiago Exp $ * Copyright (C) 2003-2007 Kepler Project. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.keplerproject.luajava; /** * JavaFunction is a class that can be used to implement a Lua function in Java. * JavaFunction is an abstract class, so in order to use it you must extend this * class and implement the <code>execute</code> method. This <code>execute</code> * method is the method that will be called when you call the function from Lua. * To register the JavaFunction in Lua use the method <code>register(String name)</code>. */ public abstract class JavaFunction { /** * This is the state in which this function will exist. */ protected LuaState L; /** * This method is called from Lua. Any parameters can be taken with * <code>getParam</code>. A reference to the JavaFunctionWrapper itself is * always the first parameter received. Values passed back as results * of the function must be pushed onto the stack. * @return The number of values pushed onto the stack. */ public abstract int execute() throws LuaException; /** * Constructor that receives a LuaState. * @param L LuaState object associated with this JavaFunction object */ public JavaFunction(LuaState L) { this.L = L; } /** * Returns a parameter received from Lua. Parameters are numbered from 1. * A reference to the JavaFunction itself is always the first parameter * received (the same as <code>this</code>). * @param idx Index of the parameter. * @return Reference to parameter. * @see LuaObject */ public LuaObject getParam(int idx) { return L.getLuaObject(idx); } /** * Register a JavaFunction with a given name. This method registers in a * global variable the JavaFunction specified. * @param name name of the function. */ public void register(String name) throws LuaException { synchronized (L) { L.pushJavaFunction(this); L.setGlobal(name); } } }
bunnyblue/AndroLua
src/org/keplerproject/luajava/JavaFunction.java
Java
mit
3,034
{% from 'events/timetable/display/indico/_common.html' import render_speakers, render_references, render_description %} {% from 'attachments/_display.html' import render_attachments_folders %} {# Do not forget to update the conditions in the parent template when you add a new row in the details table. #} <div class="event-details"> {% if event.description %} <div class="event-details-row"> <div class="event-details-label">{% trans %}Description{% endtrans %}</div> <div class="event-details-content">{{ render_description(event, class='event-description') }}</div> </div> {% endif %} {% if event.references and event.type_.name == "meeting" %} <div class="event-details-row"> <div class="event-details-label">{% trans %}External references{% endtrans %}</div> <div class="event-details-content">{{ render_references(event) }}</div> </div> {% endif %} {% if files or folders %} <div class="event-details-row"> <div class="event-details-label icon-attachment inline-attachments-icon"></div> <div class="event-details-content material-list"> {{ render_attachments_folders(files=files, folders=folders) }} </div> </div> {% endif %} {% if lectures %} <div class="event-details-row"> <div class="event-details-label">{% trans %}From the same series{% endtrans %}</div> <div class="event-details-content"> {% for lecture in lectures %} <a href="{{ lecture.url }}" class="lecture-series-link">{{ lecture.series_pos }}</a> {% endfor %} </div> </div> {% endif %} {% if event.organizer_info %} <div class="event-details-row"> <div class="event-details-label">{% trans %}Organized by{% endtrans %}</div> <div class="event-details-content">{{ event.organizer_info | markdown }}</div> </div> {% endif %} {{ hook_event_header }} {% if event.contact_emails or event.contact_phones %} <div class="event-details-row"> <div class="event-details-label">{{ event.contact_title }}</div> <div class="event-details-content"> {% for email in event.contact_emails %} <div> <i class="icon-mail"></i> <a href="mailto:{{ email }}">{{ email }}</a> </div> {% endfor %} {% for phone in event.contact_phones %} <div> <i class="icon-phone"></i> <a href="tel:{{ phone }}">{{ phone }}</a> </div> {% endfor %} </div> </div> {% endif %} </div>
indico/indico
indico/modules/events/templates/display/indico/_details.html
HTML
mit
2,912
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:3:"cin";s:4:"type";s:7:"integer";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');
orlk/hopitrepo
app/cache/prod/annotations/75e5fdab246307ff8551aacf4481389716bc3adc$cin.cache.php
PHP
mit
260
<?php if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } class Tribe__Events__Pro__Shortcodes__Tribe_Events__Map { protected $shortcode; protected $date = ''; public function __construct( Tribe__Events__Pro__Shortcodes__Tribe_Events $shortcode ) { $this->shortcode = $shortcode; $this->setup(); $this->hooks(); } protected function hooks() { add_action( 'tribe_events_pro_tribe_events_shortcode_pre_render', array( $this, 'shortcode_pre_render' ) ); add_action( 'tribe_events_pro_tribe_events_shortcode_post_render', array( $this, 'shortcode_post_render' ) ); } protected function setup() { Tribe__Events__Main::instance()->displaying = 'map'; $this->shortcode->set_current_page(); $this->shortcode->prepare_default(); Tribe__Events__Pro__Main::instance()->enqueue_pro_scripts(); Tribe__Events__Pro__Template_Factory::asset_package( 'events-pro-css' ); Tribe__Events__Template_Factory::asset_package( 'jquery-placeholder' ); Tribe__Events__Pro__Template_Factory::asset_package( 'ajax-maps' ); $this->shortcode->set_template_object( new Tribe__Events__Pro__Templates__Map( $this->shortcode->get_query_args() ) ); } /** * Filters the baseurl of ugly links * * @param string $url URL to filter * * @return string */ public function filter_baseurl( $url ) { return trailingslashit( get_home_url( null, $GLOBALS['wp']->request ) ); } public function shortcode_pre_render() { add_filter( 'tribe_events_force_ugly_link', '__return_true' ); add_filter( 'tribe_events_ugly_link_baseurl', array( $this, 'filter_baseurl' ) ); } public function shortcode_post_render() { remove_filter( 'tribe_events_force_ugly_link', '__return_true' ); remove_filter( 'tribe_events_ugly_link_baseurl', array( $this, 'filter_baseurl' ) ); } }
mandino/nu
wp-content/plugins/events-calendar-pro/src/Tribe/Shortcodes/Tribe_Events/Map.php
PHP
mit
1,784
1.27.0 / 2017-03-16 =================== * Add `application/emergencycalldata.control+xml` * Add `application/emergencycalldata.ecall.msd` * Add `application/emergencycalldata.veds+xml` * Add `application/geo+json-seq` * Add `application/n-quads` * Add `application/n-triples` * Add `application/vnd.apothekende.reservation+json` * Add `application/vnd.efi.img` * Add `application/vnd.efi.iso` * Add `application/vnd.imagemeter.image+zip` * Add `application/vnd.las.las+json` * Add `application/vnd.ocf+cbor` * Add `audio/melp` * Add `audio/melp1200` * Add `audio/melp2400` * Add `audio/melp600` * Add `image/apng` with extension `.apng` 1.26.0 / 2017-01-14 =================== * Add `application/coap-payload` * Add `application/cose` * Add `application/cose-key` * Add `application/cose-key-set` * Add `application/mud+json` * Add `application/trig` * Add `application/vnd.dataresource+json` * Add `application/vnd.hc+json` * Add `application/vnd.tableschema+json` * Add `application/yang-patch+json` * Add `application/yang-patch+xml` * Add extension `.geojson` to `application/geo+json` 1.25.0 / 2016-11-11 =================== * Add `application/dicom+json` * Add `application/dicom+xml` * Add `application/vnd.openstreetmap.data+xml` * Add `application/vnd.tri.onesource` * Add `application/yang-data+json` * Add `application/yang-data+xml` 1.24.0 / 2016-09-18 =================== * Add `application/clue_info+xml` * Add `application/geo+json` * Add `application/lgr+xml` * Add `application/vnd.amazon.mobi8-ebook` * Add `application/vnd.chess-pgn` * Add `application/vnd.comicbook+zip` * Add `application/vnd.d2l.coursepackage1p0+zip` * Add `application/vnd.espass-espass+zip` * Add `application/vnd.nearst.inv+json` * Add `application/vnd.oma.lwm2m+json` * Add `application/vnd.oma.lwm2m+tlv` * Add `application/vnd.quarantainenet` * Add `application/vnd.rar` * Add `audio/mp3` * Add `image/dicom-rle` * Add `image/emf` * Add `image/jls` * Add `image/wmf` * Add `model/gltf+json` * Add `text/vnd.ascii-art` 1.23.0 / 2016-05-01 =================== * Add `application/efi` * Add `application/vnd.3gpp.sms+xml` * Add `application/vnd.3lightssoftware.imagescal` * Add `application/vnd.coreos.ignition+json` * Add `application/vnd.desmume.movie` * Add `application/vnd.onepager` * Add `application/vnd.vel+json` * Add `text/prs.prop.logic` * Add `video/encaprtp` * Add `video/h265` * Add `video/iso.segment` * Add `video/raptorfec` * Add `video/rtploopback` * Add `video/vnd.radgamettools.bink` * Add `video/vnd.radgamettools.smacker` * Add `video/vp8` * Add extension `.3gpp` to `audio/3gpp` 1.22.0 / 2016-02-15 =================== * Add `application/ppsp-tracker+json` * Add `application/problem+json` * Add `application/problem+xml` * Add `application/vnd.hdt` * Add `application/vnd.ms-printschematicket+xml` * Add `model/vnd.rosette.annotated-data-model` * Add `text/slim` * Add extension `.rng` to `application/xml` * Fix extension of `application/dash+xml` to be `.mpd` * Update primary extension to `.m4a` for `audio/mp4` 1.21.0 / 2016-01-06 =================== * Add `application/emergencycalldata.comment+xml` * Add `application/emergencycalldata.deviceinfo+xml` * Add `application/emergencycalldata.providerinfo+xml` * Add `application/emergencycalldata.serviceinfo+xml` * Add `application/emergencycalldata.subscriberinfo+xml` * Add `application/vnd.filmit.zfc` * Add `application/vnd.google-apps.document` * Add `application/vnd.google-apps.presentation` * Add `application/vnd.google-apps.spreadsheet` * Add `application/vnd.mapbox-vector-tile` * Add `application/vnd.ms-printdevicecapabilities+xml` * Add `application/vnd.ms-windows.devicepairing` * Add `application/vnd.ms-windows.nwprinting.oob` * Add `application/vnd.tml` * Add `audio/evs` 1.20.0 / 2015-11-10 =================== * Add `application/cdni` * Add `application/csvm+json` * Add `application/rfc+xml` * Add `application/vnd.3gpp.access-transfer-events+xml` * Add `application/vnd.3gpp.srvcc-ext+xml` * Add `application/vnd.ms-windows.wsd.oob` * Add `application/vnd.oxli.countgraph` * Add `application/vnd.pagerduty+json` * Add `text/x-suse-ymp` 1.19.0 / 2015-09-17 =================== * Add `application/vnd.3gpp-prose-pc3ch+xml` * Add `application/vnd.3gpp.srvcc-info+xml` * Add `application/vnd.apple.pkpass` * Add `application/vnd.drive+json` 1.18.0 / 2015-09-03 =================== * Add `application/pkcs12` * Add `application/vnd.3gpp-prose+xml` * Add `application/vnd.3gpp.mid-call+xml` * Add `application/vnd.3gpp.state-and-event-info+xml` * Add `application/vnd.anki` * Add `application/vnd.firemonkeys.cloudcell` * Add `application/vnd.openblox.game+xml` * Add `application/vnd.openblox.game-binary` 1.17.0 / 2015-08-13 =================== * Add `application/x-msdos-program` * Add `audio/g711-0` * Add `image/vnd.mozilla.apng` * Add extension `.exe` to `application/x-msdos-program` 1.16.0 / 2015-07-29 =================== * Add `application/vnd.uri-map` 1.15.0 / 2015-07-13 =================== * Add `application/x-httpd-php` 1.14.0 / 2015-06-25 =================== * Add `application/scim+json` * Add `application/vnd.3gpp.ussd+xml` * Add `application/vnd.biopax.rdf+xml` * Add `text/x-processing` 1.13.0 / 2015-06-07 =================== * Add nginx as a source * Add `application/x-cocoa` * Add `application/x-java-archive-diff` * Add `application/x-makeself` * Add `application/x-perl` * Add `application/x-pilot` * Add `application/x-redhat-package-manager` * Add `application/x-sea` * Add `audio/x-m4a` * Add `audio/x-realaudio` * Add `image/x-jng` * Add `text/mathml` 1.12.0 / 2015-06-05 =================== * Add `application/bdoc` * Add `application/vnd.hyperdrive+json` * Add `application/x-bdoc` * Add extension `.rtf` to `text/rtf` 1.11.0 / 2015-05-31 =================== * Add `audio/wav` * Add `audio/wave` * Add extension `.litcoffee` to `text/coffeescript` * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` 1.10.0 / 2015-05-19 =================== * Add `application/vnd.balsamiq.bmpr` * Add `application/vnd.microsoft.portable-executable` * Add `application/x-ns-proxy-autoconfig` 1.9.1 / 2015-04-19 ================== * Remove `.json` extension from `application/manifest+json` - This is causing bugs downstream 1.9.0 / 2015-04-19 ================== * Add `application/manifest+json` * Add `application/vnd.micro+json` * Add `image/vnd.zbrush.pcx` * Add `image/x-ms-bmp` 1.8.0 / 2015-03-13 ================== * Add `application/vnd.citationstyles.style+xml` * Add `application/vnd.fastcopy-disk-image` * Add `application/vnd.gov.sk.xmldatacontainer+xml` * Add extension `.jsonld` to `application/ld+json` 1.7.0 / 2015-02-08 ================== * Add `application/vnd.gerber` * Add `application/vnd.msa-disk-image` 1.6.1 / 2015-02-05 ================== * Community extensions ownership transferred from `node-mime` 1.6.0 / 2015-01-29 ================== * Add `application/jose` * Add `application/jose+json` * Add `application/json-seq` * Add `application/jwk+json` * Add `application/jwk-set+json` * Add `application/jwt` * Add `application/rdap+json` * Add `application/vnd.gov.sk.e-form+xml` * Add `application/vnd.ims.imsccv1p3` 1.5.0 / 2014-12-30 ================== * Add `application/vnd.oracle.resource+json` * Fix various invalid MIME type entries - `application/mbox+xml` - `application/oscp-response` - `application/vwg-multiplexed` - `audio/g721` 1.4.0 / 2014-12-21 ================== * Add `application/vnd.ims.imsccv1p2` * Fix various invalid MIME type entries - `application/vnd-acucobol` - `application/vnd-curl` - `application/vnd-dart` - `application/vnd-dxr` - `application/vnd-fdf` - `application/vnd-mif` - `application/vnd-sema` - `application/vnd-wap-wmlc` - `application/vnd.adobe.flash-movie` - `application/vnd.dece-zip` - `application/vnd.dvb_service` - `application/vnd.micrografx-igx` - `application/vnd.sealed-doc` - `application/vnd.sealed-eml` - `application/vnd.sealed-mht` - `application/vnd.sealed-ppt` - `application/vnd.sealed-tiff` - `application/vnd.sealed-xls` - `application/vnd.sealedmedia.softseal-html` - `application/vnd.sealedmedia.softseal-pdf` - `application/vnd.wap-slc` - `application/vnd.wap-wbxml` - `audio/vnd.sealedmedia.softseal-mpeg` - `image/vnd-djvu` - `image/vnd-svf` - `image/vnd-wap-wbmp` - `image/vnd.sealed-png` - `image/vnd.sealedmedia.softseal-gif` - `image/vnd.sealedmedia.softseal-jpg` - `model/vnd-dwf` - `model/vnd.parasolid.transmit-binary` - `model/vnd.parasolid.transmit-text` - `text/vnd-a` - `text/vnd-curl` - `text/vnd.wap-wml` * Remove example template MIME types - `application/example` - `audio/example` - `image/example` - `message/example` - `model/example` - `multipart/example` - `text/example` - `video/example` 1.3.1 / 2014-12-16 ================== * Fix missing extensions - `application/json5` - `text/hjson` 1.3.0 / 2014-12-07 ================== * Add `application/a2l` * Add `application/aml` * Add `application/atfx` * Add `application/atxml` * Add `application/cdfx+xml` * Add `application/dii` * Add `application/json5` * Add `application/lxf` * Add `application/mf4` * Add `application/vnd.apache.thrift.compact` * Add `application/vnd.apache.thrift.json` * Add `application/vnd.coffeescript` * Add `application/vnd.enphase.envoy` * Add `application/vnd.ims.imsccv1p1` * Add `text/csv-schema` * Add `text/hjson` * Add `text/markdown` * Add `text/yaml` 1.2.0 / 2014-11-09 ================== * Add `application/cea` * Add `application/dit` * Add `application/vnd.gov.sk.e-form+zip` * Add `application/vnd.tmd.mediaflex.api+xml` * Type `application/epub+zip` is now IANA-registered 1.1.2 / 2014-10-23 ================== * Rebuild database for `application/x-www-form-urlencoded` change 1.1.1 / 2014-10-20 ================== * Mark `application/x-www-form-urlencoded` as compressible. 1.1.0 / 2014-09-28 ================== * Add `application/font-woff2` 1.0.3 / 2014-09-25 ================== * Fix engine requirement in package 1.0.2 / 2014-09-25 ================== * Add `application/coap-group+json` * Add `application/dcd` * Add `application/vnd.apache.thrift.binary` * Add `image/vnd.tencent.tap` * Mark all JSON-derived types as compressible * Update `text/vtt` data 1.0.1 / 2014-08-30 ================== * Fix extension ordering 1.0.0 / 2014-08-30 ================== * Add `application/atf` * Add `application/merge-patch+json` * Add `multipart/x-mixed-replace` * Add `source: 'apache'` metadata * Add `source: 'iana'` metadata * Remove badly-assumed charset data
Moccine/global-service-plus.com
web/libariries/bootstrap/node_modules/mime-db/HISTORY.md
Markdown
mit
11,684
import EmptyObject from 'ember-data/-private/system/empty-object'; import parseResponseHeaders from 'ember-data/-private/utils/parse-response-headers'; import { module, test } from 'qunit'; const CRLF = '\u000d\u000a'; module('unit/adapters/parse-response-headers'); test('returns an EmptyObject when headersString is undefined', function(assert) { let headers = parseResponseHeaders(undefined); assert.deepEqual(headers, new EmptyObject(), 'EmptyObject is returned'); }); test('header parsing', function(assert) { let headersString = [ 'Content-Encoding: gzip', 'content-type: application/json; charset=utf-8', 'date: Fri, 05 Feb 2016 21:47:56 GMT' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['Content-Encoding'], 'gzip', 'parses basic header pair'); assert.equal(headers['content-type'], 'application/json; charset=utf-8', 'parses header with complex value'); assert.equal(headers['date'], 'Fri, 05 Feb 2016 21:47:56 GMT', 'parses header with date value'); }); test('field-name parsing', function(assert) { let headersString = [ ' name-with-leading-whitespace: some value', 'name-with-whitespace-before-colon : another value' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['name-with-leading-whitespace'], 'some value', 'strips leading whitespace from field-name'); assert.equal(headers['name-with-whitespace-before-colon'], 'another value', 'strips whitespace before colon from field-name'); }); test('field-value parsing', function(assert) { let headersString = [ 'value-with-leading-space: value with leading whitespace', 'value-without-leading-space:value without leading whitespace', 'value-with-colon: value with: a colon', 'value-with-trailing-whitespace: banana ' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['value-with-leading-space'], 'value with leading whitespace', 'strips leading whitespace in field-value'); assert.equal(headers['value-without-leading-space'], 'value without leading whitespace', 'works without leaading whitespace in field-value'); assert.equal(headers['value-with-colon'], 'value with: a colon', 'has correct value when value contains a colon'); assert.equal(headers['value-with-trailing-whitespace'], 'banana', 'strips trailing whitespace from field-value'); }); test('ignores headers that do not contain a colon', function(assert) { let headersString = [ 'Content-Encoding: gzip', 'I am ignored because I do not contain a colon' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.deepEqual(headers['Content-Encoding'], 'gzip', 'parses basic header pair'); assert.equal(Object.keys(headers).length, 1, 'only has the one valid header'); });
danmcclain/data
tests/unit/utils/parse-response-headers-test.js
JavaScript
mit
2,834
# # Author:: Daniel DeLeo (<dan@kallistec.com>) # Author:: Seth Falcon (<seth@opscode.com>) # Copyright:: Copyright (c) 2009 Daniel DeLeo # Copyright:: Copyright (c) 2010 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # require 'chef/json_compat' class Chef module IndexQueue module Indexable module ClassMethods def index_object_type(explicit_type_name=nil) @index_object_type = explicit_type_name.to_s if explicit_type_name @index_object_type end # Resets all metadata used for indexing to nil. Used for testing def reset_index_metadata! @index_object_type = nil end end def self.included(including_class) including_class.send(:extend, ClassMethods) end attr_accessor :index_id def index_object_type self.class.index_object_type || Mixin::ConvertToClassName.snake_case_basename(self.class.name) end def with_indexer_metadata(indexer_metadata={}) # changing input param symbol keys to strings, as the keys in hash that goes to solr are expected to be strings [cb] # Ruby 1.9 hates you, cb [dan] with_metadata = {} indexer_metadata.each_key do |key| with_metadata[key.to_s] = indexer_metadata[key] end with_metadata["type"] ||= self.index_object_type with_metadata["id"] ||= self.index_id with_metadata["database"] ||= Chef::Config[:couchdb_database] with_metadata["item"] ||= self.to_hash with_metadata["enqueued_at"] ||= Time.now.utc.to_i raise ArgumentError, "Type, Id, or Database missing in index operation: #{with_metadata.inspect}" if (with_metadata["id"].nil? or with_metadata["type"].nil?) with_metadata end def add_to_index(metadata={}) Chef::Log.debug("Pushing item to index queue for addition: #{self.with_indexer_metadata(metadata)}") object_with_metadata = with_indexer_metadata(metadata) obj_id = object_with_metadata["id"] obj = {:action => :add, :payload => self.with_indexer_metadata(metadata)} publish_object(obj_id, obj) end def delete_from_index(metadata={}) Chef::Log.debug("Pushing item to index queue for deletion: #{self.with_indexer_metadata(metadata)}") object_with_metadata = with_indexer_metadata(metadata) obj_id = object_with_metadata["id"] obj = {:action => :delete, :payload => self.with_indexer_metadata(metadata)} publish_object(obj_id, obj) end private # Uses the publisher to update the object's queue. If # Chef::Config[:persistent_queue] is true, the update is wrapped # in a transaction. def publish_object(object_id, object) publisher = AmqpClient.instance begin publisher.amqp_client.tx_select if Chef::Config[:persistent_queue] publisher.queue_for_object(object_id) do |queue| queue.publish(Chef::JSONCompat.to_json(object), :persistent => Chef::Config[:persistent_queue]) end publisher.amqp_client.tx_commit if Chef::Config[:persistent_queue] rescue publisher.amqp_client.tx_rollback if Chef::Config[:persistent_queue] raise end true end end end end
higanworks/chef-with-ruby_precise-x86_64
lib/ruby/gems/1.9.1/gems/chef-10.16.0/lib/chef/index_queue/indexable.rb
Ruby
mit
3,943
<?php declare(strict_types=1); namespace Doctrine\ORM\Query\AST; /** * CollectionMemberExpression ::= EntityExpression ["NOT"] "MEMBER" ["OF"] CollectionValuedPathExpression */ class CollectionMemberExpression extends Node { /** @var mixed */ public $entityExpression; /** @var PathExpression */ public $collectionValuedPathExpression; /** @var bool */ public $not; /** * @param mixed $entityExpr * @param PathExpression $collValuedPathExpr */ public function __construct($entityExpr, $collValuedPathExpr) { $this->entityExpression = $entityExpr; $this->collectionValuedPathExpression = $collValuedPathExpr; } /** * {@inheritdoc} */ public function dispatch($walker) { return $walker->walkCollectionMemberExpression($this); } }
localheinz/doctrine2
lib/Doctrine/ORM/Query/AST/CollectionMemberExpression.php
PHP
mit
865
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(ObjectCreationCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(ObjectInitializerCompletionProvider))> <[Shared]> Partial Friend Class ObjectCreationCompletionProvider Inherits AbstractObjectCreationCompletionProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options) End Function Friend Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.SpaceTriggerChar Protected Overrides Function GetObjectCreationNewExpression(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxNode Dim newExpression As SyntaxNode = Nothing If tree IsNot Nothing AndAlso Not tree.IsInNonUserCode(position, cancellationToken) AndAlso Not tree.IsInSkippedText(position, cancellationToken) Then Dim newToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken) newToken = newToken.GetPreviousTokenIfTouchingWord(position) ' Only after 'new'. If newToken.Kind = SyntaxKind.NewKeyword Then ' Only if the 'new' belongs to an object creation expression. If tree.IsObjectCreationTypeContext(position, cancellationToken) Then newExpression = TryCast(newToken.Parent, ExpressionSyntax) End If End If End If Return newExpression End Function Protected Overrides Async Function CreateContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext) Dim semanticModel = Await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(False) Return Await VisualBasicSyntaxContext.CreateContextAsync(document.Project.Solution.Workspace, semanticModel, position, cancellationToken).ConfigureAwait(False) End Function Private Shared ReadOnly s_rules As CompletionItemRules = CompletionItemRules.Create( commitCharacterRules:=ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, " "c, "("c)), matchPriority:=MatchPriority.Preselect, selectionBehavior:=CompletionItemSelectionBehavior.HardSelection) Protected Overrides Function GetCompletionItemRules(symbols As IReadOnlyList(Of ISymbol), preselect As Boolean) As CompletionItemRules Return s_rules End Function End Class End Namespace
jmarolf/roslyn
src/Features/VisualBasic/Portable/Completion/CompletionProviders/ObjectCreationCompletionProvider.vb
Visual Basic
mit
3,736
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>buffered_stream</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../reference.html" title="Reference"> <link rel="prev" href="buffered_read_stream/write_some/overload2.html" title="buffered_read_stream::write_some (2 of 2 overloads)"> <link rel="next" href="buffered_stream/async_fill.html" title="buffered_stream::async_fill"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="buffered_read_stream/write_some/overload2.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="buffered_stream/async_fill.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="boost_asio.reference.buffered_stream"></a><a class="link" href="buffered_stream.html" title="buffered_stream">buffered_stream</a> </h3></div></div></div> <p> Adds buffering to the read- and write-related operations of a stream. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <span class="identifier">Stream</span><span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">buffered_stream</span> <span class="special">:</span> <span class="identifier">noncopyable</span> </pre> <h5> <a name="boost_asio.reference.buffered_stream.h0"></a> <span><a name="boost_asio.reference.buffered_stream.types"></a></span><a class="link" href="buffered_stream.html#boost_asio.reference.buffered_stream.types">Types</a> </h5> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Name </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody> <tr> <td> <p> <a class="link" href="buffered_stream/lowest_layer_type.html" title="buffered_stream::lowest_layer_type"><span class="bold"><strong>lowest_layer_type</strong></span></a> </p> </td> <td> <p> The type of the lowest layer. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/next_layer_type.html" title="buffered_stream::next_layer_type"><span class="bold"><strong>next_layer_type</strong></span></a> </p> </td> <td> <p> The type of the next layer. </p> </td> </tr> </tbody> </table></div> <h5> <a name="boost_asio.reference.buffered_stream.h1"></a> <span><a name="boost_asio.reference.buffered_stream.member_functions"></a></span><a class="link" href="buffered_stream.html#boost_asio.reference.buffered_stream.member_functions">Member Functions</a> </h5> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Name </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody> <tr> <td> <p> <a class="link" href="buffered_stream/async_fill.html" title="buffered_stream::async_fill"><span class="bold"><strong>async_fill</strong></span></a> </p> </td> <td> <p> Start an asynchronous fill. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/async_flush.html" title="buffered_stream::async_flush"><span class="bold"><strong>async_flush</strong></span></a> </p> </td> <td> <p> Start an asynchronous flush. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/async_read_some.html" title="buffered_stream::async_read_some"><span class="bold"><strong>async_read_some</strong></span></a> </p> </td> <td> <p> Start an asynchronous read. The buffer into which the data will be read must be valid for the lifetime of the asynchronous operation. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/async_write_some.html" title="buffered_stream::async_write_some"><span class="bold"><strong>async_write_some</strong></span></a> </p> </td> <td> <p> Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/buffered_stream.html" title="buffered_stream::buffered_stream"><span class="bold"><strong>buffered_stream</strong></span></a> </p> </td> <td> <p> Construct, passing the specified argument to initialise the next layer. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/close.html" title="buffered_stream::close"><span class="bold"><strong>close</strong></span></a> </p> </td> <td> <p> Close the stream. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/fill.html" title="buffered_stream::fill"><span class="bold"><strong>fill</strong></span></a> </p> </td> <td> <p> Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation. Throws an exception on failure. </p> <p> Fill the buffer with some data. Returns the number of bytes placed in the buffer as a result of the operation, or 0 if an error occurred. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/flush.html" title="buffered_stream::flush"><span class="bold"><strong>flush</strong></span></a> </p> </td> <td> <p> Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation. Throws an exception on failure. </p> <p> Flush all data from the buffer to the next layer. Returns the number of bytes written to the next layer on the last write operation, or 0 if an error occurred. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/get_io_service.html" title="buffered_stream::get_io_service"><span class="bold"><strong>get_io_service</strong></span></a> </p> </td> <td> <p> Get the io_service associated with the object. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/in_avail.html" title="buffered_stream::in_avail"><span class="bold"><strong>in_avail</strong></span></a> </p> </td> <td> <p> Determine the amount of data that may be read without blocking. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/lowest_layer.html" title="buffered_stream::lowest_layer"><span class="bold"><strong>lowest_layer</strong></span></a> </p> </td> <td> <p> Get a reference to the lowest layer. </p> <p> Get a const reference to the lowest layer. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/next_layer.html" title="buffered_stream::next_layer"><span class="bold"><strong>next_layer</strong></span></a> </p> </td> <td> <p> Get a reference to the next layer. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/peek.html" title="buffered_stream::peek"><span class="bold"><strong>peek</strong></span></a> </p> </td> <td> <p> Peek at the incoming data on the stream. Returns the number of bytes read. Throws an exception on failure. </p> <p> Peek at the incoming data on the stream. Returns the number of bytes read, or 0 if an error occurred. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/read_some.html" title="buffered_stream::read_some"><span class="bold"><strong>read_some</strong></span></a> </p> </td> <td> <p> Read some data from the stream. Returns the number of bytes read. Throws an exception on failure. </p> <p> Read some data from the stream. Returns the number of bytes read or 0 if an error occurred. </p> </td> </tr> <tr> <td> <p> <a class="link" href="buffered_stream/write_some.html" title="buffered_stream::write_some"><span class="bold"><strong>write_some</strong></span></a> </p> </td> <td> <p> Write the given data to the stream. Returns the number of bytes written. Throws an exception on failure. </p> <p> Write the given data to the stream. Returns the number of bytes written, or 0 if an error occurred. </p> </td> </tr> </tbody> </table></div> <p> The <a class="link" href="buffered_stream.html" title="buffered_stream"><code class="computeroutput"><span class="identifier">buffered_stream</span></code></a> class template can be used to add buffering to the synchronous and asynchronous read and write operations of a stream. </p> <h5> <a name="boost_asio.reference.buffered_stream.h2"></a> <span><a name="boost_asio.reference.buffered_stream.thread_safety"></a></span><a class="link" href="buffered_stream.html#boost_asio.reference.buffered_stream.thread_safety">Thread Safety</a> </h5> <p> <span class="bold"><strong>Distinct</strong></span> <span class="bold"><strong>objects:</strong></span> Safe. </p> <p> <span class="bold"><strong>Shared</strong></span> <span class="bold"><strong>objects:</strong></span> Unsafe. </p> <h5> <a name="boost_asio.reference.buffered_stream.h3"></a> <span><a name="boost_asio.reference.buffered_stream.requirements"></a></span><a class="link" href="buffered_stream.html#boost_asio.reference.buffered_stream.requirements">Requirements</a> </h5> <p> <span class="bold"><strong>Header: </strong></span><code class="literal">boost/asio/buffered_stream.hpp</code> </p> <p> <span class="bold"><strong>Convenience header: </strong></span><code class="literal">boost/asio.hpp</code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2012 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="buffered_read_stream/write_some/overload2.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="buffered_stream/async_fill.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
mxrrow/zaicoin
src/deps/boost/doc/html/boost_asio/reference/buffered_stream.html
HTML
mit
14,180
# encoding: UTF-8 from eventEngine import * # 默认空值 EMPTY_STRING = '' EMPTY_UNICODE = u'' EMPTY_INT = 0 EMPTY_FLOAT = 0.0 # 方向常量 DIRECTION_NONE = u'无方向' DIRECTION_LONG = u'多' DIRECTION_SHORT = u'空' DIRECTION_UNKNOWN = u'未知' DIRECTION_NET = u'净' # 开平常量 OFFSET_NONE = u'无开平' OFFSET_OPEN = u'开仓' OFFSET_CLOSE = u'平仓' OFFSET_UNKNOWN = u'未知' # 状态常量 STATUS_NOTTRADED = u'未成交' STATUS_PARTTRADED = u'部分成交' STATUS_ALLTRADED = u'全部成交' STATUS_CANCELLED = u'已撤销' STATUS_UNKNOWN = u'未知' # 合约类型常量 PRODUCT_EQUITY = u'股票' PRODUCT_FUTURES = u'期货' PRODUCT_OPTION = u'期权' PRODUCT_INDEX = u'指数' PRODUCT_COMBINATION = u'组合' # 期权类型 OPTION_CALL = u'看涨期权' OPTION_PUT = u'看跌期权' ######################################################################## class VtGateway(object): """交易接口""" #---------------------------------------------------------------------- def __init__(self, eventEngine): """Constructor""" self.eventEngine = eventEngine #---------------------------------------------------------------------- def onTick(self, tick): """市场行情推送""" # 通用事件 event1 = Event(type_=EVENT_TICK) event1.dict_['data'] = tick self.eventEngine.put(event1) # 特定合约代码的事件 event2 = Event(type_=EVENT_TICK+tick.vtSymbol) event2.dict_['data'] = tick self.eventEngine.put(event2) #---------------------------------------------------------------------- def onTrade(self, trade): """成交信息推送""" # 因为成交通常都是事后才会知道成交编号,因此只需要推送通用事件 event1 = Event(type_=EVENT_TRADE) event1.dict_['data'] = trade self.eventEngine.put(event1) #---------------------------------------------------------------------- def onOrder(self, order): """订单变化推送""" # 通用事件 event1 = Event(type_=EVENT_ORDER) event1.dict_['data'] = order self.eventEngine.put(event1) # 特定订单编号的事件 event2 = Event(type_=EVENT_ORDER+order.vtOrderID) event2.dict_['data'] = order self.eventEngine.put(event2) #---------------------------------------------------------------------- def onPosition(self, position): """持仓信息推送""" # 通用事件 event1 = Event(type_=EVENT_POSITION) event1.dict_['data'] = position self.eventEngine.put(event1) # 特定合约代码的事件 event2 = Event(type_=EVENT_POSITION+position.vtPositionName) event2.dict_['data'] = position self.eventEngine.put(event2) #---------------------------------------------------------------------- def onAccount(self, account): """账户信息推送""" # 通用事件 event1 = Event(type_=EVENT_ACCOUNT) event1.dict_['data'] = account self.eventEngine.put(event1) # 特定合约代码的事件 event2 = Event(type_=EVENT_ACCOUNT+account.vtAccountID) event2.dict_['data'] = account self.eventEngine.put(event2) #---------------------------------------------------------------------- def onError(self, error): """错误信息推送""" # 通用事件 event1 = Event(type_=EVENT_ERROR) event1.dict_['data'] = error self.eventEngine.put(event1) #---------------------------------------------------------------------- def onLog(self, log): """日志推送""" # 通用事件 event1 = Event(type_=EVENT_LOG) event1.dict_['data'] = log self.eventEngine.put(event1) #---------------------------------------------------------------------- def onContract(self, contract): """合约基础信息推送""" # 通用事件 event1 = Event(type_=EVENT_CONTRACT) event1.dict_['data'] = contract self.eventEngine.put(event1) #---------------------------------------------------------------------- def connect(self): """连接""" pass #---------------------------------------------------------------------- def subscribe(self): """订阅行情""" pass #---------------------------------------------------------------------- def sendOrder(self): """发单""" pass #---------------------------------------------------------------------- def cancelOrder(self): """撤单""" pass #---------------------------------------------------------------------- def close(self): """关闭""" pass ######################################################################## class VtBaseData(object): """回调函数推送数据的基础类,其他数据类继承于此""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.gatewayName = EMPTY_STRING # Gateway名称 self.rawData = None # 原始数据 ######################################################################## class VtTickData(VtBaseData): """Tick行情数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtTickData, self).__init__() # 代码相关 self.symbol = EMPTY_STRING # 合约代码 self.vtSymbol = EMPTY_STRING # 合约在vt系统中的唯一代码,通常是 Gateway名.合约代码 # 成交数据 self.lastPrice = EMPTY_FLOAT # 最新成交价 self.volume = EMPTY_INT # 最新成交量 self.openInterest = EMPTY_INT # 持仓量 self.tickTime = EMPTY_STRING # 更新时间 # 五档行情 self.bidPrice1 = EMPTY_FLOAT self.bidPrice2 = EMPTY_FLOAT self.bidPrice3 = EMPTY_FLOAT self.bidPrice4 = EMPTY_FLOAT self.bidPrice5 = EMPTY_FLOAT self.askPrice1 = EMPTY_FLOAT self.askPrice2 = EMPTY_FLOAT self.askPrice3 = EMPTY_FLOAT self.askPrice4 = EMPTY_FLOAT self.askPrice5 = EMPTY_FLOAT self.bidVolume1 = EMPTY_INT self.bidVolume2 = EMPTY_INT self.bidVolume3 = EMPTY_INT self.bidVolume4 = EMPTY_INT self.bidVolume5 = EMPTY_INT self.askVolume1 = EMPTY_INT self.askVolume2 = EMPTY_INT self.askVolume3 = EMPTY_INT self.askVolume4 = EMPTY_INT self.askVolume5 = EMPTY_INT ######################################################################## class VtTradeData(VtBaseData): """成交数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtTradeData, self).__init__() # 代码编号相关 self.symbol = EMPTY_STRING # 合约代码 self.vtSymbol = EMPTY_STRING # 合约在vt系统中的唯一代码,通常是 Gateway名.合约代码 self.tradeID = EMPTY_STRING # 成交编号 self.vtTradeID = EMPTY_STRING # 成交在vt系统中的唯一编号,通常是 Gateway名.成交编号 self.orderID = EMPTY_STRING # 订单编号 self.vtOrderID = EMPTY_STRING # 订单在vt系统中的唯一编号,通常是 Gateway名.订单编号 # 成交相关 self.direction = EMPTY_UNICODE # 成交方向 self.offset = EMPTY_UNICODE # 成交开平仓 self.price = EMPTY_FLOAT # 成交价格 self.volume = EMPTY_INT # 成交数量 self.tradeTime = EMPTY_STRING # 成交时间 ######################################################################## class VtOrderData(VtBaseData): """订单数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtOrderData, self).__init__() # 代码编号相关 self.symbol = EMPTY_STRING # 合约代码 self.vtSymbol = EMPTY_STRING # 合约在vt系统中的唯一代码,通常是 Gateway名.合约代码 self.orderID = EMPTY_STRING # 订单编号 self.vtOrderID = EMPTY_STRING # 订单在vt系统中的唯一编号,通常是 Gateway名.订单编号 # 报单相关 self.direction = EMPTY_UNICODE # 报单方向 self.offset = EMPTY_UNICODE # 报单开平仓 self.price = EMPTY_FLOAT # 报单价格 self.totalVolume = EMPTY_INT # 报单总数量 self.tradedVolume = EMPTY_INT # 报单成交数量 self.status = EMPTY_UNICODE # 报单状态 self.orderTime = EMPTY_STRING # 发单时间 self.cancelTime = EMPTY_STRING # 撤单时间 # CTP/LTS相关 self.frontID = EMPTY_INT # 前置机编号 self.sessionID = EMPTY_INT # 连接编号 ######################################################################## class VtPositionData(VtBaseData): """持仓数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtPositionData, self).__init__() # 代码编号相关 self.symbol = EMPTY_STRING # 合约代码 self.vtSymbol = EMPTY_STRING # 合约在vt系统中的唯一代码,通常是 Gateway名.合约代码 # 持仓相关 self.direction = EMPTY_STRING # 持仓方向 self.position = EMPTY_INT # 持仓量 self.frozen = EMPTY_INT # 冻结数量 self.price = EMPTY_FLOAT # 持仓均价 self.vtPositionName = EMPTY_STRING # 持仓在vt系统中的唯一代码,通常是vtSymbol.方向 ######################################################################## class VtAccountData(VtBaseData): """账户数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtAccountData, self).__init__() # 账号代码相关 self.accountID = EMPTY_STRING # 账户代码 self.vtAccountID = EMPTY_STRING # 账户在vt中的唯一代码,通常是 Gateway名.账户代码 # 数值相关 self.preBalance = EMPTY_FLOAT # 昨日账户结算净值 self.balance = EMPTY_FLOAT # 账户净值 self.available = EMPTY_FLOAT # 可用资金 self.commission = EMPTY_FLOAT # 今日手续费 self.margin = EMPTY_FLOAT # 保证金占用 self.closeProfit = EMPTY_FLOAT # 平仓盈亏 self.positionProfit = EMPTY_FLOAT # 持仓盈亏 ######################################################################## class VtErrorData(VtBaseData): """错误数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtErrorData, self).__init__() self.errorID = EMPTY_STRING # 错误代码 self.errorMsg = EMPTY_UNICODE # 错误信息 ######################################################################## class VtLogData(VtBaseData): """日志数据类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtLogData, self).__init__() self.logContent = EMPTY_UNICODE # 日志信息 ######################################################################## class VtContractData(VtBaseData): """合约详细信息类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(VtBaseData, self).__init__() self.symbol = EMPTY_STRING self.vtSymbol = EMPTY_STRING self.productClass = EMPTY_STRING self.size = EMPTY_INT self.priceTick = EMPTY_FLOAT # 期权相关 self.strikePrice = EMPTY_FLOAT self.underlyingSymbol = EMPTY_STRING self.optionType = EMPTY_UNICODE ######################################################################## class VtSubscribeReq: """订阅行情时传入的对象类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.symbol = EMPTY_STRING self.exchange = EMPTY_STRING ######################################################################## class VtOrderReq: """发单时传入的对象类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.symbol = EMPTY_STRING ######################################################################## class VtCancelOrderReq: """撤单时传入的对象类""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.symbol = EMPTY_STRING self.exchange = EMPTY_STRING self.
drongh/vnpy
vn.trader/gateway.py
Python
mit
14,192
# Create an Azure VM with a new AD Forest (from a module) ![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/active-directory/active-directory-new-domain-module-use/PublicLastTestDate.svg) ![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/active-directory/active-directory-new-domain-module-use/PublicDeployment.svg) ![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/active-directory/active-directory-new-domain-module-use/FairfaxLastTestDate.svg) ![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/active-directory/active-directory-new-domain-module-use/FairfaxDeployment.svg) ![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/active-directory/active-directory-new-domain-module-use/BestPracticeResult.svg) ![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/application-workloads/active-directory/active-directory-new-domain-module-use/CredScanResult.svg) [![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Factive-directory%2Factive-directory-new-domain-module-use%2Fazuredeploy.json) [![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Factive-directory%2Factive-directory-new-domain-module-use%2Fazuredeploy.json) [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fapplication-workloads%2Factive-directory%2Factive-directory-new-domain-module-use%2Fazuredeploy.json) This template will deploy a new VM (along with a new VNet and Load Balancer) and will configure it as a Domain Controller and create a new forest and domain. _This sample deploys the controller from a shared module in the modules folder. You can use the sample directly or as an example of how to use a module in a larger template deployment._
neudesic/azure-quickstart-templates
application-workloads/active-directory/active-directory-new-domain-module-use/README.md
Markdown
mit
2,725
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_deadline_timer::basic_deadline_timer (3 of 3 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../basic_deadline_timer.html" title="basic_deadline_timer::basic_deadline_timer"> <link rel="prev" href="overload2.html" title="basic_deadline_timer::basic_deadline_timer (2 of 3 overloads)"> <link rel="next" href="../cancel.html" title="basic_deadline_timer::cancel"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload2.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_deadline_timer.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../cancel.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_deadline_timer.basic_deadline_timer.overload3"></a><a class="link" href="overload3.html" title="basic_deadline_timer::basic_deadline_timer (3 of 3 overloads)">basic_deadline_timer::basic_deadline_timer (3 of 3 overloads)</a> </h5></div></div></div> <p> Constructor to set a particular expiry time relative to now. </p> <pre class="programlisting"><span class="identifier">basic_deadline_timer</span><span class="special">(</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span> <span class="special">&amp;</span> <span class="identifier">io_service</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">duration_type</span> <span class="special">&amp;</span> <span class="identifier">expiry_time</span><span class="special">);</span> </pre> <p> This constructor creates a timer and sets the expiry time. </p> <h6> <a name="boost_asio.reference.basic_deadline_timer.basic_deadline_timer.overload3.h0"></a> <span><a name="boost_asio.reference.basic_deadline_timer.basic_deadline_timer.overload3.parameters"></a></span><a class="link" href="overload3.html#boost_asio.reference.basic_deadline_timer.basic_deadline_timer.overload3.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">io_service</span></dt> <dd><p> The <a class="link" href="../../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the timer will use to dispatch handlers for any asynchronous operations performed on the timer. </p></dd> <dt><span class="term">expiry_time</span></dt> <dd><p> The expiry time to be used for the timer, relative to now. </p></dd> </dl> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2012 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload2.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_deadline_timer.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../cancel.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
mxrrow/zaicoin
src/deps/boost/doc/html/boost_asio/reference/basic_deadline_timer/basic_deadline_timer/overload3.html
HTML
mit
4,964
// // SPDatabaseData.h // sequel-pro // // Created by Stuart Connolly (stuconnolly.com) on May 20, 2009. // Copyright (c) 2009 Stuart Connolly. All rights reserved. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // // More info at <https://github.com/sequelpro/sequelpro> @class SPServerSupport; @class SPMySQLConnection; /** * @class SPDatabaseData SPDatabaseData.h * * @author Stuart Connolly http://stuconnolly.com/ * * This class provides various convenience methods for obtaining data associated with the current database, * if available. This includes available encodings, collations, etc. */ @interface SPDatabaseData : NSObject { NSString *characterSetEncoding; NSString *defaultCharacterSetEncoding; NSString *defaultCollation; NSString *serverDefaultCharacterSetEncoding; NSString *serverDefaultCollation; NSString *defaultStorageEngine; NSMutableArray *collations; NSMutableArray *characterSetCollations; NSMutableArray *storageEngines; NSMutableArray *characterSetEncodings; NSMutableDictionary *cachedCollationsByEncoding; SPMySQLConnection *connection; SPServerSupport *serverSupport; } /** * @property connection The current database connection */ @property (readwrite, assign) SPMySQLConnection *connection; /** * @property serverSupport The connection's associated SPServerSupport instance */ @property (readwrite, assign) SPServerSupport *serverSupport; - (void)resetAllData; - (NSArray *)getDatabaseCollations; - (NSArray *)getDatabaseCollationsForEncoding:(NSString *)encoding; - (NSArray *)getDatabaseStorageEngines; - (NSArray *)getDatabaseCharacterSetEncodings; - (NSString *)getDatabaseDefaultCharacterSet; - (NSString *)getDatabaseDefaultCollation; - (NSString *)getDatabaseDefaultStorageEngine; - (NSString *)getServerDefaultCharacterSet; - (NSString *)getServerDefaultCollation; @end
treejames/sequelpro
Source/SPDatabaseData.h
C
mit
2,911
Please take a look in the sub-folders in this directory in order to see the main features. The really critical ones are in the home_page directory, but other important ones are also in the superadmin directory. Features without scenarios are in the pending sub-directories. Whenever adding a new feature please check the pending sub-dirs in order to avoid duplication. Where possible please add links to pivotal stories to connect with the larger project picture.
Aleks4ndr/LocalSupport
features/README.md
Markdown
mit
466
// ////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2011 Prof. William H. Green (whgreen@mit.edu) and the // RMG Team (rmg_dev@mit.edu) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // ////////////////////////////////////////////////////////////////////////////// package jing.chem; import java.util.*; // ## package jing::chem // ---------------------------------------------------------------------------- // jing\chem\ChemElementDictionary.java // ---------------------------------------------------------------------------- // ## class ChemElementDictionary public class ChemElementDictionary { private static ChemElementDictionary INSTANCE = new ChemElementDictionary(); // ## attribute INSTANCE /** * Table holds all the element in the system. */ protected LinkedHashMap dictionary; // ## attribute dictionary // Constructors // ## operation ChemElementDictionary() private ChemElementDictionary() { // #[ operation ChemElementDictionary() dictionary = new LinkedHashMap(); // #] } // ## operation getChemElement(String) public ChemElement getChemElement(String p_name) { // #[ operation getChemElement(String) return (ChemElement) (dictionary.get(p_name)); // #] } // ## operation getInstance() public static ChemElementDictionary getInstance() { // #[ operation getInstance() return INSTANCE; // #] } // ## operation putChemElement(ChemElement) public void putChemElement(ChemElement p_chemElement) { // #[ operation putChemElement(ChemElement) dictionary.put(p_chemElement.name, p_chemElement); // #] } // ## operation size() public int size() { // #[ operation size() return dictionary.size(); // #] } protected LinkedHashMap getDictionary() { return dictionary; } } /********************************************************************* * File Path : RMG\RMG\jing\chem\ChemElementDictionary.java *********************************************************************/
keceli/RMG-Java
source/RMG/jing/chem/ChemElementDictionary.java
Java
mit
3,323
#include <stdio.h> extern FILE *path_fopen(const char *mode, int exit_on_err, const char *path, ...) __attribute__ ((__format__ (__printf__, 3, 4))); extern void path_getstr(char *result, size_t len, const char *path, ...) __attribute__ ((__format__ (__printf__, 3, 4))); extern int path_writestr(const char *str, const char *path, ...) __attribute__ ((__format__ (__printf__, 2, 3))); extern int path_getnum(const char *path, ...) __attribute__ ((__format__ (__printf__, 1, 2))); extern int path_exist(const char *path, ...) __attribute__ ((__format__ (__printf__, 1, 2))); extern cpu_set_t *path_cpuset(int, const char *path, ...) __attribute__ ((__format__ (__printf__, 2, 3))); extern cpu_set_t *path_cpulist(int, const char *path, ...) __attribute__ ((__format__ (__printf__, 2, 3))); extern void path_setprefix(const char *);
imx6uldev/depedency_tools
util-linux/util-linux-2.21.2/include/path.h
C
mit
879
module FindIndex extend ActiveSupport::Concern attr_accessor :applicant_collection_method included do def self.part_of applicant_collection_method define_method :my_number do applicant.send(applicant_collection_method).find_index(self)+1 end end end end
uncompiled/districthousing
app/models/concerns/find_index.rb
Ruby
mit
342
/* * Copyright (C) 2013 Glyptodon LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "config.h" #include "client.h" #include <freerdp/freerdp.h> #include <freerdp/client/disp.h> #include <guacamole/client.h> #include <guacamole/timestamp.h> guac_rdp_disp* guac_rdp_disp_alloc() { guac_rdp_disp* disp = malloc(sizeof(guac_rdp_disp)); /* Not yet connected */ disp->disp = NULL; /* No requests have been made */ disp->last_request = 0; disp->requested_width = 0; disp->requested_height = 0; return disp; } void guac_rdp_disp_free(guac_rdp_disp* disp) { free(disp); } void guac_rdp_disp_load_plugin(rdpContext* context) { #ifdef HAVE_RDPSETTINGS_SUPPORTDISPLAYCONTROL context->settings->SupportDisplayControl = TRUE; #endif /* Add "disp" channel */ ADDIN_ARGV* args = malloc(sizeof(ADDIN_ARGV)); args->argc = 1; args->argv = malloc(sizeof(char**) * 1); args->argv[0] = strdup("disp"); freerdp_dynamic_channel_collection_add(context->settings, args); } void guac_rdp_disp_connect(guac_rdp_disp* guac_disp, DispClientContext* disp) { guac_disp->disp = disp; } /** * Fits a given dimension within the allowed bounds for Display Update * messages, adjusting the other dimension such that aspect ratio is * maintained. * * @param a The dimension to fit within allowed bounds. * * @param b * The other dimension to adjust if and only if necessary to preserve * aspect ratio. */ static void guac_rdp_disp_fit(int* a, int* b) { int a_value = *a; int b_value = *b; /* Ensure first dimension is within allowed range */ if (a_value < GUAC_RDP_DISP_MIN_SIZE) { /* Adjust other dimension to maintain aspect ratio */ int adjusted_b = b_value * GUAC_RDP_DISP_MIN_SIZE / a_value; if (adjusted_b > GUAC_RDP_DISP_MAX_SIZE) adjusted_b = GUAC_RDP_DISP_MAX_SIZE; *a = GUAC_RDP_DISP_MIN_SIZE; *b = adjusted_b; } else if (a_value > GUAC_RDP_DISP_MAX_SIZE) { /* Adjust other dimension to maintain aspect ratio */ int adjusted_b = b_value * GUAC_RDP_DISP_MAX_SIZE / a_value; if (adjusted_b < GUAC_RDP_DISP_MIN_SIZE) adjusted_b = GUAC_RDP_DISP_MIN_SIZE; *a = GUAC_RDP_DISP_MAX_SIZE; *b = adjusted_b; } } void guac_rdp_disp_set_size(guac_rdp_disp* disp, rdpContext* context, int width, int height) { /* Fit width within bounds, adjusting height to maintain aspect ratio */ guac_rdp_disp_fit(&width, &height); /* Fit height within bounds, adjusting width to maintain aspect ratio */ guac_rdp_disp_fit(&height, &width); /* Width must be even */ if (width % 2 == 1) width -= 1; /* Store deferred size */ disp->requested_width = width; disp->requested_height = height; /* Send display update notification if possible */ guac_rdp_disp_update_size(disp, context); } void guac_rdp_disp_update_size(guac_rdp_disp* disp, rdpContext* context) { guac_client* client = ((rdp_freerdp_context*) context)->client; /* Send display update notification if display channel is connected */ if (disp->disp == NULL) return; int width = disp->requested_width; int height = disp->requested_height; DISPLAY_CONTROL_MONITOR_LAYOUT monitors[1] = {{ .Flags = 0x1, /* DISPLAYCONTROL_MONITOR_PRIMARY */ .Left = 0, .Top = 0, .Width = width, .Height = height, .PhysicalWidth = 0, .PhysicalHeight = 0, .Orientation = 0, .DesktopScaleFactor = 0, .DeviceScaleFactor = 0 }}; guac_timestamp now = guac_timestamp_current(); /* Limit display update frequency */ if (disp->last_request != 0 && now - disp->last_request <= GUAC_RDP_DISP_UPDATE_INTERVAL) return; /* Do NOT send requests unless the size will change */ if (width == guac_rdp_get_width(context->instance) && height == guac_rdp_get_height(context->instance)) return; guac_client_log(client, GUAC_LOG_DEBUG, "Resizing remote display to %ix%i", width, height); disp->last_request = now; disp->disp->SendMonitorLayout(disp->disp, 1, monitors); }
AIexandr/guacamole-server
src/protocols/rdp/rdp_disp.c
C
mit
5,311
# MongoDB - Aula 04 - Exercício autor: Felipe Cabianchi de Oliveira ## **Adicionar** 2 ataques ao mesmo tempo para os seguintes pokemons: Pikachu, Squirtle, Bulbassauro e Charmander. ```js var query = {name : {$in : poke}} var poke = [/pikachu/i, /bulbasaur/i, /squirtle/i, /charmander/i] var attacks = ['investida', 'desvio'] var mod = {$pushAll : {moves : attacks}} var opt = {multi : true} Updated 4 existing record(s) in 10ms WriteResult({ "nMatched": 4, "nUpserted": 0, "nModified": 4 }) { "_id": ObjectId("5653dca1415e21582441090e"), "name": "Pikachu", "description": "Ratinho", "type": "eletric", "attack": 55, "height": 4, "moves": [ "investida", "desvio" ] } { "_id": ObjectId("5653dca6415e21582441090f"), "name": "Squirtle", "description": "aguinha", "type": "water", "attack": 48, "height": 5, "moves": [ "investida", "desvio" ] } { "_id": ObjectId("5653dcaa415e215824410910"), "name": "Bulbasaur", "description": "Chicote", "type": "grass", "attack": 49, "height": 7, "moves": [ "investida", "desvio" ] } { "_id": ObjectId("5654b3a5f2014feb151bc27e"), "name": "Charmander", "description": "Sou eu bola de fogo", "type": "fire", "attack": 123, "height": 0.5, "moves": [ "investida", "desvio" ] } ``` ## **Adicionar** 1 movimento em todos os pokemons: `desvio`.## ```js var query = {} var mod = {$push : {moves : 'desvio'}} var opt = {multi : true} db.pokemons.update(query, mod, opt) Updated 9 existing record(s) in 2ms WriteResult({ "nMatched": 9, "nUpserted": 0, "nModified": 9 }) ``` ## **Adicionar** o pokemon `AindaNaoExisteMon` caso ele não exista com todos os dados com o valor `null` e a descrição: "Sem maiores informações".## ```js var query = {name : /AindaNaoExisteMon/i} var mod = {$setOnInsert : { 'name' : 'AindaNaoExisteMon' ,'description' : 'Sem maiores informações' ,'type' : null ,'attack' : null ,'height' : null ,'moves' : [] }} var opt = {upsert : true} db.pokemons.update(query, mod, opt) WriteResult({ "nMatched": 0, "nUpserted": 1, "nModified": 0, "_id": ObjectId("5654c11710c42b67840bd89d") }) { "_id": ObjectId("5654c11710c42b67840bd89d"), "name": "AindaNaoExisteMon", "description": "Sem maiores informações", "type": null, "attack": null, "height": null, "moves": [ ] } ``` ## Pesquisar todos o pokemons que possuam o ataque `investida` e mais um que você adicionou, escolha seu pokemon favorito.## ```js var query = {moves : {$in : [/investida/i, /bola de fogo/i]}} db.pokemons.find(query) { "_id": ObjectId("5643f4dd403adc69105a1ed2"), "name": "Charizard", "description": "fogo++", "type": "fire", "attack": 84, "height": 17, "moves": [ "desvio", "bola de fogo" ] } { "_id": ObjectId("5653dca1415e21582441090e"), "name": "Pikachu", "description": "Ratinho", "type": "eletric", "attack": 55, "height": 4, "moves": [ "investida", "desvio", "choque do trovao" ] } { "_id": ObjectId("5653dca6415e21582441090f"), "name": "Squirtle", "description": "aguinha", "type": "water", "attack": 48, "height": 5, "moves": [ "investida", "desvio" ] } { "_id": ObjectId("5653dcaa415e215824410910"), "name": "Bulbasaur", "description": "Chicote", "type": "grass", "attack": 49, "height": 7, "moves": [ "investida", "desvio" ] } { "_id": ObjectId("5654b3a5f2014feb151bc27e"), "name": "Charmander", "description": "Sou eu bola de fogo", "type": "fire", "attack": 123, "height": 0.5, "moves": [ "investida", "desvio" ] } ``` ## Pesquisar **todos** os pokemons que possuam os ataques que você adicionou, escolha seu pokemon favorito.## ```js var query = {moves : {$all : [/investida/i, /choque do trovao/i]}} db.pokemons.find(query) { "_id": ObjectId("5653dca1415e21582441090e"), "name": "Pikachu", "description": "Ratinho", "type": "eletric", "attack": 55, "height": 4, "moves": [ "investida", "desvio", "choque do trovao" ] } ``` ## Pesquisar **todos** os pokemons que não são do tipo `elétrico`.## ```js var query = {type : {$not : /eletric/i}} db.pokemons.find(query) { "_id": ObjectId("5643f4dd403adc69105a1ed2"), "name": "Charizard", "description": "fogo++", "type": "fire", "attack": 84, "height": 17, "moves": [ "desvio", "bola de fogo" ], "defense": 15 } { "_id": ObjectId("5643f54a403adc69105a1ed3"), "name": "Charmeleon", "description": "sorta -fogo", "type": "fire", "attack": 64, "height": 11, "moves": [ "desvio" ], "defense": 40 } { "_id": ObjectId("5643f5ac403adc69105a1ed4"), "name": "Pidgeot", "description": "nois q voa", "type": "normal", "attack": 80, "height": 15, "moves": [ "desvio" ], "defense": 28 } { "_id": ObjectId("5643f631403adc69105a1ed6"), "name": "Kakuna", "description": "Pele de pedra", "type": "Bug", "attack": 25, "height": 6, "moves": [ "desvio" ], "defense": 28 } { "_id": ObjectId("5653dca6415e21582441090f"), "name": "Squirtle", "description": "aguinha", "type": "water", "attack": 48, "height": 5, "moves": [ "investida", "desvio" ], "defense": 61 } { "_id": ObjectId("5653dcaa415e215824410910"), "name": "Bulbasaur", "description": "Chicote", "type": "grass", "attack": 49, "height": 7, "moves": [ "investida", "desvio" ], "defense": 15 } { "_id": ObjectId("5654b3a5f2014feb151bc27e"), "name": "Charmander", "description": "Sou eu bola de fogo", "type": "fire", "attack": 123, "height": 0.5, "moves": [ "investida", "desvio" ], "defense": 41 } { "_id": ObjectId("5643f600403adc69105a1ed5"), "name": "Meowth", "description": "Mia", "type": "normal", "attack": 45, "height": 4, "moves": [ "desvio" ], "defense": 40 } { "_id": ObjectId("5654c11710c42b67840bd89d"), "name": "AindaNaoExisteMon", "description": "Sem maiores informações", "type": null, "attack": null, "height": null, "moves": [ ], "defense": 66 } ``` ## Pesquisar **todos** os pokemons que tenham o ataque `investida` **E** tenham a defesa **não menor ou igual** a 49.## ```js var query = {$and : [{moves : {$in : [/investida/i]}}, {defense : {$not : {$lte : 49}}}]} db.pokemons.find(query) { "_id": ObjectId("5653dca6415e21582441090f"), "name": "Squirtle", "description": "aguinha", "type": "water", "attack": 48, "height": 5, "moves": [ "investida", "desvio" ], "defense": 61 } ``` ## Remova **todos** os pokemons do tipo água e com attack menor que 50. ```js var query = {$and : [{type : /water/i}, {attack : {$lt : 50}}]} WriteResult({ "nRemoved": 1 }) ``` ## Diferença entre **$ne** e **$not**. ``` $not : faz um não logico para uma operação expecifica e seleciona os documentos que não combina com a expressão Exemplo db.pokemons.find({height: { $not : {$lt : 5}}}) A query vai selecionar os pokemons aonde a altura é maior que 5. ``` ``` $ne : seleciona os documentos aonde o valor do campo é diferente de um valor expecifico. Exemplo db.pokemons.find({attack : {$ne : 30}}) A query vai listar todos pokemons no qual o attack não é igual a 30. ```
netoabel/be-mean-instagram-mongodb-exercises
class-04/class-04-resolved-fecabianchi-felipe-cabianchi.md
Markdown
cc0-1.0
7,911
/** * Copyright (c) 2010-2014, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.io.gcal.internal.util; import java.io.BufferedReader; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.lang.StringUtils; import org.openhab.io.console.Console; import org.openhab.io.console.ConsoleInterpreter; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of Quartz {@link Job}-Interface. It parses the Calendar-Event * content into single commands and let {@link ConsoleInterpreter} handle those * commands. * * @author Thomas.Eichstaedt-Engelen * @since 0.7.0 */ public class ExecuteCommandJob implements Job { private static final Logger logger = LoggerFactory.getLogger(ExecuteCommandJob.class); public static final String JOB_DATA_CONTENT_KEY = "content"; public void execute(JobExecutionContext context) throws JobExecutionException { String content = (String) context.getJobDetail().getJobDataMap().get(JOB_DATA_CONTENT_KEY); if (StringUtils.isNotBlank(content)) { String[] commands = parseCommands(content); for (String command : commands) { String[] args = parseCommand(command); logger.debug("About to execute CommandJob with arguments {}", Arrays.asList(args)); try { ConsoleInterpreter.handleRequest(args, new LogConsole()); } catch (Exception e) { throw new JobExecutionException("Executing command '" + command + "' throws an Exception. Job will be refired immediately.", e, true); } } } } /** * Reads the Calendar-Event content String line by line. It is assumed, that * each line contains a single command. Blank lines are omitted. * * @param content the Calendar-Event content * @return an array of single commands which can be executed afterwards */ protected String[] parseCommands(String content) { Collection<String> parsedCommands = new ArrayList<String>(); BufferedReader in = new BufferedReader(new StringReader(content)); try { String command; while ((command = in.readLine()) != null) { if (StringUtils.isNotBlank(command)) { parsedCommands.add(command.trim()); } } } catch (IOException ioe) { logger.error("reading event content throws exception", ioe); } finally { try { in.close(); } catch (IOException ioe) {} } return parsedCommands.toArray(new String[0]); } /** * Parses a <code>command</code>. Utilizes the {@link StreamTokenizer} which * takes care of quoted Strings as well. * * @param command the command to parse * @return the tokenized command which can be processed by the * <code>ConsoleInterpreter</code> * * @see org.openhab.io.console.ConsoleInterpreter */ protected String[] parseCommand(String command) { logger.trace("going to parse command '{}'", command); // if the command starts with '>' it contains a script which needs no // further handling here ... if (command.startsWith(">")) { return new String[] {">", command.substring(1).trim()}; } StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(command)); tokenizer.wordChars('_', '_'); tokenizer.wordChars('-', '-'); tokenizer.wordChars('.', '.'); List<String> tokens = new ArrayList<String>(); try { int tokenType = 0; while (tokenType != StreamTokenizer.TT_EOF && tokenType != StreamTokenizer.TT_EOL) { tokenType = tokenizer.nextToken(); String token = ""; switch (tokenType) { case StreamTokenizer.TT_WORD: case 34 /* quoted String */: token = tokenizer.sval; break; case StreamTokenizer.TT_NUMBER: token = String.valueOf(tokenizer.nval); break; } tokens.add(token); logger.trace("read value {} from the given command", token); } } catch (IOException ioe) {} return tokens.toArray(new String[0]); } /** * Simple implementation of the {@link Console} interface. It's output is * send to the logger (INFO-Level). * * @author Thomas.Eichstaedt-Engelen * @since 0.7.0 */ private static class LogConsole implements Console { public void print(String s) { logger.info(s); } public void println(String s) { logger.info(s); } public void printUsage(String s) { logger.info(s); } } }
hubermi/openhab
bundles/io/org.openhab.io.gcal/src/main/java/org/openhab/io/gcal/internal/util/ExecuteCommandJob.java
Java
epl-1.0
4,778
<?php namespace Drupal\layout_builder\Plugin\Block; use Drupal\Component\Plugin\Factory\DefaultFactory; use Drupal\Component\Utility\NestedArray; use Drupal\Core\Access\AccessResult; use Drupal\Core\Block\BlockBase; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Entity\EntityDisplayBase; use Drupal\Core\Entity\EntityFieldManagerInterface; use Drupal\Core\Entity\FieldableEntityInterface; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\Core\Field\FormatterInterface; use Drupal\Core\Field\FormatterPluginManager; use Drupal\Core\Form\EnforcedResponseException; use Drupal\Core\Form\FormHelper; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\Core\Plugin\ContextAwarePluginInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\StringTranslation\TranslatableMarkup; use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a block that renders a field from an entity. * * @Block( * id = "field_block", * deriver = "\Drupal\layout_builder\Plugin\Derivative\FieldBlockDeriver", * ) * * @internal * Plugin classes are internal. */ class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface { /** * The entity field manager. * * @var \Drupal\Core\Entity\EntityFieldManagerInterface */ protected $entityFieldManager; /** * The formatter manager. * * @var \Drupal\Core\Field\FormatterPluginManager */ protected $formatterManager; /** * The entity type ID. * * @var string */ protected $entityTypeId; /** * The bundle ID. * * @var string */ protected $bundle; /** * The field name. * * @var string */ protected $fieldName; /** * The field definition. * * @var \Drupal\Core\Field\FieldDefinitionInterface */ protected $fieldDefinition; /** * The module handler. * * @var \Drupal\Core\Extension\ModuleHandlerInterface */ protected $moduleHandler; /** * The logger. * * @var \Psr\Log\LoggerInterface */ protected $logger; /** * Constructs a new FieldBlock. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin ID for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager * The entity field manager. * @param \Drupal\Core\Field\FormatterPluginManager $formatter_manager * The formatter manager. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. * @param \Psr\Log\LoggerInterface $logger * The logger. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFieldManagerInterface $entity_field_manager, FormatterPluginManager $formatter_manager, ModuleHandlerInterface $module_handler, LoggerInterface $logger) { $this->entityFieldManager = $entity_field_manager; $this->formatterManager = $formatter_manager; $this->moduleHandler = $module_handler; $this->logger = $logger; // Get the entity type and field name from the plugin ID. list (, $entity_type_id, $bundle, $field_name) = explode(static::DERIVATIVE_SEPARATOR, $plugin_id, 4); $this->entityTypeId = $entity_type_id; $this->bundle = $bundle; $this->fieldName = $field_name; parent::__construct($configuration, $plugin_id, $plugin_definition); } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('entity_field.manager'), $container->get('plugin.manager.field.formatter'), $container->get('module_handler'), $container->get('logger.channel.layout_builder') ); } /** * Gets the entity that has the field. * * @return \Drupal\Core\Entity\FieldableEntityInterface * The entity. */ protected function getEntity() { return $this->getContextValue('entity'); } /** * {@inheritdoc} */ public function build() { $display_settings = $this->getConfiguration()['formatter']; $entity = $this->getEntity(); try { $build = $entity->get($this->fieldName)->view($display_settings); } // @todo Remove in https://www.drupal.org/project/drupal/issues/2367555. catch (EnforcedResponseException $e) { throw $e; } catch (\Exception $e) { $build = []; $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]); } CacheableMetadata::createFromObject($this)->applyTo($build); return $build; } /** * {@inheritdoc} */ public function getPreviewFallbackString() { return new TranslatableMarkup('"@field" field', ['@field' => $this->getFieldDefinition()->getLabel()]); } /** * {@inheritdoc} */ protected function blockAccess(AccountInterface $account) { $entity = $this->getEntity(); // First consult the entity. $access = $entity->access('view', $account, TRUE); if (!$access->isAllowed()) { return $access; } // Check that the entity in question has this field. if (!$entity instanceof FieldableEntityInterface || !$entity->hasField($this->fieldName)) { return $access->andIf(AccessResult::forbidden()); } // Check field access. $field = $entity->get($this->fieldName); $access = $access->andIf($field->access('view', $account, TRUE)); if (!$access->isAllowed()) { return $access; } // Check to see if the field has any values. if ($field->isEmpty()) { return $access->andIf(AccessResult::forbidden()); } return $access; } /** * {@inheritdoc} */ public function defaultConfiguration() { return [ 'label_display' => FALSE, 'formatter' => [ 'label' => 'above', 'type' => $this->pluginDefinition['default_formatter'], 'settings' => [], 'third_party_settings' => [], ], ]; } /** * {@inheritdoc} */ public function blockForm($form, FormStateInterface $form_state) { $config = $this->getConfiguration(); $form['formatter'] = [ '#tree' => TRUE, '#process' => [ [$this, 'formatterSettingsProcessCallback'], ], ]; $form['formatter']['label'] = [ '#type' => 'select', '#title' => $this->t('Label'), // @todo This is directly copied from // \Drupal\field_ui\Form\EntityViewDisplayEditForm::getFieldLabelOptions(), // resolve this in https://www.drupal.org/project/drupal/issues/2933924. '#options' => [ 'above' => $this->t('Above'), 'inline' => $this->t('Inline'), 'hidden' => '- ' . $this->t('Hidden') . ' -', 'visually_hidden' => '- ' . $this->t('Visually Hidden') . ' -', ], '#default_value' => $config['formatter']['label'], ]; $form['formatter']['type'] = [ '#type' => 'select', '#title' => $this->t('Formatter'), '#options' => $this->getApplicablePluginOptions($this->getFieldDefinition()), '#required' => TRUE, '#default_value' => $config['formatter']['type'], '#ajax' => [ 'callback' => [static::class, 'formatterSettingsAjaxCallback'], 'wrapper' => 'formatter-settings-wrapper', ], ]; // Add the formatter settings to the form via AJAX. $form['formatter']['settings_wrapper'] = [ '#prefix' => '<div id="formatter-settings-wrapper">', '#suffix' => '</div>', ]; return $form; } /** * Render API callback: builds the formatter settings elements. */ public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form) { if ($formatter = $this->getFormatter($element['#parents'], $form_state)) { $element['settings_wrapper']['settings'] = $formatter->settingsForm($complete_form, $form_state); $element['settings_wrapper']['settings']['#parents'] = array_merge($element['#parents'], ['settings']); $element['settings_wrapper']['third_party_settings'] = $this->thirdPartySettingsForm($formatter, $this->getFieldDefinition(), $complete_form, $form_state); $element['settings_wrapper']['third_party_settings']['#parents'] = array_merge($element['#parents'], ['third_party_settings']); FormHelper::rewriteStatesSelector($element['settings_wrapper'], "fields[$this->fieldName][settings_edit_form]", 'settings[formatter]'); // Store the array parents for our element so that we can retrieve the // formatter settings in our AJAX callback. $form_state->set('field_block_array_parents', $element['#array_parents']); } return $element; } /** * Adds the formatter third party settings forms. * * @param \Drupal\Core\Field\FormatterInterface $plugin * The formatter. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * @param array $form * The (entire) configuration form array. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. * * @return array * The formatter third party settings form. */ protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) { $settings_form = []; // Invoke hook_field_formatter_third_party_settings_form(), keying resulting // subforms by module name. foreach ($this->moduleHandler->getImplementations('field_formatter_third_party_settings_form') as $module) { $settings_form[$module] = $this->moduleHandler->invoke($module, 'field_formatter_third_party_settings_form', [ $plugin, $field_definition, EntityDisplayBase::CUSTOM_MODE, $form, $form_state, ]); } return $settings_form; } /** * Render API callback: gets the layout settings elements. */ public static function formatterSettingsAjaxCallback(array $form, FormStateInterface $form_state) { $formatter_array_parents = $form_state->get('field_block_array_parents'); return NestedArray::getValue($form, array_merge($formatter_array_parents, ['settings_wrapper'])); } /** * {@inheritdoc} */ public function blockSubmit($form, FormStateInterface $form_state) { $this->configuration['formatter'] = $form_state->getValue('formatter'); } /** * Gets the field definition. * * @return \Drupal\Core\Field\FieldDefinitionInterface * The field definition. */ protected function getFieldDefinition() { if (empty($this->fieldDefinition)) { $field_definitions = $this->entityFieldManager->getFieldDefinitions($this->entityTypeId, $this->bundle); $this->fieldDefinition = $field_definitions[$this->fieldName]; } return $this->fieldDefinition; } /** * Returns an array of applicable formatter options for a field. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * * @return array * An array of applicable formatter options. * * @see \Drupal\field_ui\Form\EntityDisplayFormBase::getApplicablePluginOptions() */ protected function getApplicablePluginOptions(FieldDefinitionInterface $field_definition) { $options = $this->formatterManager->getOptions($field_definition->getType()); $applicable_options = []; foreach ($options as $option => $label) { $plugin_class = DefaultFactory::getPluginClass($option, $this->formatterManager->getDefinition($option)); if ($plugin_class::isApplicable($field_definition)) { $applicable_options[$option] = $label; } } return $applicable_options; } /** * Gets the formatter object. * * @param array $parents * The #parents of the element representing the formatter. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @return \Drupal\Core\Field\FormatterInterface * The formatter object. */ protected function getFormatter(array $parents, FormStateInterface $form_state) { // Use the processed values, if available. $configuration = NestedArray::getValue($form_state->getValues(), $parents); if (!$configuration) { // Next check the raw user input. $configuration = NestedArray::getValue($form_state->getUserInput(), $parents); if (!$configuration) { // If no user input exists, use the default values. $configuration = $this->getConfiguration()['formatter']; } } return $this->formatterManager->getInstance([ 'configuration' => $configuration, 'field_definition' => $this->getFieldDefinition(), 'view_mode' => EntityDisplayBase::CUSTOM_MODE, 'prepare' => TRUE, ]); } }
wheelercreek/faithblog
core/modules/layout_builder/src/Plugin/Block/FieldBlock.php
PHP
gpl-2.0
13,279
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "native_thread.cpp" #include "nsk_tools.cpp" #include "jni_tools.cpp" #include "jvmti_tools.cpp" #include "agent_tools.cpp" #include "jvmti_FollowRefObjects.cpp" #include "Injector.cpp" #include "JVMTITools.cpp" #include "agent_common.cpp" #include "ma03t001.cpp"
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/multienv/MA03/ma03t001/libma03t001.cpp
C++
gpl-2.0
1,325
# encoding: utf-8 require 'katello_test_helper' module Katello class OrganizationTestDelete < ActiveSupport::TestCase def test_org_being_deleted Organization.any_instance.stubs(:being_deleted?).returns(true) User.current = User.find(users(:admin).id) org = get_organization(:organization2) org.content_view_environments.first.destroy! org.reload.library.destroy! org.reload.kt_environments.destroy_all id = org.id org.destroy! assert_nil Organization.find_by_id(id) end def test_org_katello_params org = Organization.new(:name => 'My Org', :label => 'my_org') org.instance_variable_set('@service_level', 'foo') org.stubs(:service_level=) org.update_attributes(:service_level => 'bar') assert(org.valid?) end end end
komidore64/katello
test/models/organization_test.rb
Ruby
gpl-2.0
823
/* * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Instance_Sunken_Temple SD%Complete: 100 SDComment:Place Holder SDCategory: Sunken Temple EndScriptData */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "sunken_temple.h" enum Gameobject { GO_ATALAI_STATUE1 = 148830, GO_ATALAI_STATUE2 = 148831, GO_ATALAI_STATUE3 = 148832, GO_ATALAI_STATUE4 = 148833, GO_ATALAI_STATUE5 = 148834, GO_ATALAI_STATUE6 = 148835, GO_ATALAI_LIGHT1 = 148883, GO_ATALAI_LIGHT2 = 148937 }; enum CreatureIds { NPC_ATALALARION = 8580 }; static Position const atalalarianPos = { -466.5134f, 95.19822f, -189.6463f, 0.03490658f }; static uint8 const nStatues = 6; static Position const statuePositions[nStatues] { { -515.553f, 95.25821f, -173.707f, 0.0f }, { -419.8487f, 94.48368f, -173.707f, 0.0f }, { -491.4003f, 135.9698f, -173.707f, 0.0f }, { -491.4909f, 53.48179f, -173.707f, 0.0f }, { -443.8549f, 136.1007f, -173.707f, 0.0f }, { -443.4171f, 53.83124f, -173.707f, 0.0f } }; class instance_sunken_temple : public InstanceMapScript { public: instance_sunken_temple() : InstanceMapScript("instance_sunken_temple", 109) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_sunken_temple_InstanceMapScript(map); } struct instance_sunken_temple_InstanceMapScript : public InstanceScript { instance_sunken_temple_InstanceMapScript(Map* map) : InstanceScript(map) { SetHeaders(DataHeader); State = 0; s1 = false; s2 = false; s3 = false; s4 = false; s5 = false; s6 = false; } ObjectGuid GOAtalaiStatue1; ObjectGuid GOAtalaiStatue2; ObjectGuid GOAtalaiStatue3; ObjectGuid GOAtalaiStatue4; ObjectGuid GOAtalaiStatue5; ObjectGuid GOAtalaiStatue6; uint32 State; bool s1; bool s2; bool s3; bool s4; bool s5; bool s6; void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { case GO_ATALAI_STATUE1: GOAtalaiStatue1 = go->GetGUID(); break; case GO_ATALAI_STATUE2: GOAtalaiStatue2 = go->GetGUID(); break; case GO_ATALAI_STATUE3: GOAtalaiStatue3 = go->GetGUID(); break; case GO_ATALAI_STATUE4: GOAtalaiStatue4 = go->GetGUID(); break; case GO_ATALAI_STATUE5: GOAtalaiStatue5 = go->GetGUID(); break; case GO_ATALAI_STATUE6: GOAtalaiStatue6 = go->GetGUID(); break; } } virtual void Update(uint32 /*diff*/) override // correct order goes form 1-6 { switch (State) { case GO_ATALAI_STATUE1: if (!s1 && !s2 && !s3 && !s4 && !s5 && !s6) { if (GameObject* pAtalaiStatue1 = instance->GetGameObject(GOAtalaiStatue1)) UseStatue(pAtalaiStatue1); s1 = true; State = 0; }; break; case GO_ATALAI_STATUE2: if (s1 && !s2 && !s3 && !s4 && !s5 && !s6) { if (GameObject* pAtalaiStatue2 = instance->GetGameObject(GOAtalaiStatue2)) UseStatue(pAtalaiStatue2); s2 = true; State = 0; }; break; case GO_ATALAI_STATUE3: if (s1 && s2 && !s3 && !s4 && !s5 && !s6) { if (GameObject* pAtalaiStatue3 = instance->GetGameObject(GOAtalaiStatue3)) UseStatue(pAtalaiStatue3); s3 = true; State = 0; }; break; case GO_ATALAI_STATUE4: if (s1 && s2 && s3 && !s4 && !s5 && !s6) { if (GameObject* pAtalaiStatue4 = instance->GetGameObject(GOAtalaiStatue4)) UseStatue(pAtalaiStatue4); s4 = true; State = 0; } break; case GO_ATALAI_STATUE5: if (s1 && s2 && s3 && s4 && !s5 && !s6) { if (GameObject* pAtalaiStatue5 = instance->GetGameObject(GOAtalaiStatue5)) UseStatue(pAtalaiStatue5); s5 = true; State = 0; } break; case GO_ATALAI_STATUE6: if (s1 && s2 && s3 && s4 && s5 && !s6) { if (GameObject* pAtalaiStatue6 = instance->GetGameObject(GOAtalaiStatue6)) { UseStatue(pAtalaiStatue6); UseLastStatue(pAtalaiStatue6); } s6 = true; State = 0; } break; } }; void UseStatue(GameObject* go) { go->SummonGameObject(GO_ATALAI_LIGHT1, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0, 0, 0, 0, 0, 0); go->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } void UseLastStatue(GameObject* go) { for (uint8 i = 0; i < nStatues; ++i) go->SummonGameObject(GO_ATALAI_LIGHT2, statuePositions[i].GetPositionX(), statuePositions[i].GetPositionY(), statuePositions[i].GetPositionZ(), statuePositions[i].GetOrientation(), 0, 0, 0, 0, 0); go->SummonCreature(NPC_ATALALARION, atalalarianPos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200); } void SetData(uint32 type, uint32 data) override { if (type == EVENT_STATE) State = data; } uint32 GetData(uint32 type) const override { if (type == EVENT_STATE) return State; return 0; } }; }; void AddSC_instance_sunken_temple() { new instance_sunken_temple(); }
Tiuz90/TrinityCore
src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp
C++
gpl-2.0
7,077
/*************************************************************************** file : schedulespy.cpp author : Jean-Philippe Meuret (jpmeuret@free.fr) A tool to study the way some special code sections (named "events" here) in the program are actually scheduled at a fine grain level. Absolute time and duration are logged in memory each time declared sections are executed. A detailed schedule of these events can be printed to a text file at the end. ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifdef SCHEDULE_SPY #include <vector> #include <map> #include <sstream> #include <fstream> #include <iomanip> #include <locale> #include <portability.h> #include "tgf.h" class GfScheduleEventLog { public: GfScheduleEventLog(unsigned nMaxEvents, double dIgnoreDelay); void configure(unsigned nMaxEvents, double dIgnoreDelay); void reinit(double dZeroTime); void beginEvent(); void endEvent(); unsigned nbEvents() const { return _vecDurations.size(); }; float startTime(unsigned nEventInd) const { return _vecStartTimes[nEventInd]; }; float duration(unsigned nEventInd) const { return _vecDurations[nEventInd]; }; private: double _dZeroTime; double _dIgnoreDelay; unsigned _nMaxEvents; std::vector<float> _vecStartTimes; std::vector<float> _vecDurations; }; class GfScheduleSpy { protected: GfScheduleSpy(const char* pszName, std::map<std::string, GfScheduleSpy*>& mapSpies); public: ~GfScheduleSpy(); static GfScheduleSpy* self(const char* pszName); void configureEventLog(const char* pszLogName, unsigned nMaxEvents, double dIgnoreDelay); void beginSession(); void beginEvent(const char* pszLogName); void endEvent(const char* pszLogName); void endSession(); void printReport(const char* pszFileName, double fTimeResolution, double fDurationUnit, double fDurationResolution); private: const char* _pszName; std::map<std::string, GfScheduleSpy*>& _rmapSpies; double _dZeroTime; typedef std::map<std::string, GfScheduleEventLog*> MapEventLogs; MapEventLogs _mapEventLogs; }; // GfScheduleEventLog class implementation //------------------------------------------------- // GfScheduleEventLog::GfScheduleEventLog(unsigned nMaxEvents, double dIgnoreDelay) { configure(nMaxEvents, dIgnoreDelay); } // void GfScheduleEventLog::configure(unsigned nMaxEvents, double dIgnoreDelay) { _nMaxEvents = nMaxEvents <= _vecStartTimes.max_size() ? nMaxEvents : _vecStartTimes.max_size(); _dIgnoreDelay = dIgnoreDelay; } // Precondition : configure() void GfScheduleEventLog::reinit(double dZeroTime) { _dZeroTime = dZeroTime; _vecStartTimes.reserve(_nMaxEvents); _vecDurations.reserve(_nMaxEvents); } // Precondition : reinit() void GfScheduleEventLog::beginEvent() { // Ignore events after the _nMaxEvents'th (to avoid vector resize, which is slow). if (_vecStartTimes.size() < _vecStartTimes.capacity()) { const double dNowTime = GfTimeClock(); if (dNowTime >= _dZeroTime + _dIgnoreDelay) _vecStartTimes.push_back((float)(dNowTime - _dZeroTime)); } } // Precondition : beginEvent() void GfScheduleEventLog::endEvent() { // Ignore events after the _nMaxEvents'th (to avoid vector resize, which is slow). if (_vecStartTimes.size() < _vecStartTimes.capacity()) { const double dNowTime = GfTimeClock(); if (dNowTime >= _dZeroTime + _dIgnoreDelay) _vecDurations.push_back((float)(dNowTime - _dZeroTime) - _vecStartTimes[_vecStartTimes.size() - 1]); } } // GfScheduleSpy class implementation //------------------------------------------------------- GfScheduleSpy::GfScheduleSpy(const char* pszName, std::map<std::string, GfScheduleSpy*>& mapSpies) : _pszName(pszName), _rmapSpies(mapSpies) { } GfScheduleSpy::~GfScheduleSpy() { _rmapSpies.erase(_pszName); } GfScheduleSpy* GfScheduleSpy::self(const char* pszName) { static std::map<std::string, GfScheduleSpy*> mapSpies; if (mapSpies.find(pszName) == mapSpies.end()) mapSpies[pszName] = new GfScheduleSpy(pszName, mapSpies); return mapSpies[pszName]; } void GfScheduleSpy::configureEventLog(const char* pszLogName, unsigned nMaxEvents, double dIgnoreDelay) { if (_mapEventLogs.find(pszLogName) == _mapEventLogs.end()) _mapEventLogs[pszLogName] = new GfScheduleEventLog(nMaxEvents, dIgnoreDelay); else _mapEventLogs[pszLogName]->configure(nMaxEvents, dIgnoreDelay); } // Precondition : for all needed event logs, configureEventLog(...) void GfScheduleSpy::beginSession() { GfOut("Beginning schedule spy session\n"); _dZeroTime = GfTimeClock(); MapEventLogs::iterator iterLogs; for (iterLogs = _mapEventLogs.begin(); iterLogs != _mapEventLogs.end(); iterLogs++) (*iterLogs).second->reinit(_dZeroTime); } // Precondition : beginSession() void GfScheduleSpy::beginEvent(const char* pszLogName) { if (_mapEventLogs.find(pszLogName) != _mapEventLogs.end()) _mapEventLogs[pszLogName]->beginEvent(); else GfError("GfScheduleSpy : Can't beginEvent in undeclared event log '%s'\n", pszLogName); } // Precondition : beginEvent(pszLogName) void GfScheduleSpy::endEvent(const char* pszLogName) { if (_mapEventLogs.find(pszLogName) != _mapEventLogs.end()) _mapEventLogs[pszLogName]->endEvent(); else GfError("GfScheduleSpy : Can't endEvent in undeclared event log '%s'\n", pszLogName); } // Precondition : beginSession() void GfScheduleSpy::endSession() { GfOut("Ending schedule spy session\n"); } // Precondition : endSession() void GfScheduleSpy::printReport(const char* pszFileName, double fTimeResolution, double fDurationUnit, double fDurationResolution) { // Output file : // a) Build absolute path (mandatory storage under GfLocalDir()/debug folder. std::ostringstream ossFilePathName; ossFilePathName << GfLocalDir() << "debug/" << pszFileName; GfOut("Writing schedule spy report to %s\n", ossFilePathName.str().c_str()); // b) Create parent dir(s) if needed. const std::size_t nLastSlashPos = ossFilePathName.str().rfind('/'); const std::string strDirPathName(ossFilePathName.str().substr(0, nLastSlashPos)); GfDirCreate(strDirPathName.c_str()); // c) Finally open in write mode. std::ofstream outFStream(ossFilePathName.str().c_str()); if (!outFStream) { GfError("Could not open %s for writing report\n", ossFilePathName.str().c_str()); return; } // Initialize the next event index for each log (a kind of cursor inside each log). std::map<std::string, unsigned> mapNextEventInd; MapEventLogs::const_iterator itLog; for (itLog = _mapEventLogs.begin(); itLog != _mapEventLogs.end(); itLog++) { const std::string& strLogName = (*itLog).first; mapNextEventInd[strLogName] = 0; } // Print columns header (1st line : name of each event log). std::ostringstream ossStepLine; for (itLog = _mapEventLogs.begin(); itLog != _mapEventLogs.end(); itLog++) { const std::string& strLogName = (*itLog).first; ossStepLine << '\t' << strLogName << '\t'; } outFStream << ossStepLine.str() << std::endl; // Print columns header (2nd line : Contents description for each column). ossStepLine.str(""); ossStepLine.imbue(std::locale("")); // Set stream locale to the OS-level-defined one. ossStepLine << "Time"; for (itLog = _mapEventLogs.begin(); itLog != _mapEventLogs.end(); itLog++) { const std::string& strLogName = (*itLog).first; ossStepLine << "\tStart\tDuration"; } outFStream << ossStepLine.str() << std::endl; // For each time step (fTimeResolution), print events info. const int nTimePrecision = (int)ceil(-log10(fTimeResolution)); const int nDurationPrecision = (int)ceil(-log10(fDurationResolution / fDurationUnit)); double dRelTime = 0.0; bool bEventAreLeft = true; ossStepLine << std::fixed; while (bEventAreLeft) { // As many lines per step as necessary to print all avents inside. bool bEventAreLeftInStep = true; while (bEventAreLeftInStep) { unsigned nbProcessedEvents = 0; ossStepLine.str(""); // 1st column = step start time. ossStepLine << std::setprecision(nTimePrecision) << dRelTime; ossStepLine << std::setprecision(nDurationPrecision); for (itLog = _mapEventLogs.begin(); itLog != _mapEventLogs.end(); itLog++) { // Then 2 columns per event : relative start time and duration of the event. const std::string& strLogName = (*itLog).first; const GfScheduleEventLog* pEventLog = (*itLog).second; const unsigned& nEventInd = mapNextEventInd[strLogName]; if (nEventInd < pEventLog->nbEvents() && pEventLog->startTime(nEventInd) >= dRelTime && pEventLog->startTime(nEventInd) < dRelTime + fTimeResolution) { ossStepLine << '\t' << (pEventLog->startTime(nEventInd) - dRelTime) / fDurationUnit << '\t' << pEventLog->duration(nEventInd) / fDurationUnit; mapNextEventInd[strLogName]++; // Event processed. nbProcessedEvents++; } else { ossStepLine << "\t\t"; } } // Print report line if any was produced, // and check if any event left to process in this time step. if (nbProcessedEvents > 0) { outFStream << ossStepLine.str() << std::endl; } else { bEventAreLeftInStep = false; } } // Check if any event left to process. bEventAreLeft = false; for (itLog = _mapEventLogs.begin(); itLog != _mapEventLogs.end(); itLog++) { const std::string& strLogName = (*itLog).first; const GfScheduleEventLog* pEventLog = (*itLog).second; if (mapNextEventInd[strLogName] < pEventLog->nbEvents()) { bEventAreLeft = true; break; } } // Next time step. dRelTime += fTimeResolution; } outFStream.close(); } // C interface functions //----------------------------------------------------------------- /* Configure an event log before using it (can be called more than once to change settings) @ingroup schedulespy \param pszLogName Name/id \param nMaxEvents Maximum number of events to be logged (other ignored) \param dIgnoreDelay Delay (s) before taking Begin/EndEvent into account (from BeginSession time) */ void GfSchedConfigureEventLog(const char* pszSpyName, const char* pszLogName, unsigned nMaxEvents, double dIgnoreDelay) { GfScheduleSpy::self(pszSpyName)->configureEventLog(pszLogName, nMaxEvents, dIgnoreDelay); } /* Start a new spying session @ingroup schedulespy \precondition All event logs must be configured at least once before) */ void GfSchedBeginSession(const char* pszSpyName) { GfScheduleSpy::self(pszSpyName)->beginSession(); } /* Log the beginning of an event (enter the associated code section) @ingroup schedulespy \precondition BeginSession \param pszLogName Name/id */ void GfSchedBeginEvent(const char* pszSpyName, const char* pszLogName) { GfScheduleSpy::self(pszSpyName)->beginEvent(pszLogName); } /* Log the end of an event (exit from the associated code section) @ingroup schedulespy \precondition BeginEvent(pszLogName) \param pszLogName Name/id */ void GfSchedEndEvent(const char* pszSpyName, const char* pszLogName) { GfScheduleSpy::self(pszSpyName)->endEvent(pszLogName); } /* Terminate the current spying session @ingroup schedulespy \precondition BeginSession */ void GfSchedEndSession(const char* pszSpyName) { GfScheduleSpy::self(pszSpyName)->endSession(); } /* Print a table log : * each time step (duration = fTimeResolution) is displayed on as many lines as necessary to log all the events that occured during the step * 1st column = step start time, in seconds since the call to BeginSession * 2 columns for each event log : start time (relative to the step start) and duration @ingroup schedulespy \param pszFileName Target text file for the log \param fTimeResolution Resolution to use for time = duration of 1 step \param fDurationUnit Unit to use for durations (1 = 1s, 1.0e-3 = 1ms ...) \param fDurationResolution Resolution to use for durations (must divide fDurationUnit) \precondition EndSession */ void GfSchedPrintReport(const char* pszSpyName, const char* pszFileName, double fTimeResolution, double fDurationUnit, double fDurationResolution) { std::ostringstream ossFileName; ossFileName << pszSpyName << '-' << pszFileName; GfScheduleSpy::self(pszSpyName)->printReport(ossFileName.str().c_str(), fTimeResolution, fDurationUnit, fDurationResolution); } #endif // SCHEDULE_SPY
kumar003vinod/SpeedDreams
src/libs/tgf/schedulespy.cpp
C++
gpl-2.0
13,156
/* * Copyright (C) 2004 Nathan Lutchansky <lutchann@litech.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <pthread.h> #include <mpegaudio.h> #include <event.h> #include <log.h> #include <frame.h> #include <stream.h> #include <encoders.h> #include <conf_parse.h> struct mp2_encoder { struct stream *output; struct stream_destination *input; MpegAudioContext ctx; int samprate; int channels; int bitrate; struct soft_queue *inq; struct soft_queue *outq; pthread_t thread; }; static const int bitrateII_tab[] = { -1, 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 384000, -1 }; static const int samrate_tab[] = { 44100, 48000, 32000, -1 }; int MPA_encode_init(MpegAudioContext *s, int freq, int bitrate, int channels); int MPA_encode_frame(MpegAudioContext *s, unsigned char *frame, int buf_size, unsigned char *sampbuf, int step); static void *mp2_loop( void *data ) { struct mp2_encoder *en = (struct mp2_encoder *)data; struct frame *mp2, *in; unsigned char *pcm, *pcmbuf; int maxlen, off = 0, s, d, c; pcmbuf = (unsigned char *)malloc( 2 * en->channels * 1152 ); maxlen = 1152 / 8 * bitrateII_tab[en->bitrate] / samrate_tab[en->samprate] + 1; in = get_next_event( en->inq ); for(;;) { if( ( in->length - off ) < 1152 * in->step ) { int split = ( in->length - off ) / in->step; /* Copy the samples from off to length into pcmbuf */ for( c = 0; c < en->channels; ++c ) for( s = off + ( c << 1 ), d = c << 1; s < in->length; s += in->step, d += en->channels << 1 ) { pcmbuf[d] = in->d[s]; pcmbuf[d + 1] = in->d[s + 1]; } /* Get rid of old frame and get new frame */ unref_frame( in ); in = get_next_event( en->inq ); /* Set off to be the offset *after* we get the partial * frame from the beginning */ off = ( 1152 - split ) * in->step; /* Copy the samples from 0 to off into pcmbuf */ for( c = 0; c < en->channels; ++c ) for( s = c << 1, d = ( ( split * en->channels ) << 1 ) + ( c << 1 ); s < off; s += in->step, d += en->channels << 1 ) { pcmbuf[d] = in->d[s]; pcmbuf[d + 1] = in->d[s + 1]; } pcm = pcmbuf; } else { pcm = in->d + off; off += 1152 * in->step; } if( ! ( mp2 = new_frame() ) ) continue; mp2->format = FORMAT_MPA; mp2->width = mp2->height = 0; mp2->key = 1; mp2->length = MPA_encode_frame( &en->ctx, mp2->d, maxlen, pcm, pcm == pcmbuf ? ( en->channels << 1 ) : in->step ); if( soft_queue_add( en->outq, mp2 ) < 0 ) unref_frame( mp2 ); } return NULL; } static void get_back_frame( struct event_info *ei, void *d ) { struct mp2_encoder *en = (struct mp2_encoder *)d; struct frame *f = (struct frame *)ei->data; deliver_frame_to_stream( f, en->output ); } static void mp2_encode( struct frame *input, void *d ) { struct mp2_encoder *en = (struct mp2_encoder *)d; if( soft_queue_add( en->inq, input ) < 0 ) unref_frame( input ); } static void get_framerate( struct stream *s, int *fincr, int *fbase ) { struct mp2_encoder *en = (struct mp2_encoder *)s->private; en->input->stream->get_framerate( en->input->stream, fincr, fbase ); } static void set_running( struct stream *s, int running ) { struct mp2_encoder *en = (struct mp2_encoder *)s->private; set_waiting( en->input, running ); } /************************ CONFIGURATION DIRECTIVES ************************/ static void *start_block(void) { struct mp2_encoder *en; en = (struct mp2_encoder *)malloc( sizeof( struct mp2_encoder ) ); en->output = NULL; en->bitrate = 0; return en; } static int end_block( void *d ) { struct mp2_encoder *en = (struct mp2_encoder *)d; int fincr, fbase; if( ! en->input ) { spook_log( SL_ERR, "mp2: missing input stream name" ); return -1; } if( ! en->output ) { spook_log( SL_ERR, "mp2: missing output stream name" ); return -1; } en->input->stream->get_framerate( en->input->stream, &fincr, &fbase ); en->channels = fincr; switch( fbase / fincr ) { case 44100: en->samprate = 0; break; case 48000: en->samprate = 1; break; case 32000: en->samprate = 2; break; default: spook_log( SL_ERR, "mp2: sample rate %d cannot be encoded to MP2", fbase / fincr ); return -1; } if( bitrateII_tab[en->bitrate] < 0 ) { spook_log( SL_ERR, "mp2: no bitrate specified!" ); return -1; } if( MPA_encode_init( &en->ctx, samrate_tab[en->samprate], bitrateII_tab[en->bitrate], en->channels ) < 0 ) { spook_log( SL_ERR, "mp2: unable to initialize MPEG encoder" ); return -1; } en->inq = new_soft_queue( 16 ); en->outq = new_soft_queue( 16 ); add_softqueue_event( en->outq, 0, get_back_frame, en ); pthread_create( &en->thread, NULL, mp2_loop, en ); return 0; } static int set_input( int num_tokens, struct token *tokens, void *d ) { struct mp2_encoder *en = (struct mp2_encoder *)d; int format = FORMAT_PCM; if( ! ( en->input = connect_to_stream( tokens[1].v.str, mp2_encode, en, &format, 1 ) ) ) { spook_log( SL_ERR, "mp2: unable to connect to stream \"%s\"", tokens[1].v.str ); return -1; } return 0; } static int set_output( int num_tokens, struct token *tokens, void *d ) { struct mp2_encoder *en = (struct mp2_encoder *)d; en->output = new_stream( tokens[1].v.str, FORMAT_MPA, en ); if( ! en->output ) { spook_log( SL_ERR, "mp2: unable to create stream \"%s\"", tokens[1].v.str ); return -1; } en->output->get_framerate = get_framerate; en->output->set_running = set_running; return 0; } static int set_bitrate( int num_tokens, struct token *tokens, void *d ) { struct mp2_encoder *en = (struct mp2_encoder *)d; if( tokens[1].v.num < 1000 ) tokens[1].v.num *= 1000; for( en->bitrate = 1; bitrateII_tab[en->bitrate] > 0; ++en->bitrate ) if( bitrateII_tab[en->bitrate] == tokens[1].v.num ) return 0; spook_log( SL_ERR, "mp2: invalid bitrate %d", tokens[1].v.num ); return -1; } static struct statement config_statements[] = { /* directive name, process function, min args, max args, arg types */ { "input", set_input, 1, 1, { TOKEN_STR } }, { "output", set_output, 1, 1, { TOKEN_STR } }, { "bitrate", set_bitrate, 1, 1, { TOKEN_NUM } }, /* empty terminator -- do not remove */ { NULL, NULL, 0, 0, {} } }; int mp2_init(void) { register_config_context( "encoder", "mp2", start_block, end_block, config_statements ); return 0; }
BrandoJS/Paparazzi_vtol
sw/in_progress/videolizer/spook/encoder-mp2.c
C
gpl-2.0
7,249
<?php namespace TYPO3\CMS\Version\Dependency; /** * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Object to create and keep track of element or reference entities. */ class DependencyEntityFactory { /** * @var array */ protected $elements = array(); /** * @var array */ protected $references = array(); /** * Gets and registers a new element. * * @param string $table * @param integer $id * @param array $data (optional) * @param \TYPO3\CMS\Version\Dependency\DependencyResolver $dependency * @return \TYPO3\CMS\Version\Dependency\ElementEntity */ public function getElement($table, $id, array $data = array(), \TYPO3\CMS\Version\Dependency\DependencyResolver $dependency) { /** @var $element ElementEntity */ $element = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Version\\Dependency\\ElementEntity', $table, $id, $data, $dependency); $elementName = $element->__toString(); if (!isset($this->elements[$elementName])) { $this->elements[$elementName] = $element; } return $this->elements[$elementName]; } /** * Gets and registers a new reference. * * @param \TYPO3\CMS\Version\Dependency\ElementEntity $element * @param string $field * @return \TYPO3\CMS\Version\Dependency\ReferenceEntity */ public function getReference(\TYPO3\CMS\Version\Dependency\ElementEntity $element, $field) { $referenceName = $element->__toString() . '.' . $field; if (!isset($this->references[$referenceName][$field])) { $this->references[$referenceName][$field] = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Version\\Dependency\\ReferenceEntity', $element, $field); } return $this->references[$referenceName][$field]; } /** * Gets and registers a new reference. * * @param string $table * @param integer $id * @param string $field * @param array $data (optional) * @param \TYPO3\CMS\Version\Dependency\DependencyResolver $dependency * @return \TYPO3\CMS\Version\Dependency\ReferenceEntity * @see getElement * @see getReference */ public function getReferencedElement($table, $id, $field, array $data = array(), \TYPO3\CMS\Version\Dependency\DependencyResolver $dependency) { return $this->getReference($this->getElement($table, $id, $data, $dependency), $field); } }
demonege/sutogo
typo3/sysext/version/Classes/Dependency/DependencyEntityFactory.php
PHP
gpl-2.0
2,674
#include <harness.h> int main(int argc, char** argv){ int i; char buffer[256]; char* tk; FILTERCHAIN* tmp_chn; FILTERCHAIN* del_chn; HARNESS_INSTANCE* hinstance; if(harness_init(argc,argv,&hinstance)){ printf("Error: Initialization failed.\n"); skygw_log_write(LOGFILE_ERROR,"Error: Initialization failed.\n"); skygw_logmanager_done(); skygw_logmanager_exit(); return 1; } if(instance.verbose){ printf("\n\n\tFilter Test Harness\n\n"); } while(instance.running){ printf("Harness> "); memset(buffer,0,256); fgets(buffer,256,stdin); tk = strtok(buffer," \n"); switch(user_input(tk)) { case RUNFILTERS: if(instance.head->next == NULL){ printf("No filters loaded.\n"); break; } if(instance.buffer == NULL){ if(instance.infile<0){ manual_query(); }else{ load_query(); } } route_buffers(); break; case LOAD_FILTER: tk = strtok(NULL," \n"); tmp_chn = load_filter_module(tk); if(!tmp_chn || !load_filter(tmp_chn,instance.conf)){ printf("Error creating filter instance.\n"); skygw_log_write(LOGFILE_ERROR,"Error: Error creating filter instance.\n"); }else{ instance.head = tmp_chn; } break; case DELETE_FILTER: tk = strtok(NULL," \n\0"); tmp_chn = instance.head; del_chn = instance.head; if(tk){ if(strcmp(instance.head->name,tk) == 0){ instance.head = instance.head->next; }else{ while(del_chn->next){ if(strcmp(del_chn->name,tk) == 0){ tmp_chn->next = del_chn->next; break; }else{ tmp_chn = del_chn; del_chn = del_chn->next; } } } if(del_chn && del_chn->next){ printf("Deleted %s.\n",del_chn->name); if(del_chn->instance){ del_chn->instance->freeSession(del_chn->filter,del_chn->session); } free(del_chn->filter); free(del_chn->down); free(del_chn->name); free(del_chn); }else{ printf("No matching filter found.\n"); } } break; case LOAD_CONFIG: tk = strtok(NULL," \n\0"); if(!load_config(tk)){ free_filters(); } break; case SET_INFILE: tk = strtok(NULL," \n\0"); if(instance.infile >= 0){ close(instance.infile); free(instance.infile_name); } if(tk!= NULL){ free_buffers(); instance.infile = open_file(tk,0); if(instance.infile >= 0){ load_query(); instance.infile_name = strdup(tk); if(instance.verbose){ printf("Loaded %d queries from file '%s'\n",instance.buffer_count,instance.infile_name); } } }else{ instance.infile = -1; printf("Queries are read from: command line\n"); } break; case SET_OUTFILE: tk = strtok(NULL," \n\0"); if(instance.outfile >= 0){ close(instance.outfile); free(instance.outfile_name); } if(tk!= NULL){ instance.outfile = open_file(tk,1); if(instance.outfile >= 0){ instance.outfile_name = strdup(tk); printf("Output is logged to: %s\n",tk); } }else{ instance.outfile = -1; printf("Output logging disabled.\n"); } break; case SESS_COUNT: tk = strtok(NULL," \n\0"); free_buffers(); free_filters(); instance.session_count = atoi(tk); printf("Sessions set to: %d\n", instance.session_count); break; case THR_COUNT: instance.running = 0; pthread_mutex_unlock(&instance.work_mtx); for(i = 0;i<instance.thrcount;i++){ pthread_join(instance.thrpool[i],NULL); } pthread_mutex_lock(&instance.work_mtx); instance.running = 1; tk = strtok(NULL," \n\0"); instance.thrcount = atoi(tk); void* t_thr_pool; if(!(t_thr_pool = realloc(instance.thrpool,instance.thrcount * sizeof(pthread_t)))){ printf("Error: Out of memory\n"); skygw_log_write(LOGFILE_ERROR,"Error: Out of memory\n"); instance.running = 0; break; } instance.thrpool = t_thr_pool; intptr_t thr_num = 1; for(i = 0;i<instance.thrcount;i++){ pthread_create(&instance.thrpool[i], NULL, (void*)work_buffer, (void*)thr_num++); } printf("Threads set to: %d\n", instance.thrcount); break; case QUIT: instance.running = 0; pthread_mutex_unlock(&instance.work_mtx); for(i = 0;i<instance.thrcount;i++){ pthread_join(instance.thrpool[i],NULL); } break; case UNDEFINED: printf("Command not found, enter \"help\" for a list of commands\n"); break; default: break; } } if(instance.infile >= 0){ close(instance.infile); } if(instance.outfile >= 0){ close(instance.outfile); } free_buffers(); free_filters(); skygw_logmanager_done(); skygw_logmanager_exit(); free(instance.head); return 0; } operation_t user_input(char* tk) { if(tk){ char cmpbuff[256]; int tklen = strcspn(tk," \n\0"); memset(cmpbuff,0,256); if(tklen > 0 && tklen < 256){ strncpy(cmpbuff,tk,tklen); strcat(cmpbuff,"\0"); if(strcmp(tk,"run")==0 || strcmp(tk,"r")==0){ return RUNFILTERS; }else if(strcmp(cmpbuff,"add")==0){ return LOAD_FILTER; }else if(strcmp(cmpbuff,"delete")==0){ return DELETE_FILTER; }else if(strcmp(cmpbuff,"clear")==0){ tk = strtok(NULL," \n\0"); if(tk && !strcmp(tk,"queries")){ free_buffers(); printf("Queries cleared.\n"); }else if(tk && !strcmp(tk,"filters")){ printf("Filters cleared.\n"); free_filters(); }else{ printf("All cleared.\n"); free_buffers(); free_filters(); } return OK; }else if(strcmp(cmpbuff,"config")==0){ return LOAD_CONFIG; }else if(strcmp(cmpbuff,"in")==0){ return SET_INFILE; }else if(strcmp(cmpbuff,"out")==0){ return SET_OUTFILE; }else if(strcmp(cmpbuff,"exit")==0 || strcmp(cmpbuff,"quit")==0 || strcmp(cmpbuff,"q")==0){ return QUIT; }else if(strcmp(cmpbuff,"help")==0){ print_help(); return OK; }else if(strcmp(cmpbuff,"status")==0){ print_status(); return OK; }else if(strcmp(cmpbuff,"quiet")==0){ instance.verbose = 0; return OK; }else if(strcmp(cmpbuff,"verbose")==0){ instance.verbose = 1; return OK; }else if(strcmp(cmpbuff,"sessions")==0){ return SESS_COUNT; }else if(strcmp(cmpbuff,"threads")==0){ return THR_COUNT; } } } return UNDEFINED; } void print_help() { printf("\nFilter Test Harness\n\n" "List of commands:\n %-32s%s\n %-32s%s\n %-32s%s\n %-32s%s\n %-32s%s\n " "%-32s%s\n %-32s%s\n %-32s%s\n %-32s%s\n %-32s%s\n %-32s%s\n %-32s%s\n " "%-32s%s\n %-32s%s\n" ,"help","Prints this help message." ,"run","Feeds the contents of the buffer to the filter chain." ,"add <filter name>","Loads a filter and appeds it to the end of the chain." ,"delete <filter name>","Deletes a filter." ,"status","Lists all loaded filters and queries" ,"clear","Clears the filter chain." ,"config <file name>","Loads filter configurations from a file." ,"in <file name>","Source file for the SQL statements." ,"out <file name>","Destination file for the SQL statements. Defaults to stdout if no parameters were passed." ,"threads <number>","Sets the amount of threads to use" ,"sessions <number>","How many sessions to create for each filter. This clears all loaded filters." ,"quiet","Print only error messages." ,"verbose","Print everything." ,"exit","Exit the program" ); } void manual_query() { char query[1024]; unsigned int qlen; GWBUF** tmpbuf; free_buffers(); printf("Enter query: "); fgets(query,1024,stdin); qlen = strnlen(query, 1024); if((tmpbuf = malloc(sizeof(GWBUF*)))== NULL){ printf("Error: cannot allocate enough memory.\n"); skygw_log_write(LOGFILE_ERROR,"Error: cannot allocate enough memory.\n"); return; } instance.buffer = tmpbuf; instance.buffer_count = 1; instance.buffer[0] = gwbuf_alloc(qlen + 5); gwbuf_set_type(instance.buffer[0],GWBUF_TYPE_MYSQL); memcpy(instance.buffer[0]->sbuf->data + 5,query,qlen); instance.buffer[0]->sbuf->data[0] = (qlen); instance.buffer[0]->sbuf->data[1] = (qlen << 8); instance.buffer[0]->sbuf->data[2] = (qlen << 16); instance.buffer[0]->sbuf->data[3] = 0x00; instance.buffer[0]->sbuf->data[4] = 0x03; } void print_status() { if(instance.head->filter){ printf("Filters currently loaded:\n\n"); FILTERCHAIN* hd = instance.head; int i = 1; while(hd->filter){ printf("%d: %s\n", i++, hd->name); hd = hd->next; } }else{ printf("No filters loaded.\n"); } printf("\n"); if(instance.buffer_count > 0){ printf("%d queries loaded.\n",instance.buffer_count); }else{ printf("No queries loaded.\n"); } printf("Using %d threads and %d sessions.\n",instance.thrcount,instance.session_count); if(instance.infile_name){ printf("Input is read from %s.\n",instance.infile_name); } if(instance.outfile_name){ printf("Output is written to %s.\n",instance.outfile_name); } }
sjmudd/MaxScale
server/modules/filter/test/harness_ui.c
C
gpl-2.0
8,833
using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; using System; using System.IO; using System.Linq; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.Library.Resolvers { public class PhotoResolver : ItemResolver<Photo> { private readonly IImageProcessor _imageProcessor; private readonly ILibraryManager _libraryManager; private readonly IFileSystem _fileSystem; public PhotoResolver(IImageProcessor imageProcessor, ILibraryManager libraryManager, IFileSystem fileSystem) { _imageProcessor = imageProcessor; _libraryManager = libraryManager; _fileSystem = fileSystem; } /// <summary> /// Resolves the specified args. /// </summary> /// <param name="args">The args.</param> /// <returns>Trailer.</returns> protected override Photo Resolve(ItemResolveArgs args) { if (!args.IsDirectory) { // Must be an image file within a photo collection var collectionType = args.GetCollectionType(); if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase) || (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.GetLibraryOptions().EnablePhotos)) { if (IsImageFile(args.Path, _imageProcessor)) { var filename = Path.GetFileNameWithoutExtension(args.Path); // Make sure the image doesn't belong to a video file var files = args.DirectoryService.GetFiles(_fileSystem.GetDirectoryName(args.Path)); var libraryOptions = args.GetLibraryOptions(); foreach (var file in files) { if (IsOwnedByMedia(_libraryManager, libraryOptions, file.FullName, filename)) { return null; } } return new Photo { Path = args.Path }; } } } return null; } internal static bool IsOwnedByMedia(ILibraryManager libraryManager, LibraryOptions libraryOptions, string file, string imageFilename) { if (libraryManager.IsVideoFile(file, libraryOptions)) { return IsOwnedByResolvedMedia(libraryManager, libraryOptions, file, imageFilename); } return false; } internal static bool IsOwnedByResolvedMedia(ILibraryManager libraryManager, LibraryOptions libraryOptions, string file, string imageFilename) { if (imageFilename.StartsWith(Path.GetFileNameWithoutExtension(file), StringComparison.OrdinalIgnoreCase)) { return true; } return false; } private static readonly string[] IgnoreFiles = { "folder", "thumb", "landscape", "fanart", "backdrop", "poster", "cover", "logo", "default" }; internal static bool IsImageFile(string path, IImageProcessor imageProcessor) { var filename = Path.GetFileNameWithoutExtension(path) ?? string.Empty; if (IgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase)) { return false; } if (IgnoreFiles.Any(i => filename.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1)) { return false; } return imageProcessor.SupportedInputFormats.Contains((Path.GetExtension(path) ?? string.Empty).TrimStart('.'), StringComparer.OrdinalIgnoreCase); } } }
razzfazz/Emby
Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs
C#
gpl-2.0
4,211
/* Test the `vreinterpretQp16_s16' ARM Neon intrinsic. */ /* This file was autogenerated by neon-testgen. */ /* { dg-do assemble } */ /* { dg-require-effective-target arm_neon_ok } */ /* { dg-options "-save-temps -O0 -mfpu=neon -mfloat-abi=softfp" } */ #include "arm_neon.h" void test_vreinterpretQp16_s16 (void) { poly16x8_t out_poly16x8_t; int16x8_t arg0_int16x8_t; out_poly16x8_t = vreinterpretq_p16_s16 (arg0_int16x8_t); } /* { dg-final { cleanup-saved-temps } } */
intervigilium/cs259-or32-gcc
gcc/testsuite/gcc.target/arm/neon/vreinterpretQp16_s16.c
C
gpl-2.0
483
! ! Copyright (C) 2005 Eyvaz Isaev ! This file is distributed under the terms of the ! GNU General Public License. See the file `License' ! in the root directory of the present distribution, ! or http://www.gnu.org/copyleft/gpl.txt . ! ! Program is designed to map the Fermi Surface using XCrySDen ! See www.xcrysden.org ! ! Eyvaz Isaev, 2004-2009 ! eyvaz_isaev@yahoo.com, isaev@ifm.liu.se ! ! Theoretical Physics Department, ! Moscow State Institute of Steel and Alloys, Russia ! ! Department of Physics, Chemistry, and Biology (IFM), Linkoping University, Sweden, ! ! Division of Materials Theory, Institute of Physics and Materials Sciene, ! Uppsala University, Sweden ! ! Description: ! The program reads output files for band structure calculations produced by PWscf. ! Input_FS file contains reciprocal basis vectors, the Fermi level, grids numbers, and ! System name extracted from self-consistent output file (See Input_FS). ! The output file(s) Bands_FS.bxsf (non spin-polarized) or Bands_FS_up.bxsf and Bands_FS_down.bxsf ! (spin-polarized) is (are) written so that it can be used directly ! in conjunction with XCrySDen to visualize the Fermi Surface. ! ! Spin-polarized calculations are allowed ! !----------------------------------------------------------------------- PROGRAM bands_FS !----------------------------------------------------------------------- ! implicit real*8(a-h,o-z) parameter (max_kpoints=100000, max_bands=500) real, allocatable :: e_up(:,:),e_down(:,:) real :: x(3),y(3),z(3) real, allocatable :: valence(:) integer :: n_kpoints, nbands integer :: KS_number character*100 line character*24 nkpt character*33 n_bands character*38 Band_structure character*13 kpoint character*80 sysname character*22 Magnetic character*9 blank character*16 KS_states logical lsda ! nkpt=' number of k points=' n_bands='nbnd' Band_structure=' End of band structure calculation' kpoint=' k =' blank=' ' KS_states='Kohn-Sham states' ! Magnetic=' Starting magnetic' lsda=.false. ! ! Read input information ! open(12,file='input_FS') read(12,*) n_start, n_last read(12,*) E_fermi read(12,*) sysname read(12,*) na,nb, nc read(12,*) x(1),x(2),x(3) read(12,*) y(1),y(2),y(3) read(12,*) z(1),z(2),z(3) print*,'E_Fermi=', E_Fermi x0=0. y0=0. z0=0. close(12) do while( .true. ) read(5,'(a)',end=110) line if(line(16:31).eq.KS_states) then goto 110 endif enddo 110 continue Backspace(5) read(5,'(36x,I9)') KS_number print*, 'KS_number==', KS_number if(n_last.gt.KS_number) then write(6,'("n_last > number of Kohn-Sham states")') write(6,'("Wrong input: you have specifed more bands than number of Kohn-Sham states")') stop endif print*, 'LSDA====', lsda rewind(5) do while( .true. ) read(5,'(a)',end=111) line if(line(1:22).eq.Magnetic) then lsda=.true. goto 111 endif enddo 111 continue print*, 'LSDA====', lsda rewind(5) do while( .true. ) read(5,'(a)') line if(line(1:24).eq.nkpt) then backspace(5) read(line,'(24x,i6)') n_kpoints goto 101 endif enddo 101 if(n_kpoints.gt.max_kpoints) then stop 'Toooooooo many k-points' endif ! End of band structure calculation do while( .true. ) read(5,'(a)',end=102) line if(line(1:38).eq.Band_Structure) then goto 102 endif enddo 102 continue print*, ' lsda==', lsda ! Find bands number, nbands ! read(5,*) read(5,*) read(5,*) if(lsda.eqv..true.) then read(5,*) read(5,*) read(5,*) endif nlines=0 3 read(5,'(a)',end=4) line if(line(1:11).ne.blank) then nlines=nlines+1 goto 3 else goto 4 endif 4 continue print*,'nlines==', nlines do k=1,nlines+1 backspace(5) enddo nbands=0 do k=1,nlines read(5,'(a)') line do j=1,8 ! ! 9 is due to output format for e(n,k): 2X, 8f9.4 ! if(line((3+9*(j-1)):(3+9*j)).ne.blank) then nbands=nbands+1 endif enddo enddo print*, 'nbands==', nbands if(lsda.eqv..true.) then ! begin for lsda calculations n_kpoints=n_kpoints/2 print*, 'kpoints=', n_kpoints allocate (e_up(n_kpoints,nbands)) allocate (e_down(n_kpoints,nbands)) ! back nlines+1 positions (number of eigenvalues lines plus one blank line) ! do k=1,nlines+1 backspace(5) enddo ! ! back 3 positions for k-points ! backspace(5) backspace(5) backspace(5) ! Now ready to start ! read(5,*) ! ! Reading spin-up energies ! do k1=1,n_kpoints read(5,*) read(5,*) read(5,*) read(5,*,end=99) (e_up(k1,j),j=1,nbands) enddo 99 continue read(5,*) read(5,*) read(5,*) ! Reading Spin-down bands do k1=1,n_kpoints read(5,*) read(5,*) read(5,*) read(5,*,end=96) (e_down(k1,j),j=1,nbands) enddo 96 continue open(11,file='Bands_FS_up.bxsf',form='formatted') ! Write header file here write(11, '(" BEGIN_INFO")') write(11, '(" #")') write(11, '(" # this is a Band-XCRYSDEN-Structure-File")') write(11, '(" # aimed at Visualization of Fermi Surface")') write(11, '(" #")') write(11, '(" # Case: ",A)') Sysname write(11, '(" #")') write(11, '(" Fermi Energy: ", f12.4)') E_Fermi write(11, '(" END_INFO")') write(11, '(" BEGIN_BLOCK_BANDGRID_3D")') write(11, '(" band_energies")') write(11, '(" BANDGRID_3D_BANDS")') write(11, '(I5)') n_last-n_start+1 write(11, '(3I5)') na+1, nb+1, nc+1 write(11, '(3f10.6)') x0, y0, z0 write(11, '(3f10.6)') x(1), x(2), x(3) write(11, '(3f10.6)') y(1), y(2), y(3) write(11, '(3f10.6)') z(1), z(2), z(3) do i=n_start, n_last write(11, '("BAND:", i4)') i write(11, '(6f10.4)') (e_up(j,i),j=1,n_kpoints) enddo ! Write 2 last lines write(11, '(" END_BANDGRID_3D")') write(11, '(" END_BLOCK_BANDGRID_3D")') close(11) open(11,file='Bands_FS_down.bxsf',form='formatted') ! Write header file here write(11, '(" BEGIN_INFO")') write(11, '(" #")') write(11, '(" # this is a Band-XCRYSDEN-Structure-File")') write(11, '(" # aimed at Visualization of Fermi Surface")') write(11, '(" #")') write(11, '(" # Case: ",A)') Sysname write(11, '(" #")') write(11, '(" Fermi Energy: ", f12.4)') E_Fermi write(11, '(" END_INFO")') write(11, '(" BEGIN_BLOCK_BANDGRID_3D")') write(11, '(" band_energies")') write(11, '(" BANDGRID_3D_BANDS")') write(11, '(I5)') n_last-n_start+1 write(11, '(3I5)') na+1, nb+1, nc+1 write(11, '(3f10.6)') x0, y0, z0 write(11, '(3f10.6)') x(1), x(2), x(3) write(11, '(3f10.6)') y(1), y(2), y(3) write(11, '(3f10.6)') z(1), z(2), z(3) do i=n_start, n_last write(11, '("BAND:", i4)') i write(11, '(6f10.4)') (e_down(j,i),j=1,n_kpoints) enddo ! Write 2 last lines write(11, '(" END_BANDGRID_3D")') write(11, '(" END_BLOCK_BANDGRID_3D")') close(11) deallocate (e_up) deallocate (e_down) print*,'SPIN-POLARIZED CASE: FINISHED!!!!' !!! end for LSDA calculations else ! end of lsda section ! allocate (e_up(n_kpoints,nbands)) ! back nlines+1 positions (number of eigenvalues lines plus one blank line) ! print*, 'nlines==', nlines do k=1,nlines+1 backspace(5) enddo ! ! back 3 positions for k-points ! backspace(5) backspace(5) backspace(5) print*, 'n_kpoints===', n_kpoints do k1=1,n_kpoints read(5,*) read(5,*) read(5,*) read(5,*,end=98) (e_up(k1,j),j=1,nbands) ! read(5,'(2x,8f9.4)',end=98) (e_up(k1,j),j=1,nbands) enddo 98 continue open(11,file='Bands_FS.bxsf',form='formatted') ! Write header file here write(11, '(" BEGIN_INFO")') write(11, '(" #")') write(11, '(" # this is a Band-XCRYSDEN-Structure-File")') write(11, '(" # aimed at Visualization of Fermi Surface")') write(11, '(" #")') write(11, '(" # Case: ",A)') Sysname write(11, '(" #")') write(11, '(" Fermi Energy: ", f12.4)') E_Fermi write(11, '(" END_INFO")') write(11, '(" BEGIN_BLOCK_BANDGRID_3D")') write(11, '(" band_energies")') write(11, '(" BANDGRID_3D_BANDS")') write(11, '(I5)') n_last-n_start+1 write(11, '(3I5)') na+1, nb+1, nc+1 write(11, '(3f10.6)') x0, y0, z0 write(11, '(3f10.6)') x(1), x(2), x(3) write(11, '(3f10.6)') y(1), y(2), y(3) write(11, '(3f10.6)') z(1), z(2), z(3) do i=n_start, n_last write(11, '("BAND:", i4)') i write(11, '(6f10.4)') (e_up(j,i),j=1,n_kpoints) enddo ! Write 2 last lines write(11, '(" END_BANDGRID_3D")') write(11, '(" END_BLOCK_BANDGRID_3D")') close(11) deallocate (e_up) print*,'NON-SPIN-POLARIZED CASE: FINISHED!!!!' endif stop END PROGRAM bands_FS
nvarini/espresso_adios
PW/tools/bands_FS.f90
FORTRAN
gpl-2.0
10,793
label#toggle-icon { display: none; } .l-responsive-page-container, #menu, #menu .sub-nav { -webkit-transform: translate(0, 0) !important; -ms-transform: translate(0, 0) !important; transform: translate(0, 0) !important; } #menu label, #menu .sub-nav, #menu .sub-heading, #header label { display: none; } #menu { left: auto; height: 0; width: 100%; z-index: 1; } #menu > ul { position: relative; margin-top: 0; display: inline-table; } #menu ul:after { content: ""; clear: both; display: block; } #menu ul li { float: left; position: relative; } #menu ul li a:only-child:after { content: ""; } #menu ul li a:after { content: "\25BA"; position: absolute; right: 0.5em; margin-top: -1.5625em; display: block; font: 1.5em Arial; } #menu ul li:hover > ul { display: block; } #menu ul ul { position: absolute; left: 0; } #menu ul ul li { float: none; width: 13.75em; } #menu ul ul li a { padding: 0 1.5em; } #menu ul ul li a:after { right: 0.375em; margin-top: -1.6875em; -webkit-transform: none; -ms-transform: none; transform: none; } #menu ul ul .sub-nav { float: left; top: 0; left: 13.75em; margin-left: 0; } #menu ul .sub-nav { top: auto; bottom: auto; left: auto; width: auto; margin-top: 0; } #menu ul .fly-left ul { left: -13.75em; } #menu { background-color: #222; height: 3.15em; } #menu > ul { font-size: 0.875em; border: 0; } #menu > ul > li { border: 0; } #menu ul { border-top: 0; } #menu ul:after { content: ""; clear: both; display: block; } #menu ul li { float: left; position: relative; text-align: left; } #menu ul li a { padding: 0.5em 2.5em 0.5em 1.5em; } #menu ul li a:only-child { padding-right: 1.5em; } #menu ul li a:only-child:after { content: ""; } #menu ul li a:after { content: "\203A"; position: absolute; right: 0.5em; margin-top: -1.5625em; display: block; font: 1.5em Arial; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } #menu ul li:hover > a { background-color: #333; -webkit-transition: background-color .25s ease; transition: background-color 0.25s ease; } #menu ul ul li { width: 13.75em; border-left: 0; } #menu ul ul li a { padding: 0 1.5em; } #menu ul ul li a:after { right: 0.375em; margin-top: -1.6875em; -webkit-transform: none; -ms-transform: none; transform: none; } #menu ul .fly-left a:after { right: auto; left: 0.5em; left: 0.375em; margin-top: -1.5625em; -webkit-transform: rotate(-180deg); -ms-transform: rotate(-180deg); transform: rotate(-180deg); }
kbulloch/blog_drupals
sites/all/modules/responsive_menu/css/responsive_menu_desktop.css
CSS
gpl-2.0
3,096
/*************************************************************** CAMERA Power control ****************************************************************/ #include <mach/gpio.h> #include <asm/gpio.h> #include <linux/clk.h> #include <linux/io.h> #include <mach/board.h> #include <mach/msm_iomap.h> #include <linux/regulator/consumer.h> #include <mach/vreg.h> #include <linux/gpio.h> #include "sec_cam_pmic.h" extern unsigned int board_hw_revision; #if defined(CONFIG_S5K5CCGX)//Power on/off functions for S5KCCGX sensor void cam_ldo_power_on_1(void) { printk("#### cam_ldo_power_on_1 ####\n"); if(gpio_request(S5K5CCGX_CAM_STBY, "s5k5ccgx_standby")<0) pr_err("%s: Request GPIO Standby failed\n", __func__); if(gpio_request(S5K5CCGX_CAM_RESET, "s5k5ccgx_reset")<0) pr_err("%s: Request GPIO Reset failed\n", __func__); gpio_direction_output(S5K5CCGX_CAM_STBY, 0); gpio_direction_output(S5K5CCGX_CAM_RESET, 0); gpio_set_value_cansleep(S5K5CCGX_CAM_STBY, 0); gpio_set_value_cansleep(S5K5CCGX_CAM_RESET, 0); //VCAM_A_2.8V #if defined(CONFIG_MACH_INFINITE_DUOS_CTC) || defined(CONFIG_MACH_KYLEPLUS_CTC) if(gpio_request(S5K5CCGX_CAM_A_EN, "s5k5ccgx_vcam_a_en")<0) pr_err("%s: Request GPIO VCAM_A failed\n", __func__); gpio_direction_output(S5K5CCGX_CAM_A_EN, 0); gpio_set_value_cansleep(S5K5CCGX_CAM_A_EN, 0); gpio_set_value(S5K5CCGX_CAM_A_EN, 1); msleep(1); #endif //VCAM_IO_1.8V #if defined(CONFIG_MACH_KYLEPLUS_OPEN) || defined(CONFIG_MACH_KYLEPLUS_CTC) if(gpio_request(S5K5CCGX_CAM_IO_EN, "s5k5ccgx_vcam_io")<0) pr_err("%s: Request GPIO VCAM_IO failed\n", __func__); gpio_direction_output(S5K5CCGX_CAM_IO_EN, 0); gpio_set_value_cansleep(S5K5CCGX_CAM_IO_EN, 0); gpio_set_value(S5K5CCGX_CAM_IO_EN, 1); msleep(10); #endif } void cam_ldo_power_on_2(void) { printk("#### cam_ldo_power_on_2 ####\n"); msleep(1); gpio_set_value_cansleep(S5K5CCGX_CAM_STBY, 1); msleep(1); gpio_set_value_cansleep(S5K5CCGX_CAM_RESET, 1); msleep(1); } void cam_ldo_power_off_1(void) { printk("#### cam_ldo_power_off_1 ####\n"); gpio_set_value_cansleep(S5K5CCGX_CAM_RESET, 0); msleep(1); } void cam_ldo_power_off_2(void) { printk("#### cam_ldo_power_off_2 ####\n"); gpio_set_value_cansleep(S5K5CCGX_CAM_STBY, 0); msleep(1); //VCAM_A_2.8V #if defined(CONFIG_MACH_INFINITE_DUOS_CTC) || defined(CONFIG_MACH_KYLEPLUS_CTC) gpio_set_value_cansleep(S5K5CCGX_CAM_A_EN, 0); gpio_free(S5K5CCGX_CAM_A_EN); msleep(1); #endif //VCAM_IO_1.8V #if defined(CONFIG_MACH_KYLEPLUS_OPEN) || defined(CONFIG_MACH_KYLEPLUS_CTC) gpio_set_value_cansleep(S5K5CCGX_CAM_IO_EN, 0); gpio_free(S5K5CCGX_CAM_IO_EN); msleep(1); #endif gpio_free(S5K5CCGX_CAM_STBY); gpio_free(S5K5CCGX_CAM_RESET); } #else void cam_ldo_power_on_1(void) { printk("#### cam_ldo_power_on_1 ####\n"); gpio_request(ARUBA_CAM_STBY, "aruba_stby"); gpio_request(ARUBA_CAM_RESET, "aruba_reset"); gpio_request(ARUBA_CAM_A_EN, "aruba_a_en"); #ifdef CONFIG_S5K4ECGX gpio_request(ARUBA_CAM_C_EN, "aruba_c_en"); gpio_request(ARUBA_CAM_AF_EN, "aruba_af_en"); #endif gpio_direction_output(ARUBA_CAM_STBY, 0); gpio_direction_output(ARUBA_CAM_RESET, 0); gpio_direction_output(ARUBA_CAM_A_EN, 0); #ifdef CONFIG_S5K4ECGX gpio_direction_output(ARUBA_CAM_C_EN, 0); gpio_direction_output(ARUBA_CAM_AF_EN, 0); #endif gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 gpio_set_value_cansleep(ARUBA_CAM_A_EN, 0); #ifdef CONFIG_S5K4ECGX gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); msleep(1); // printk("ARUBA_CAM_C_EN = %d , CAM_AF_EN = %d \n", gpio_get_value(ARUBA_CAM_C_EN), gpio_get_value(ARUBA_CAM_AF_EN)); gpio_set_value(ARUBA_CAM_C_EN, 1); gpio_set_value(ARUBA_CAM_AF_EN, 1); msleep(1); // printk("ARUBA_CAM_C_EN = %d , CAM_AF_EN = %d \n", gpio_get_value(ARUBA_CAM_C_EN), gpio_get_value(ARUBA_CAM_AF_EN)); #endif // printk("ARUBA_CAM_A_EN = %d\n", gpio_get_value(ARUBA_CAM_A_EN)); gpio_set_value(ARUBA_CAM_A_EN, 1); // printk("ARUBA_CAM_A_EN = %d\n", gpio_get_value(ARUBA_CAM_A_EN)); } void cam_ldo_power_on_2(void) { printk("#### cam_ldo_power_on_2 ####\n"); // printk("ARUBA_CAM_STBY = %d\n", gpio_get_value(ARUBA_CAM_STBY)); msleep(1); gpio_set_value_cansleep(ARUBA_CAM_STBY, 1); //STBYN :: MSM_GPIO 96 msleep(1); // printk("ARUBA_CAM_STBY = %d\n", gpio_get_value(ARUBA_CAM_STBY)); // printk("ARUBA_CAM_RESET = %d\n", gpio_get_value(ARUBA_CAM_RESET)); gpio_set_value_cansleep(ARUBA_CAM_RESET, 1); //RSTN :: MSM_GPIO 85 msleep(1); // printk("ARUBA_CAM_RESET = %d\n", gpio_get_value(ARUBA_CAM_RESET)); } void cam_ldo_power_off_1(void) { printk("#### cam_ldo_power_off_1 ####\n"); gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 } void cam_ldo_power_off_2(void) { printk("#### cam_ldo_power_off_2 ####\n"); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_A_EN, 0); #ifdef CONFIG_S5K4ECGX gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_AF_EN, 0); #endif msleep(10); #ifdef CONFIG_S5K4ECGX gpio_free(ARUBA_CAM_C_EN); gpio_free(ARUBA_CAM_AF_EN); #endif gpio_free(ARUBA_CAM_A_EN); gpio_free(ARUBA_CAM_STBY); gpio_free(ARUBA_CAM_RESET); } #endif #if defined(CONFIG_S5K4ECGX) static DEFINE_SPINLOCK(spinlock); void cam_flash_main_on(int flashMode) { int ret, i; printk("#### cam_flash_main_on ####\n"); if(flash_mode == FLASH_MODE_NONE) { flash_mode = flashMode; } else { printk("FLASH MAIN ON SKIP \n"); return; } ret = gpio_request(ARUBA_CAM_FLASH_EN, "aruba_flash_en"); if (ret < 0) { printk("cam_flash_main_on GPIO Request Fail !!! \n"); } ret = gpio_request(ARUBA_CAM_FLASH_SET, "aruba_flash_set"); if (ret < 0) { printk("cam_flash_main_on GPIO Request Fail !!! \n"); } printk("ARUBA_CAM_FLASH_EN = %d\n", gpio_get_value(ARUBA_CAM_FLASH_EN)); printk("ARUBA_CAM_FLASH_SET = %d\n", gpio_get_value(ARUBA_CAM_FLASH_SET)); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); #if defined (CONFIG_MACH_DELOS_CTC) if(board_hw_revision == 4){ gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); udelay(30); //DS data start time for(i=0; i<7; i++){ gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(10); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(5); } gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); udelay(10); //high 1 gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); //EOD_L End of Low for 10 us udelay(10); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //EOD_HEnd of High for 400 us udelay(400); //start Flash mode gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 1); }else{ gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 1); msleep(10); } #elif defined(CONFIG_MACH_DELOS_OPEN) gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 1); msleep(10); printk("ARUBA_CAM_FLASH_EN = %d\n", gpio_get_value(ARUBA_CAM_FLASH_EN)); printk("ARUBA_CAM_FLASH_SET = %d\n", gpio_get_value(ARUBA_CAM_FLASH_SET)); #else for(i=0;i<15;i++) { gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); mdelay(1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); printk("count %d \n",i); } gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); msleep(10); printk("ARUBA_CAM_FLASH_EN = %d\n", gpio_get_value(ARUBA_CAM_FLASH_EN)); printk("ARUBA_CAM_FLASH_SET = %d\n", gpio_get_value(ARUBA_CAM_FLASH_SET)); #endif } void cam_flash_torch_on(int flashMode) { int ret,i; unsigned long flags; printk("#### cam_flash_torch_on ####\n"); printk("#######board_hw_revision : %d\n",board_hw_revision); if(flash_mode == FLASH_MODE_NONE) { flash_mode = flashMode; } else { printk("FLASH TORCH ON SKIP \n"); return; } ret = gpio_request(ARUBA_CAM_FLASH_EN, "aruba_flash_en"); if (ret < 0) { printk("cam_flash_main_on GPIO Request Fail !!! \n"); } ret = gpio_request(ARUBA_CAM_FLASH_SET, "aruba_flash_set"); if (ret < 0) { printk("cam_flash_main_on GPIO Request Fail !!! \n"); } // gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); // gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 1); #if defined (CONFIG_MACH_DELOS_CTC) if(board_hw_revision == 4){ spin_lock_irqsave(&spinlock, flags); //LVP setting before starting Torch mode gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); usleep(15); //DS data start time for(i=0; i<7; i++){ gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(2); } gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); udelay(5); //high 1 gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); //EOD_L End of Low for 10 us udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //EOD_HEnd of High for 400 us udelay(400); //start torch enable gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); udelay(15); //DS data start time gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); udelay(5); //high 1 gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); udelay(5); //high 1 gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(5); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //Low 0 udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); udelay(5); //high 1 gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); //EOD_L End of Low for 10 us udelay(2); gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); //EOD_HEnd of High for 400 us udelay(400); spin_unlock_irqrestore(&spinlock, flags); }else{ //RT8515 FLASH gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); } #else gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 1); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); #endif } void cam_flash_off(int flashMode) { int ret; printk("#### cam_flash_off ####\n"); if(flash_mode == flashMode) { flash_mode = FLASH_MODE_NONE; } else { printk("FLASH OFF SKIP \n"); return; } ret = gpio_request(ARUBA_CAM_FLASH_EN, "aruba_flash_en"); if (ret < 0) { printk("cam_flash_main_on GPIO Request Fail !!! \n"); } ret = gpio_request(ARUBA_CAM_FLASH_SET, "aruba_flash_set"); if (ret < 0) { printk("cam_flash_main_on GPIO Request Fail !!! \n"); } #if defined(CONFIG_MACH_DELOS_OPEN) gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); gpio_free(ARUBA_CAM_FLASH_EN); gpio_free(ARUBA_CAM_FLASH_SET); #else if(board_hw_revision == 4){ gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); mdelay(1); }else{ gpio_set_value_cansleep(ARUBA_CAM_FLASH_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_FLASH_SET, 0); } #endif } #endif #if defined(CONFIG_MACH_BAFFIN_DUOS_CTC) static struct msm_cam_clk_info cam_clk_info[] = { {"cam_m_clk", MSM_SENSOR_MCLK_24HZ}, }; int32_t msm_sensor_power_up_baffin_duos(struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; struct msm_camera_sensor_info *data = s_ctrl->sensordata; printk("#### msm_sensor_power_up_baffin_duos ####\n"); CDBG("%s: %d\n", __func__, __LINE__); gpio_tlmm_config(GPIO_CFG(FRONT_CAM_STBY, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(FRONT_CAM_RESET, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(FRONT_CAM_C_EN, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); s_ctrl->reg_ptr = kzalloc(sizeof(struct regulator *) * data->sensor_platform_info->num_vreg, GFP_KERNEL); if (!s_ctrl->reg_ptr) { pr_err("%s: could not allocate mem for regulators\n", __func__); return -ENOMEM; } rc = msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: regulator on failed\n", __func__); goto config_vreg_failed; } rc = msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: msm_camera_enable_vreg on failed\n", __func__); goto config_vreg_failed; } gpio_request(ARUBA_CAM_STBY, "baffin_stby"); gpio_request(ARUBA_CAM_RESET, "baffin_reset"); gpio_request(ARUBA_CAM_A_EN, "baffin_a_en"); gpio_request(ARUBA_CAM_C_EN, "baffin_c_en"); gpio_request(ARUBA_CAM_AF_EN, "baffin_af_en"); gpio_request(FRONT_CAM_STBY, "front_cam_stby"); gpio_request(FRONT_CAM_RESET, "front_cam_reset"); gpio_direction_output(ARUBA_CAM_STBY, 0); gpio_direction_output(ARUBA_CAM_RESET, 0); gpio_direction_output(ARUBA_CAM_A_EN, 0); gpio_direction_output(ARUBA_CAM_C_EN, 0); gpio_direction_output(ARUBA_CAM_AF_EN, 0); gpio_direction_output(FRONT_CAM_STBY, 0); gpio_direction_output(FRONT_CAM_RESET, 0); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 gpio_set_value_cansleep(ARUBA_CAM_A_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); gpio_set_value_cansleep(FRONT_CAM_STBY, 0); gpio_set_value_cansleep(FRONT_CAM_RESET, 0); gpio_set_value(ARUBA_CAM_A_EN, 1); // 2 - MAIN VREG_A 2.8 ON mdelay(1); gpio_set_value(FRONT_CAM_C_EN, 1); // 3- 2M CAM CORE 1.8V ON gpio_set_value(ARUBA_CAM_AF_EN, 1); mdelay(1); rc = msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 1); if (rc < 0) { pr_err("%s: clk enable failed\n", __func__); goto enable_clk_failed; } mdelay(10); gpio_set_value(ARUBA_CAM_C_EN, 1); // 8 - 5M CAM_C_EN ON mdelay(1); gpio_set_value(ARUBA_CAM_STBY, 1); //9 - 5M STBY ON mdelay(1); gpio_set_value(ARUBA_CAM_RESET, 1); // 10 - 5M RESET ON if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(1); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_enable_i2c_mux(data->sensor_platform_info->i2c_conf); return rc; enable_clk_failed: //kk0704.park :: ARUBA TEMP msm_camera_config_gpio_table(data, 0); config_gpio_failed: msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); enable_vreg_failed: msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); config_vreg_failed: //kk0704.park ARUBA TEMP msm_camera_request_gpio_table(data, 0); request_gpio_failed: kfree(s_ctrl->reg_ptr); return rc; } int32_t msm_sensor_power_down_baffin_duos(struct msm_sensor_ctrl_t *s_ctrl) { struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s\n", __func__); printk("#### msm_sensor_power_down_baffin_duos ####\n"); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_disable_i2c_mux( data->sensor_platform_info->i2c_conf); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(0); msleep(1); gpio_set_value_cansleep(FRONT_CAM_RESET, 0); // turn off : 2M FRONT_CAM_RESET gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); // turn off : 5M CAM_RESET msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 0); msleep(1); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //turn off : 5M STBY gpio_set_value_cansleep(FRONT_CAM_C_EN, 0); //turn off 2M CAM_C_EN msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); gpio_set_value_cansleep(ARUBA_CAM_A_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_AF_EN, 0); msleep(10); #ifdef CONFIG_S5K4ECGX gpio_free(ARUBA_CAM_C_EN); gpio_free(ARUBA_CAM_AF_EN); #endif gpio_free(ARUBA_CAM_A_EN); gpio_free(ARUBA_CAM_STBY); gpio_free(ARUBA_CAM_RESET); gpio_free(FRONT_CAM_RESET); gpio_free(FRONT_CAM_STBY); gpio_free(FRONT_CAM_C_EN); } #endif #if defined (CONFIG_MACH_ARUBASLIM_OPEN) static struct msm_cam_clk_info cam_clk_info[] = { {"cam_m_clk", MSM_SENSOR_MCLK_24HZ}, }; int32_t msm_sensor_power_up_aruba_open(struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s: %d\n", __func__, __LINE__); s_ctrl->reg_ptr = kzalloc(sizeof(struct regulator *) * data->sensor_platform_info->num_vreg, GFP_KERNEL); if (!s_ctrl->reg_ptr) { pr_err("%s: could not allocate mem for regulators\n", __func__); return -ENOMEM; } rc = msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: regulator on failed\n", __func__); goto config_vreg_failed; } gpio_request(ARUBA_CAM_STBY, "aruba_stby"); gpio_request(ARUBA_CAM_RESET, "aruba_reset"); gpio_request(ARUBA_CAM_IO_EN, "aruba_a_en"); gpio_request(ARUBA_CAM_C_EN, "aruba_c_en"); gpio_request(ARUBA_CAM_AF_EN, "aruba_af_en"); if (rc < 0) { pr_err("%s: [ARUBASLIM]gpio_request failed\n", __func__); } gpio_direction_output(ARUBA_CAM_STBY, 0); gpio_direction_output(ARUBA_CAM_RESET, 0); gpio_direction_output(ARUBA_CAM_IO_EN, 0); gpio_direction_output(ARUBA_CAM_C_EN, 0); gpio_direction_output(ARUBA_CAM_AF_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 gpio_set_value_cansleep(ARUBA_CAM_IO_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); msleep(1); rc = msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: [ARUBASLIM]enable regulator failed\n", __func__); goto enable_vreg_failed; } udelay(150);// VCAM_A_2.8V gpio_set_value(ARUBA_CAM_IO_EN, 1); udelay(10);// GPIO 4 : EN_C_EN / VVT_1.8V gpio_set_value(ARUBA_CAM_C_EN, 1); // GPIO 107 : CAM_C_EN gpio_set_value(ARUBA_CAM_AF_EN, 1); gpio_set_value(FRONT_CAM_STBY, 1); msleep(2); // gpio 76 : VT_CAM_STBY rc = msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 1); if (rc < 0) { pr_err("%s: clk enable failed\n", __func__); goto enable_clk_failed; } msleep(2); // CAM_MCLK gpio_set_value(FRONT_CAM_RESET, 1); msleep(1); // VT_CAM_RESET gpio_set_value_cansleep(FRONT_CAM_STBY, 0); gpio_free(FRONT_CAM_STBY); gpio_set_value(FRONT_CAM_STBY, 0); msleep(1); // VT_CAM_RESET : LOW gpio_set_value(ARUBA_CAM_C_EN, 1); msleep(1); //GPIO 107 : CAM_C_EN gpio_set_value_cansleep(ARUBA_CAM_STBY, 1); msleep(1); //GPIO 96 : 5M_CAM_STBY gpio_set_value_cansleep(ARUBA_CAM_RESET, 1); msleep(1); //GPIO 85 : 5M_CAM_RESET usleep_range(1000, 2000); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(1); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_enable_i2c_mux(data->sensor_platform_info->i2c_conf); return rc; enable_clk_failed: //kk0704.park :: ARUBA TEMP msm_camera_config_gpio_table(data, 0); config_gpio_failed: msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); enable_vreg_failed: msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); config_vreg_failed: //kk0704.park ARUBA TEMP msm_camera_request_gpio_table(data, 0); request_gpio_failed: kfree(s_ctrl->reg_ptr); return rc; } int32_t msm_sensor_power_down_aruba_open(struct msm_sensor_ctrl_t *s_ctrl) { struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s\n", __func__); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_disable_i2c_mux( data->sensor_platform_info->i2c_conf); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(0); msleep(1); cam_flash_off(FLASH_MODE_CAMERA); //kk0704.park :: Flash Off when Power down gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); // GPIO 85 msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 0); msleep(1); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //GPIO 96 gpio_set_value_cansleep(FRONT_CAM_RESET, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_IO_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_AF_EN, 0); gpio_free(ARUBA_CAM_RESET); gpio_free(ARUBA_CAM_STBY); gpio_free(FRONT_CAM_RESET); gpio_free(ARUBA_CAM_C_EN); gpio_free(ARUBA_CAM_IO_EN); gpio_free(ARUBA_CAM_AF_EN); msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); kfree(s_ctrl->reg_ptr); return 0; } #elif (defined (CONFIG_MACH_ARUBA_OPEN) && !defined(CONFIG_MACH_KYLEPLUS_OPEN)) static struct msm_cam_clk_info cam_clk_info[] = { {"cam_m_clk", MSM_SENSOR_MCLK_24HZ}, }; int32_t msm_sensor_power_up_aruba_open(struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s: %d\n", __func__, __LINE__); s_ctrl->reg_ptr = kzalloc(sizeof(struct regulator *) * data->sensor_platform_info->num_vreg, GFP_KERNEL); if (!s_ctrl->reg_ptr) { pr_err("%s: could not allocate mem for regulators\n", __func__); return -ENOMEM; } rc = msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: regulator on failed\n", __func__); goto config_vreg_failed; } gpio_request(ARUBA_CAM_STBY, "aruba_stby"); gpio_request(ARUBA_CAM_RESET, "aruba_reset"); gpio_request(ARUBA_CAM_IO_EN, "aruba_a_en"); gpio_request(ARUBA_CAM_C_EN, "aruba_c_en"); gpio_request(ARUBA_CAM_AF_EN, "aruba_af_en"); gpio_direction_output(ARUBA_CAM_STBY, 0); gpio_direction_output(ARUBA_CAM_RESET, 0); gpio_direction_output(ARUBA_CAM_IO_EN, 0); gpio_direction_output(ARUBA_CAM_C_EN, 0); gpio_direction_output(ARUBA_CAM_AF_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 gpio_set_value_cansleep(ARUBA_CAM_IO_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); msleep(1); gpio_set_value(ARUBA_CAM_C_EN, 1); gpio_set_value(ARUBA_CAM_AF_EN, 1); msleep(1); rc = msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: enable regulator failed\n", __func__); goto enable_vreg_failed; } msleep(1); gpio_set_value(ARUBA_CAM_IO_EN, 1); // gpio_tlmm_config(GPIO_CFG(15, 1, 1, 1, 3, 1),GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(ARUBA_CAM_FLASH_SET, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); if (s_ctrl->clk_rate != 0) cam_clk_info->clk_rate = s_ctrl->clk_rate; rc = msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 1); if (rc < 0) { pr_err("%s: clk enable failed\n", __func__); goto enable_clk_failed; } msleep(1); gpio_set_value_cansleep(ARUBA_CAM_STBY, 1); //STBYN :: MSM_GPIO 96 msleep(1); gpio_set_value_cansleep(ARUBA_CAM_RESET, 1); //RSTN :: MSM_GPIO 85 msleep(1); usleep_range(1000, 2000); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(1); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_enable_i2c_mux(data->sensor_platform_info->i2c_conf); return rc; enable_clk_failed: //kk0704.park :: ARUBA TEMP msm_camera_config_gpio_table(data, 0); config_gpio_failed: msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); enable_vreg_failed: msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); config_vreg_failed: //kk0704.park ARUBA TEMP msm_camera_request_gpio_table(data, 0); request_gpio_failed: kfree(s_ctrl->reg_ptr); return rc; } int32_t msm_sensor_power_down_aruba_open(struct msm_sensor_ctrl_t *s_ctrl) { struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s\n", __func__); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_disable_i2c_mux( data->sensor_platform_info->i2c_conf); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(0); msleep(1); cam_flash_off(FLASH_MODE_CAMERA); //kk0704.park :: Flash Off when Power down gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 0); msleep(1); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_IO_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_AF_EN, 0); msleep(10); gpio_free(ARUBA_CAM_C_EN); gpio_free(ARUBA_CAM_AF_EN); gpio_free(ARUBA_CAM_IO_EN); gpio_free(ARUBA_CAM_STBY); gpio_free(ARUBA_CAM_RESET); msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); kfree(s_ctrl->reg_ptr); return 0; } #elif defined (CONFIG_MACH_DELOS_OPEN) || defined (CONFIG_MACH_DELOS_CTC) || defined(CONFIG_MACH_HENNESSY_DUOS_CTC) static struct msm_cam_clk_info cam_clk_info[] = { {"cam_m_clk", MSM_SENSOR_MCLK_24HZ}, }; int32_t msm_sensor_power_up_delos_open(struct msm_sensor_ctrl_t *s_ctrl) { int32_t rc = 0; printk("msm_sensor_power_up_delos_open \n"); struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s: %d\n", __func__, __LINE__); #if defined(CONFIG_MACH_DELOS_OPEN) gpio_tlmm_config(GPIO_CFG(CAM_MCLK, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(CAM_I2C_SCL, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(CAM_I2C_SDA, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE); #endif #if defined (CONFIG_MACH_DELOS_DUOS_CTC) || defined(CONFIG_MACH_HENNESSY_DUOS_CTC) rc = gpio_request(ARUBA_CAM_A_EN, "aruba_stby"); gpio_direction_output(ARUBA_CAM_A_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_A_EN, 0); gpio_set_value(ARUBA_CAM_A_EN, 1); #endif s_ctrl->reg_ptr = kzalloc(sizeof(struct regulator *) * data->sensor_platform_info->num_vreg, GFP_KERNEL); if (!s_ctrl->reg_ptr) { pr_err("%s: could not allocate mem for regulators\n", __func__); return -ENOMEM; } rc = msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: regulator on failed\n", __func__); goto config_vreg_failed; } rc = gpio_request(ARUBA_CAM_STBY, "aruba_stby"); rc = gpio_request(ARUBA_CAM_RESET, "aruba_reset"); rc = gpio_request(ARUBA_CAM_IO_EN, "aruba_a_en"); rc = gpio_request(ARUBA_CAM_C_EN, "aruba_c_en"); rc = gpio_request(ARUBA_CAM_AF_EN, "aruba_af_en"); gpio_direction_output(ARUBA_CAM_STBY, 0); gpio_direction_output(ARUBA_CAM_RESET, 0); gpio_direction_output(ARUBA_CAM_IO_EN, 0); gpio_direction_output(ARUBA_CAM_C_EN, 0); gpio_direction_output(ARUBA_CAM_AF_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 gpio_set_value_cansleep(ARUBA_CAM_IO_EN, 0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); rc = msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 1); if (rc < 0) { pr_err("%s: enable regulator failed\n", __func__); goto enable_vreg_failed; } //msleep(1); usleep(50); // gpio_set_value(FRONT_CAM_ID, 1); //VT-VGA core High // printk("FRONT_CAM_ID = %d\n", gpio_get_value(FRONT_CAM_ID)); gpio_set_value(ARUBA_CAM_IO_EN, 1); //SENSOR I/O High printk("ARUBA_CAM_IO_EN = %d\n", gpio_get_value(ARUBA_CAM_IO_EN)); usleep(50); gpio_set_value(FRONT_CAM_STBY, 1); //VT STBY High usleep(10); printk("FRONT_CAM_STBY = %d\n", gpio_get_value(FRONT_CAM_STBY)); if (s_ctrl->clk_rate != 0) cam_clk_info->clk_rate = s_ctrl->clk_rate; rc = msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 1); if (rc < 0) { pr_err("%s: clk enable failed\n", __func__); goto enable_clk_failed; } usleep(2000); //at least VT Reset high 4ms after VT STBY on gpio_set_value(FRONT_CAM_RESET, 1); //VT RESET High printk("FRONT_CAM_RESET = %d\n", gpio_get_value(FRONT_CAM_RESET)); usleep(1000); gpio_set_value(FRONT_CAM_STBY, 0); //VT STBY Low printk("FRONT_CAM_STBY = %d\n", gpio_get_value(FRONT_CAM_STBY)); gpio_set_value(ARUBA_CAM_C_EN, 1); printk("ARUBA_CAM_C_EN = %d\n", gpio_get_value(ARUBA_CAM_C_EN)); gpio_set_value(ARUBA_CAM_AF_EN, 1); //5M Core High printk("ARUBA_CAM_AF_EN = %d\n", gpio_get_value(ARUBA_CAM_AF_EN)); // gpio_tlmm_config(GPIO_CFG(15, 1, 1, 1, 3, 1),GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(ARUBA_CAM_FLASH_SET, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); usleep(100); gpio_set_value_cansleep(ARUBA_CAM_STBY, 1); //STBYN :: MSM_GPIO 96 printk("ARUBA_CAM_STBY = %d\n", gpio_get_value(ARUBA_CAM_STBY)); usleep(15); gpio_set_value_cansleep(ARUBA_CAM_RESET, 1); //RSTN :: MSM_GPIO 85 printk("ARUBA_CAM_RESET = %d\n", gpio_get_value(ARUBA_CAM_RESET)); usleep(10); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(1); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_enable_i2c_mux(data->sensor_platform_info->i2c_conf); return rc; enable_clk_failed: //kk0704.park :: ARUBA TEMP msm_camera_config_gpio_table(data, 0); config_gpio_failed: msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); enable_vreg_failed: msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); config_vreg_failed: //kk0704.park ARUBA TEMP msm_camera_request_gpio_table(data, 0); request_gpio_failed: kfree(s_ctrl->reg_ptr); return rc; } int32_t msm_sensor_power_down_delos_open(struct msm_sensor_ctrl_t *s_ctrl) { struct msm_camera_sensor_info *data = s_ctrl->sensordata; CDBG("%s\n", __func__); if (data->sensor_platform_info->i2c_conf && data->sensor_platform_info->i2c_conf->use_i2c_mux) msm_sensor_disable_i2c_mux( data->sensor_platform_info->i2c_conf); if (data->sensor_platform_info->ext_power_ctrl != NULL) data->sensor_platform_info->ext_power_ctrl(0); msleep(1); printk("msm_sensor_power_down_delos_open \n"); cam_flash_off(FLASH_MODE_CAMERA); //kk0704.park :: Flash Off when Power down gpio_set_value_cansleep(ARUBA_CAM_RESET, 0); //RSTN :: MSM_GPIO 85 msm_cam_clk_enable(&s_ctrl->sensor_i2c_client->client->dev, cam_clk_info, &s_ctrl->cam_clk, ARRAY_SIZE(cam_clk_info), 0); msleep(1); gpio_set_value_cansleep(ARUBA_CAM_STBY, 0); //STBYN :: MSM_GPIO 96 usleep(10); gpio_set_value_cansleep(FRONT_CAM_RESET,0); gpio_set_value_cansleep(ARUBA_CAM_C_EN, 0); usleep(2000); gpio_set_value_cansleep(ARUBA_CAM_IO_EN, 0); // gpio_set_value_cansleep(FRONT_CAM_ID, 0); gpio_set_value_cansleep(ARUBA_CAM_AF_EN, 0); #if defined (CONFIG_MACH_DELOS_DUOS_CTC) || defined(CONFIG_MACH_HENNESSY_DUOS_CTC) gpio_set_value_cansleep(ARUBA_CAM_A_EN, 0); #endif msm_camera_enable_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); msm_camera_config_vreg(&s_ctrl->sensor_i2c_client->client->dev, s_ctrl->sensordata->sensor_platform_info->cam_vreg, s_ctrl->sensordata->sensor_platform_info->num_vreg, s_ctrl->reg_ptr, 0); kfree(s_ctrl->reg_ptr); #if defined (CONFIG_MACH_DELOS_DUOS_CTC) || defined(CONFIG_MACH_HENNESSY_DUOS_CTC) gpio_free(ARUBA_CAM_A_EN); #endif gpio_free(ARUBA_CAM_C_EN); gpio_free(ARUBA_CAM_AF_EN); gpio_free(ARUBA_CAM_IO_EN); gpio_free(ARUBA_CAM_STBY); gpio_free(ARUBA_CAM_RESET); #if defined(CONFIG_MACH_DELOS_OPEN) gpio_tlmm_config(GPIO_CFG(CAM_MCLK, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(CAM_I2C_SCL, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(CAM_I2C_SDA, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); #endif return 0; } #endif
yajnab/android_kernel_samsung_msm8625
drivers/media/video/msm/sensors/sec_cam_pmic.c
C
gpl-2.0
36,158
<?php namespace Drupal\Tests\field\Functional; use Drupal\Component\Utility\Html; use Drupal\Core\Entity\Entity\EntityFormDisplay; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\Form\FormState; use Drupal\entity_test\Entity\EntityTest; use Drupal\entity_test\Entity\EntityTestBaseFieldDisplay; use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldStorageConfig; /** * Tests field form handling. * * @group field */ class FormTest extends FieldTestBase { /** * Modules to enable. * * Locale is installed so that TranslatableMarkup actually does something. * * @var array */ public static $modules = ['node', 'field_test', 'options', 'entity_test', 'locale']; /** * An array of values defining a field single. * * @var array */ protected $fieldStorageSingle; /** * An array of values defining a field multiple. * * @var array */ protected $fieldStorageMultiple; /** * An array of values defining a field with unlimited cardinality. * * @var array */ protected $fieldStorageUnlimited; /** * An array of values defining a field. * * @var array */ protected $field; protected function setUp() { parent::setUp(); $web_user = $this->drupalCreateUser(['view test entity', 'administer entity_test content']); $this->drupalLogin($web_user); $this->fieldStorageSingle = [ 'field_name' => 'field_single', 'entity_type' => 'entity_test', 'type' => 'test_field', ]; $this->fieldStorageMultiple = [ 'field_name' => 'field_multiple', 'entity_type' => 'entity_test', 'type' => 'test_field', 'cardinality' => 4, ]; $this->fieldStorageUnlimited = [ 'field_name' => 'field_unlimited', 'entity_type' => 'entity_test', 'type' => 'test_field', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, ]; $this->field = [ 'entity_type' => 'entity_test', 'bundle' => 'entity_test', 'label' => $this->randomMachineName() . '_label', 'description' => '[site:name]_description', 'weight' => mt_rand(0, 127), 'settings' => [ 'test_field_setting' => $this->randomMachineName(), ], ]; } public function testFieldFormSingle() { $field_storage = $this->fieldStorageSingle; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name) ->save(); // Display creation form. $this->drupalGet('entity_test/add'); // Create token value expected for description. $token_description = Html::escape($this->config('system.site')->get('name')) . '_description'; $this->assertText($token_description, 'Token replacement for description is displayed'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed'); $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed'); // Check that hook_field_widget_form_alter() does not believe this is the // default value form. $this->assertNoText('From hook_field_widget_form_alter(): Default form is true.', 'Not default value form in hook_field_widget_form_alter().'); // Check that hook_field_widget_form_alter() does not believe this is the // default value form. $this->assertNoText('From hook_field_widget_multivalue_form_alter(): Default form is true.', 'Not default value form in hook_field_widget_form_alter().'); // Submit with invalid value (field-level validation). $edit = [ "{$field_name}[0][value]" => -1, ]; $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertRaw(t('%name does not accept the value -1.', ['%name' => $this->field['label']]), 'Field validation fails with invalid input.'); // TODO : check that the correct field is flagged for error. // Create an entity $value = mt_rand(1, 127); $edit = [ "{$field_name}[0][value]" => $value, ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created'); $entity = EntityTest::load($id); $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved'); // Display edit form. $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->assertFieldByName("{$field_name}[0][value]", $value, 'Widget is displayed with the correct default value'); $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed'); // Update the entity. $value = mt_rand(1, 127); $edit = [ "{$field_name}[0][value]" => $value, ]; $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]), 'Entity was updated'); $this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$id]); $entity = EntityTest::load($id); $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated'); // Empty the field. $value = ''; $edit = [ "{$field_name}[0][value]" => $value, ]; $this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save')); $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]), 'Entity was updated'); $this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$id]); $entity = EntityTest::load($id); $this->assertTrue($entity->{$field_name}->isEmpty(), 'Field was emptied'); } /** * Tests field widget default values on entity forms. */ public function testFieldFormDefaultValue() { $field_storage = $this->fieldStorageSingle; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; $default = rand(1, 127); $this->field['default_value'] = [['value' => $default]]; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name) ->save(); // Display creation form. $this->drupalGet('entity_test/add'); // Test that the default value is displayed correctly. $this->assertFieldByXpath("//input[@name='{$field_name}[0][value]' and @value='$default']"); // Try to submit an empty value. $edit = [ "{$field_name}[0][value]" => '', ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created.'); $entity = EntityTest::load($id); $this->assertTrue($entity->{$field_name}->isEmpty(), 'Field is now empty.'); } public function testFieldFormSingleRequired() { $field_storage = $this->fieldStorageSingle; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; $this->field['required'] = TRUE; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name) ->save(); // Submit with missing required value. $edit = []; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $this->assertRaw(t('@name field is required.', ['@name' => $this->field['label']]), 'Required field with no value fails validation'); // Create an entity $value = mt_rand(1, 127); $edit = [ "{$field_name}[0][value]" => $value, ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created'); $entity = EntityTest::load($id); $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved'); // Edit with missing required value. $value = ''; $edit = [ "{$field_name}[0][value]" => $value, ]; $this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save')); $this->assertRaw(t('@name field is required.', ['@name' => $this->field['label']]), 'Required field with no value fails validation'); } public function testFieldFormUnlimited() { $field_storage = $this->fieldStorageUnlimited; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name) ->save(); // Display creation form -> 1 widget. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed'); $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed'); // Check if aria-describedby attribute is placed on multiple value widgets. $elements = $this->xpath('//table[@id="field-unlimited-values" and @aria-describedby="edit-field-unlimited--description"]'); $this->assertTrue(isset($elements[0]), t('aria-describedby attribute is properly placed on multiple value widgets.')); // Press 'add more' button -> 2 widgets. $this->drupalPostForm(NULL, [], t('Add another item')); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed'); $this->assertFieldByName("{$field_name}[1][value]", '', 'New widget is displayed'); $this->assertNoField("{$field_name}[2][value]", 'No extraneous widget is displayed'); // TODO : check that non-field inputs are preserved ('title'), etc. // Yet another time so that we can play with more values -> 3 widgets. $this->drupalPostForm(NULL, [], t('Add another item')); // Prepare values and weights. $count = 3; $delta_range = $count - 1; $values = $weights = $pattern = $expected_values = []; $edit = []; for ($delta = 0; $delta <= $delta_range; $delta++) { // Assign unique random values and weights. do { $value = mt_rand(1, 127); } while (in_array($value, $values)); do { $weight = mt_rand(-$delta_range, $delta_range); } while (in_array($weight, $weights)); $edit["{$field_name}[$delta][value]"] = $value; $edit["{$field_name}[$delta][_weight]"] = $weight; // We'll need three slightly different formats to check the values. $values[$delta] = $value; $weights[$delta] = $weight; $field_values[$weight]['value'] = (string) $value; $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*"; } // Press 'add more' button -> 4 widgets $this->drupalPostForm(NULL, $edit, t('Add another item')); for ($delta = 0; $delta <= $delta_range; $delta++) { $this->assertFieldByName("{$field_name}[$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value"); $this->assertFieldByName("{$field_name}[$delta][_weight]", $weights[$delta], "Widget $delta has the right weight"); } ksort($pattern); $pattern = implode('.*', array_values($pattern)); $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order'); $this->assertFieldByName("{$field_name}[$delta][value]", '', "New widget is displayed"); $this->assertFieldByName("{$field_name}[$delta][_weight]", $delta, "New widget has the right weight"); $this->assertNoField("{$field_name}[" . ($delta + 1) . '][value]', 'No extraneous widget is displayed'); // Submit the form and create the entity. $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', ['@id' => $id]), 'Entity was created'); $entity = EntityTest::load($id); ksort($field_values); $field_values = array_values($field_values); $this->assertIdentical($entity->{$field_name}->getValue(), $field_values, 'Field values were saved in the correct order'); // Display edit form: check that the expected number of widgets is // displayed, with correct values change values, reorder, leave an empty // value in the middle. // Submit: check that the entity is updated with correct values // Re-submit: check that the field can be emptied. // Test with several multiple fields in a form } /** * Tests the position of the required label. */ public function testFieldFormUnlimitedRequired() { $field_name = $this->fieldStorageUnlimited['field_name']; $this->field['field_name'] = $field_name; $this->field['required'] = TRUE; FieldStorageConfig::create($this->fieldStorageUnlimited)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name) ->save(); // Display creation form -> 1 widget. $this->drupalGet('entity_test/add'); // Check that the Required symbol is present for the multifield label. $element = $this->xpath('//h4[contains(@class, "label") and contains(@class, "js-form-required") and contains(text(), :value)]', [':value' => $this->field['label']]); $this->assertTrue(isset($element[0]), 'Required symbol added field label.'); // Check that the label of the field input is visually hidden and contains // the field title and an indication of the delta for a11y. $element = $this->xpath('//label[@for=:for and contains(@class, "visually-hidden") and contains(text(), :value)]', [':for' => 'edit-field-unlimited-0-value', ':value' => $this->field['label'] . ' (value 1)']); $this->assertTrue(isset($element[0]), 'Required symbol not added for field input.'); } /** * Tests widget handling of multiple required radios. */ public function testFieldFormMultivalueWithRequiredRadio() { // Create a multivalue test field. $field_storage = $this->fieldStorageUnlimited; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name) ->save(); // Add a required radio field. FieldStorageConfig::create([ 'field_name' => 'required_radio_test', 'entity_type' => 'entity_test', 'type' => 'list_string', 'settings' => [ 'allowed_values' => ['yes' => 'yes', 'no' => 'no'], ], ])->save(); $field = [ 'field_name' => 'required_radio_test', 'entity_type' => 'entity_test', 'bundle' => 'entity_test', 'required' => TRUE, ]; FieldConfig::create($field)->save(); entity_get_form_display($field['entity_type'], $field['bundle'], 'default') ->setComponent($field['field_name'], [ 'type' => 'options_buttons', ]) ->save(); // Display creation form. $this->drupalGet('entity_test/add'); // Press the 'Add more' button. $this->drupalPostForm(NULL, [], t('Add another item')); // Verify that no error is thrown by the radio element. $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.'); // Verify that the widget is added. $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed'); $this->assertFieldByName("{$field_name}[1][value]", '', 'New widget is displayed'); $this->assertNoField("{$field_name}[2][value]", 'No extraneous widget is displayed'); } /** * Tests widgets handling multiple values. */ public function testFieldFormMultipleWidget() { // Create a field with fixed cardinality, configure the form to use a // "multiple" widget. $field_storage = $this->fieldStorageMultiple; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); $form = entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name, [ 'type' => 'test_field_widget_multiple', ]); $form->save(); $session = $this->assertSession(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName($field_name, '', 'Widget is displayed.'); // Create entity with three values. $edit = [ $field_name => '1, 2, 3', ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match); $id = $match[1]; // Check that the values were saved. $entity_init = EntityTest::load($id); $this->assertFieldValues($entity_init, $field_name, [1, 2, 3]); // Display the form, check that the values are correctly filled in. $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->assertFieldByName($field_name, '1, 2, 3', 'Widget is displayed.'); // Submit the form with more values than the field accepts. $edit = [$field_name => '1, 2, 3, 4, 5']; $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertRaw('this field cannot hold more than 4 values', 'Form validation failed.'); // Check that the field values were not submitted. $this->assertFieldValues($entity_init, $field_name, [1, 2, 3]); // Check that Attributes are rendered on the multivalue container if it is // a multiple widget form. $form->setComponent($field_name, [ 'type' => 'entity_reference_autocomplete', ]) ->save(); $this->drupalGet('entity_test/manage/' . $id . '/edit'); $name = str_replace('_', '-', $field_name); $session->responseContains('data-drupal-selector="edit-' . $name . '"'); } /** * Tests fields with no 'edit' access. */ public function testFieldFormAccess() { $entity_type = 'entity_test_rev'; // Create a "regular" field. $field_storage = $this->fieldStorageSingle; $field_storage['entity_type'] = $entity_type; $field_name = $field_storage['field_name']; $field = $this->field; $field['field_name'] = $field_name; $field['entity_type'] = $entity_type; $field['bundle'] = $entity_type; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($field)->save(); entity_get_form_display($entity_type, $entity_type, 'default') ->setComponent($field_name) ->save(); // Create a field with no edit access. See // field_test_entity_field_access(). $field_storage_no_access = [ 'field_name' => 'field_no_edit_access', 'entity_type' => $entity_type, 'type' => 'test_field', ]; $field_name_no_access = $field_storage_no_access['field_name']; $field_no_access = [ 'field_name' => $field_name_no_access, 'entity_type' => $entity_type, 'bundle' => $entity_type, 'default_value' => [0 => ['value' => 99]], ]; FieldStorageConfig::create($field_storage_no_access)->save(); FieldConfig::create($field_no_access)->save(); entity_get_form_display($field_no_access['entity_type'], $field_no_access['bundle'], 'default') ->setComponent($field_name_no_access) ->save(); // Test that the form structure includes full information for each delta // apart from #access. $entity = $this->container->get('entity_type.manager') ->getStorage($entity_type) ->create(['id' => 0, 'revision_id' => 0]); $display = entity_get_form_display($entity_type, $entity_type, 'default'); $form = []; $form_state = new FormState(); $display->buildForm($entity, $form, $form_state); $this->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.'); // Display creation form. $this->drupalGet($entity_type . '/add'); $this->assertNoFieldByName("{$field_name_no_access}[0][value]", '', 'Widget is not displayed if field access is denied.'); // Create entity. $edit = [ "{$field_name}[0][value]" => 1, ]; $this->drupalPostForm(NULL, $edit, t('Save')); preg_match("|$entity_type/manage/(\d+)|", $this->getUrl(), $match); $id = $match[1]; // Check that the default value was saved. $storage = $this->container->get('entity_type.manager') ->getStorage($entity_type); $entity = $storage->load($id); $this->assertEqual($entity->$field_name_no_access->value, 99, 'Default value was saved for the field with no edit access.'); $this->assertEqual($entity->$field_name->value, 1, 'Entered value vas saved for the field with edit access.'); // Create a new revision. $edit = [ "{$field_name}[0][value]" => 2, 'revision' => TRUE, ]; $this->drupalPostForm($entity_type . '/manage/' . $id . '/edit', $edit, t('Save')); // Check that the new revision has the expected values. $storage->resetCache([$id]); $entity = $storage->load($id); $this->assertEqual($entity->$field_name_no_access->value, 99, 'New revision has the expected value for the field with no edit access.'); $this->assertEqual($entity->$field_name->value, 2, 'New revision has the expected value for the field with edit access.'); // Check that the revision is also saved in the revisions table. $entity = $this->container->get('entity_type.manager') ->getStorage($entity_type) ->loadRevision($entity->getRevisionId()); $this->assertEqual($entity->$field_name_no_access->value, 99, 'New revision has the expected value for the field with no edit access.'); $this->assertEqual($entity->$field_name->value, 2, 'New revision has the expected value for the field with edit access.'); } /** * Tests hiding a field in a form. */ public function testHiddenField() { $entity_type = 'entity_test_rev'; $field_storage = $this->fieldStorageSingle; $field_storage['entity_type'] = $entity_type; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; $this->field['default_value'] = [0 => ['value' => 99]]; $this->field['entity_type'] = $entity_type; $this->field['bundle'] = $entity_type; FieldStorageConfig::create($field_storage)->save(); $this->field = FieldConfig::create($this->field); $this->field->save(); // We explicitly do not assign a widget in a form display, so the field // stays hidden in forms. // Display the entity creation form. $this->drupalGet($entity_type . '/add'); // Create an entity and test that the default value is assigned correctly to // the field that uses the hidden widget. $this->assertNoField("{$field_name}[0][value]", 'The field does not appear in the form'); $this->drupalPostForm(NULL, [], t('Save')); preg_match('|' . $entity_type . '/manage/(\d+)|', $this->getUrl(), $match); $id = $match[1]; $this->assertText(t('entity_test_rev @id has been created.', ['@id' => $id]), 'Entity was created'); $storage = $this->container->get('entity_type.manager') ->getStorage($entity_type); $entity = $storage->load($id); $this->assertEqual($entity->{$field_name}->value, 99, 'Default value was saved'); // Update the field to remove the default value, and switch to the default // widget. $this->field->setDefaultValue([]); $this->field->save(); entity_get_form_display($entity_type, $this->field->getTargetBundle(), 'default') ->setComponent($this->field->getName(), [ 'type' => 'test_field_widget', ]) ->save(); // Display edit form. $this->drupalGet($entity_type . '/manage/' . $id . '/edit'); $this->assertFieldByName("{$field_name}[0][value]", 99, 'Widget is displayed with the correct default value'); // Update the entity. $value = mt_rand(1, 127); $edit = ["{$field_name}[0][value]" => $value]; $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('entity_test_rev @id has been updated.', ['@id' => $id]), 'Entity was updated'); $storage->resetCache([$id]); $entity = $storage->load($id); $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated'); // Set the field back to hidden. entity_get_form_display($entity_type, $this->field->getTargetBundle(), 'default') ->removeComponent($this->field->getName()) ->save(); // Create a new revision. $edit = ['revision' => TRUE]; $this->drupalPostForm($entity_type . '/manage/' . $id . '/edit', $edit, t('Save')); // Check that the expected value has been carried over to the new revision. $storage->resetCache([$id]); $entity = $storage->load($id); $this->assertEqual($entity->{$field_name}->value, $value, 'New revision has the expected value for the field with the Hidden widget'); } /** * Tests the form display of the label for multi-value fields. */ public function testLabelOnMultiValueFields() { $user = $this->drupalCreateUser(['administer entity_test content']); $this->drupalLogin($user); FieldStorageConfig::create([ 'entity_type' => 'entity_test_base_field_display', 'field_name' => 'foo', 'type' => 'text', 'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED, ])->save(); FieldConfig::create([ 'entity_type' => 'entity_test_base_field_display', 'bundle' => 'bar', 'field_name' => 'foo', // Set a dangerous label to test XSS filtering. 'label' => "<script>alert('a configurable field');</script>", ])->save(); EntityFormDisplay::create([ 'targetEntityType' => 'entity_test_base_field_display', 'bundle' => 'bar', 'mode' => 'default', ])->setComponent('foo', ['type' => 'text_textfield'])->enable()->save(); $entity = EntityTestBaseFieldDisplay::create(['type' => 'bar']); $entity->save(); $this->drupalGet('entity_test_base_field_display/manage/' . $entity->id()); $this->assertResponse(200); $this->assertText('A field with multiple values'); // Test if labels were XSS filtered. $this->assertEscaped("<script>alert('a configurable field');</script>"); } /** * Tests hook_field_widget_multivalue_form_alter(). */ public function testFieldFormMultipleWidgetAlter() { $this->widgetAlterTest('hook_field_widget_multivalue_form_alter', 'test_field_widget_multiple'); } /** * Tests hook_field_widget_multivalue_form_alter() with single value elements. */ public function testFieldFormMultipleWidgetAlterSingleValues() { $this->widgetAlterTest('hook_field_widget_multivalue_form_alter', 'test_field_widget_multiple_single_value'); } /** * Tests hook_field_widget_multivalue_WIDGET_TYPE_form_alter(). */ public function testFieldFormMultipleWidgetTypeAlter() { $this->widgetAlterTest('hook_field_widget_multivalue_WIDGET_TYPE_form_alter', 'test_field_widget_multiple'); } /** * Tests hook_field_widget_multivalue_WIDGET_TYPE_form_alter() with single value elements. */ public function testFieldFormMultipleWidgetTypeAlterSingleValues() { $this->widgetAlterTest('hook_field_widget_multivalue_WIDGET_TYPE_form_alter', 'test_field_widget_multiple_single_value'); } /** * Tests widget alter hooks for a given hook name. */ protected function widgetAlterTest($hook, $widget) { // Create a field with fixed cardinality, configure the form to use a // "multiple" widget. $field_storage = $this->fieldStorageMultiple; $field_name = $field_storage['field_name']; $this->field['field_name'] = $field_name; FieldStorageConfig::create($field_storage)->save(); FieldConfig::create($this->field)->save(); // Set a flag in state so that the hook implementations will run. \Drupal::state()->set("field_test.widget_alter_test", [ 'hook' => $hook, 'field_name' => $field_name, 'widget' => $widget, ]); entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default') ->setComponent($field_name, [ 'type' => $widget, ]) ->save(); $this->drupalGet('entity_test/add'); $this->assertUniqueText("From $hook(): prefix on $field_name parent element."); if ($widget === 'test_field_widget_multiple_single_value') { $suffix_text = "From $hook(): suffix on $field_name child element."; $this->assertEqual($field_storage['cardinality'], substr_count($this->getTextContent(), $suffix_text), "'$suffix_text' was found {$field_storage['cardinality']} times using widget $widget"); } } }
wheelercreek/faithblog
core/modules/field/tests/src/Functional/FormTest.php
PHP
gpl-2.0
29,293
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "native_thread.cpp" #include "nsk_tools.cpp" #include "jni_tools.cpp" #include "jvmti_tools.cpp" #include "agent_tools.cpp" #include "jvmti_FollowRefObjects.cpp" #include "Injector.cpp" #include "JVMTITools.cpp" #include "agent_common.cpp" #include "framecnt002.cpp"
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jvmti/GetFrameCount/framecnt002/libframecnt002.cpp
C++
gpl-2.0
1,328
<?php namespace Drupal\yamlform; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ServiceProviderBase; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; /** * Service Provider for Yamlform. */ class YamlformServiceProvider extends ServiceProviderBase { /** * {@inheritdoc} */ public function alter(ContainerBuilder $container) { $modules = $container->getParameter('container.modules'); if (isset($modules['hal'])) { // Hal module is enabled, add our new normalizer for yamlform items. $service_definition = new Definition('Drupal\yamlform\Normalizer\YamlFormEntityReferenceItemNormalizer', [ new Reference('rest.link_manager'), new Reference('serializer.entity_resolver'), ]); // The priority must be higher than that of // serializer.normalizer.entity_reference_item.hal in // hal.services.yml. $service_definition->addTag('normalizer', ['priority' => 20]); $container->setDefinition('serializer.normalizer.yamlform_entity_reference_item', $service_definition); } } }
akorkot/copieubl
modules/yamlform/src/YamlformServiceProvider.php
PHP
gpl-2.0
1,163
/* * drivers/media/video/isp/omap_resizer.c * * Wrapper for Resizer module in TI's OMAP3430 ISP * * Copyright (C) 2008 Texas Instruments, Inc. * * Contributors: * Sergio Aguirre <saaguirre@ti.com> * Troy Laramy <t-laramy@ti.com> * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <linux/mutex.h> #include <linux/cdev.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/uaccess.h> #include <media/v4l2-dev.h> #include <asm/cacheflush.h> #include "isp.h" #include "ispmmu.h" #include "ispreg.h" #include "ispresizer.h" #include <linux/omap_resizer.h> #define OMAP_REZR_NAME "omap-resizer" /* Defines and Constants*/ #define MAX_CHANNELS 16 #define MAX_IMAGE_WIDTH 2047 #define MAX_IMAGE_WIDTH_HIGH 2047 #define ALIGNMENT 16 #define CHANNEL_BUSY 1 #define CHANNEL_FREE 0 #define PIXEL_EVEN 2 #define RATIO_MULTIPLIER 256 /* Bit position Macro */ /* macro for bit set and clear */ #define BITSET(variable, bit) ((variable) | (1 << bit)) #define BITRESET(variable, bit) ((variable) & ~(0x00000001 << (bit))) #define SET_BIT_INPUTRAM 28 #define SET_BIT_CBLIN 29 #define SET_BIT_INPTYP 27 #define SET_BIT_YCPOS 26 #define INPUT_RAM 1 #define UP_RSZ_RATIO 64 #define DOWN_RSZ_RATIO 512 #define UP_RSZ_RATIO1 513 #define DOWN_RSZ_RATIO1 1024 #define RSZ_IN_SIZE_VERT_SHIFT 16 #define MAX_HORZ_PIXEL_8BIT 31 #define MAX_HORZ_PIXEL_16BIT 15 #define NUM_PHASES 8 #define NUM_TAPS 4 #define NUM_D2PH 4 /* for downsampling * 2+x ~ 4x, * number of phases */ #define NUM_D2TAPS 7 /* for downsampling * 2+x ~ 4x, * number of taps */ #define ALIGN32 32 #define MAX_COEF_COUNTER 16 #define COEFF_ADDRESS_OFFSET 0x04 static DECLARE_MUTEX(resz_wrapper_mutex); /* Global structure which contains information about number of channels and protection variables */ struct device_params { unsigned char opened; /* state of the device */ struct completion compl_isr; /* Completion for interrupt */ struct mutex reszwrap_mutex; /* Semaphore for array */ struct videobuf_queue_ops vbq_ops; /* videobuf queue operations */ }; /* Register mapped structure which contains the every register information */ struct resizer_config { u32 rsz_pcr; /* pcr register mapping * variable. */ u32 rsz_in_start; /* in_start register mapping * variable. */ u32 rsz_in_size; /* in_size register mapping * variable. */ u32 rsz_out_size; /* out_size register mapping * variable. */ u32 rsz_cnt; /* rsz_cnt register mapping * variable. */ u32 rsz_sdr_inadd; /* sdr_inadd register mapping * variable. */ u32 rsz_sdr_inoff; /* sdr_inoff register mapping * variable. */ u32 rsz_sdr_outadd; /* sdr_outadd register mapping * variable. */ u32 rsz_sdr_outoff; /* sdr_outbuff register * mapping variable. */ u32 rsz_coeff_horz[16]; /* horizontal coefficients * mapping array. */ u32 rsz_coeff_vert[16]; /* vertical coefficients * mapping array. */ u32 rsz_yehn; /* yehn(luma)register mapping * variable. */ }; struct rsz_mult { int in_hsize; /* input frame horizontal * size. */ int in_vsize; /* input frame vertical size. */ int out_hsize; /* output frame horizontal * size. */ int out_vsize; /* output frame vertical * size. */ int in_pitch; /* offset between two rows of * input frame. */ int out_pitch; /* offset between two rows of * output frame. */ int end_hsize; int end_vsize; int num_htap; /* 0 = 7tap; 1 = 4tap */ int num_vtap; /* 0 = 7tap; 1 = 4tap */ int active; int inptyp; int vrsz; int hrsz; int hstph; /* for specifying horizontal * starting phase. */ int vstph; int pix_fmt; /* # defined, UYVY or YUYV. */ int cbilin; /* # defined, filter with luma * or bi-linear. */ u16 tap4filt_coeffs[32]; /* horizontal filter * coefficients. */ u16 tap7filt_coeffs[32]; /* vertical filter * coefficients. */ }; /* Channel specific structure contains information regarding the every channel */ struct channel_config { struct resizer_config register_config; /* Instance of register set * mapping structure */ int status; /* Specifies whether the * channel is busy or not */ struct mutex chanprotection_mutex; enum config_done config_state; u8 input_buf_index; u8 output_buf_index; }; /* per-filehandle data structure */ struct rsz_fh { struct rsz_params *params; struct channel_config *config; struct rsz_mult *multipass; /* Multipass to support * resizing ration outside * of 0.25x to 4x */ spinlock_t vbq_lock; /* spinlock for videobuf * queues. */ enum v4l2_buf_type type; struct videobuf_queue vbq; struct device_params *device; dma_addr_t isp_addr_read; /* Input/Output address */ dma_addr_t isp_addr_write; /* Input/Output address */ u32 rsz_bufsize; /* channel specific buffersize */ }; static struct device_params *device_config; static struct device *rsz_device; static int rsz_major = -1; /* functions declaration */ static void rsz_hardware_setup(struct channel_config *rsz_conf_chan); static int rsz_set_params(struct rsz_mult *multipass, struct rsz_params *, struct channel_config *); static int rsz_get_params(struct rsz_params *, struct channel_config *); static void rsz_copy_data(struct rsz_mult *multipass, struct rsz_params *params); static void rsz_isr(unsigned long status, isp_vbq_callback_ptr arg1, void *arg2); static void rsz_calculate_crop(struct channel_config *rsz_conf_chan, struct rsz_cropsize *cropsize); static int rsz_set_multipass(struct rsz_mult *multipass, struct channel_config *rsz_conf_chan); static int rsz_set_ratio(struct rsz_mult *multipass, struct channel_config *rsz_conf_chan); static void rsz_config_ratio(struct rsz_mult *multipass, struct channel_config *rsz_conf_chan); /** * rsz_hardware_setup - Sets hardware configuration registers * @rsz_conf_chan: Structure containing channel configuration * * Set hardware configuration registers **/ static void rsz_hardware_setup(struct channel_config *rsz_conf_chan) { int coeffcounter; int coeffoffset = 0; down(&resz_wrapper_mutex); omap_writel(rsz_conf_chan->register_config.rsz_cnt, ISPRSZ_CNT); omap_writel(rsz_conf_chan->register_config.rsz_in_start, ISPRSZ_IN_START); omap_writel(rsz_conf_chan->register_config.rsz_in_size, ISPRSZ_IN_SIZE); omap_writel(rsz_conf_chan->register_config.rsz_out_size, ISPRSZ_OUT_SIZE); omap_writel(rsz_conf_chan->register_config.rsz_sdr_inadd, ISPRSZ_SDR_INADD); omap_writel(rsz_conf_chan->register_config.rsz_sdr_inoff, ISPRSZ_SDR_INOFF); omap_writel(rsz_conf_chan->register_config.rsz_sdr_outadd, ISPRSZ_SDR_OUTADD); omap_writel(rsz_conf_chan->register_config.rsz_sdr_outoff, ISPRSZ_SDR_OUTOFF); omap_writel(rsz_conf_chan->register_config.rsz_yehn, ISPRSZ_YENH); for (coeffcounter = 0; coeffcounter < MAX_COEF_COUNTER; coeffcounter++) { omap_writel(rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter], ISPRSZ_HFILT10 + coeffoffset); omap_writel(rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter], ISPRSZ_VFILT10 + coeffoffset); coeffoffset = coeffoffset + COEFF_ADDRESS_OFFSET; } up(&resz_wrapper_mutex); } /** * rsz_start - Enables Resizer Wrapper * @arg: Currently not used. * @device: Structure containing ISP resizer wrapper global information * * Submits a resizing task specified by the rsz_resize structure. The call can * either be blocked until the task is completed or returned immediately based * on the value of the blocking argument in the rsz_resize structure. If it is * blocking, the status of the task can be checked by calling ioctl * RSZ_G_STATUS. Only one task can be outstanding for each logical channel. * * Returns 0 if successful, or -EINVAL if could not set callback for RSZR IRQ * event or the state of the channel is not configured. **/ int rsz_start(int *arg, struct rsz_fh *fh) { struct channel_config *rsz_conf_chan = fh->config; struct rsz_mult *multipass = fh->multipass; struct videobuf_queue *q = &fh->vbq; int ret; if (rsz_conf_chan->config_state) { dev_err(rsz_device, "State not configured \n"); goto err_einval; } rsz_conf_chan->status = CHANNEL_BUSY; rsz_hardware_setup(rsz_conf_chan); if (isp_set_callback(CBK_RESZ_DONE, rsz_isr, (void *) NULL, (void *)NULL)) { dev_err(rsz_device, "No callback for RSZR\n"); goto err_einval; } mult: device_config->compl_isr.done = 0; ispresizer_enable(1); ret = wait_for_completion_interruptible(&device_config->compl_isr); if (ret != 0) { dev_dbg(rsz_device, "Unexpected exit from " "wait_for_completion_interruptible\n"); wait_for_completion(&device_config->compl_isr); } if (multipass->active) { rsz_set_multipass(multipass, rsz_conf_chan); goto mult; } if (fh->isp_addr_read) { ispmmu_unmap(fh->isp_addr_read); fh->isp_addr_read = 0; } if (fh->isp_addr_write) { ispmmu_unmap(fh->isp_addr_write); fh->isp_addr_write = 0; } rsz_conf_chan->status = CHANNEL_FREE; q->bufs[rsz_conf_chan->input_buf_index]->state = VIDEOBUF_NEEDS_INIT; q->bufs[rsz_conf_chan->output_buf_index]->state = VIDEOBUF_NEEDS_INIT; rsz_conf_chan->register_config.rsz_sdr_outadd = 0; rsz_conf_chan->register_config.rsz_sdr_inadd = 0; /* Unmap and free the DMA memory allocated for buffers */ videobuf_dma_unmap(q, videobuf_to_dma( q->bufs[rsz_conf_chan->input_buf_index])); videobuf_dma_unmap(q, videobuf_to_dma( q->bufs[rsz_conf_chan->output_buf_index])); videobuf_dma_free(videobuf_to_dma( q->bufs[rsz_conf_chan->input_buf_index])); videobuf_dma_free(videobuf_to_dma( q->bufs[rsz_conf_chan->output_buf_index])); isp_unset_callback(CBK_RESZ_DONE); return 0; err_einval: return -EINVAL; } /** * rsz_set_multipass - Set resizer multipass * @rsz_conf_chan: Structure containing channel configuration * * Returns always 0 **/ static int rsz_set_multipass(struct rsz_mult *multipass, struct channel_config *rsz_conf_chan) { multipass->in_hsize = multipass->out_hsize; multipass->in_vsize = multipass->out_vsize; multipass->out_hsize = multipass->end_hsize; multipass->out_vsize = multipass->end_vsize; multipass->out_pitch = (multipass->inptyp ? multipass->out_hsize : (multipass->out_hsize * 2)); multipass->in_pitch = (multipass->inptyp ? multipass->in_hsize : (multipass->in_hsize * 2)); rsz_set_ratio(multipass, rsz_conf_chan); rsz_config_ratio(multipass, rsz_conf_chan); rsz_hardware_setup(rsz_conf_chan); return 0; } /** * rsz_copy_data - Copy data * @params: Structure containing the Resizer Wrapper parameters * * Copy data **/ static void rsz_copy_data(struct rsz_mult *multipass, struct rsz_params *params) { int i; multipass->in_hsize = params->in_hsize; multipass->in_vsize = params->in_vsize; multipass->out_hsize = params->out_hsize; multipass->out_vsize = params->out_vsize; multipass->end_hsize = params->out_hsize; multipass->end_vsize = params->out_vsize; multipass->in_pitch = params->in_pitch; multipass->out_pitch = params->out_pitch; multipass->hstph = params->hstph; multipass->vstph = params->vstph; multipass->inptyp = params->inptyp; multipass->pix_fmt = params->pix_fmt; multipass->cbilin = params->cbilin; for (i = 0; i < 32; i++) { multipass->tap4filt_coeffs[i] = params->tap4filt_coeffs[i]; multipass->tap7filt_coeffs[i] = params->tap7filt_coeffs[i]; } } /** * rsz_set_params - Set parameters for resizer wrapper * @params: Structure containing the Resizer Wrapper parameters * @rsz_conf_chan: Structure containing channel configuration * * Used to set the parameters of the Resizer hardware, including input and * output image size, horizontal and vertical poly-phase filter coefficients, * luma enchancement filter coefficients, etc. **/ static int rsz_set_params(struct rsz_mult *multipass, struct rsz_params *params, struct channel_config *rsz_conf_chan) { int mul = 1; if ((params->yenh_params.type < 0) || (params->yenh_params.type > 2)) { dev_err(rsz_device, "rsz_set_params: Wrong yenh type\n"); return -EINVAL; } if ((params->in_vsize <= 0) || (params->in_hsize <= 0) || (params->out_vsize <= 0) || (params->out_hsize <= 0) || (params->in_pitch <= 0) || (params->out_pitch <= 0)) { dev_err(rsz_device, "rsz_set_params: Invalid size params\n"); return -EINVAL; } if ((params->inptyp != RSZ_INTYPE_YCBCR422_16BIT) && (params->inptyp != RSZ_INTYPE_PLANAR_8BIT)) { dev_err(rsz_device, "rsz_set_params: Invalid input type\n"); return -EINVAL; } if ((params->pix_fmt != RSZ_PIX_FMT_UYVY) && (params->pix_fmt != RSZ_PIX_FMT_YUYV)) { dev_err(rsz_device, "rsz_set_params: Invalid pixel format\n"); return -EINVAL; } if (params->inptyp == RSZ_INTYPE_YCBCR422_16BIT) mul = 2; else mul = 1; if (params->in_pitch < (params->in_hsize * mul)) { dev_err(rsz_device, "rsz_set_params: Pitch is incorrect\n"); return -EINVAL; } if (params->out_pitch < (params->out_hsize * mul)) { dev_err(rsz_device, "rsz_set_params: Out pitch cannot be less" " than out hsize\n"); return -EINVAL; } /* Output H size should be even */ if ((params->out_hsize % PIXEL_EVEN) != 0) { dev_err(rsz_device, "rsz_set_params: Output H size should" " be even\n"); return -EINVAL; } if (params->horz_starting_pixel < 0) { dev_err(rsz_device, "rsz_set_params: Horz start pixel cannot" " be less than zero\n"); return -EINVAL; } rsz_copy_data(multipass, params); if (0 != rsz_set_ratio(multipass, rsz_conf_chan)) goto err_einval; if (params->yenh_params.type) { if ((multipass->num_htap && multipass->out_hsize > 1280) || (!multipass->num_htap && multipass->out_hsize > 640)) goto err_einval; } if (INPUT_RAM) params->vert_starting_pixel = 0; rsz_conf_chan->register_config.rsz_in_start = (params->vert_starting_pixel << ISPRSZ_IN_SIZE_VERT_SHIFT) & ISPRSZ_IN_SIZE_VERT_MASK; if (params->inptyp == RSZ_INTYPE_PLANAR_8BIT) { if (params->horz_starting_pixel > MAX_HORZ_PIXEL_8BIT) goto err_einval; } if (params->inptyp == RSZ_INTYPE_YCBCR422_16BIT) { if (params->horz_starting_pixel > MAX_HORZ_PIXEL_16BIT) goto err_einval; } rsz_conf_chan->register_config.rsz_in_start |= params->horz_starting_pixel & ISPRSZ_IN_START_HORZ_ST_MASK; rsz_conf_chan->register_config.rsz_yehn = (params->yenh_params.type << ISPRSZ_YENH_ALGO_SHIFT) & ISPRSZ_YENH_ALGO_MASK; if (params->yenh_params.type) { rsz_conf_chan->register_config.rsz_yehn |= params->yenh_params.core & ISPRSZ_YENH_CORE_MASK; rsz_conf_chan->register_config.rsz_yehn |= (params->yenh_params.gain << ISPRSZ_YENH_GAIN_SHIFT) & ISPRSZ_YENH_GAIN_MASK; rsz_conf_chan->register_config.rsz_yehn |= (params->yenh_params.slop << ISPRSZ_YENH_SLOP_SHIFT) & ISPRSZ_YENH_SLOP_MASK; } rsz_config_ratio(multipass, rsz_conf_chan); rsz_conf_chan->config_state = STATE_CONFIGURED; return 0; err_einval: return -EINVAL; } /** * rsz_set_ratio - Set ratio * @rsz_conf_chan: Structure containing channel configuration * * Returns 0 if successful, -EINVAL if invalid output size, upscaling ratio is * being requested, or other ratio configuration value is out of bounds **/ static int rsz_set_ratio(struct rsz_mult *multipass, struct channel_config *rsz_conf_chan) { int alignment = 0; rsz_conf_chan->register_config.rsz_cnt = 0; if ((multipass->out_hsize > MAX_IMAGE_WIDTH) || (multipass->out_vsize > MAX_IMAGE_WIDTH)) { dev_err(rsz_device, "Invalid output size!"); goto err_einval; } if (multipass->cbilin) { rsz_conf_chan->register_config.rsz_cnt = BITSET(rsz_conf_chan->register_config.rsz_cnt, SET_BIT_CBLIN); } if (INPUT_RAM) { rsz_conf_chan->register_config.rsz_cnt = BITSET(rsz_conf_chan->register_config.rsz_cnt, SET_BIT_INPUTRAM); } if (multipass->inptyp == RSZ_INTYPE_PLANAR_8BIT) { rsz_conf_chan->register_config.rsz_cnt = BITSET(rsz_conf_chan->register_config.rsz_cnt, SET_BIT_INPTYP); } else { rsz_conf_chan->register_config.rsz_cnt = BITRESET(rsz_conf_chan->register_config. rsz_cnt, SET_BIT_INPTYP); if (multipass->pix_fmt == RSZ_PIX_FMT_UYVY) { rsz_conf_chan->register_config.rsz_cnt = BITRESET(rsz_conf_chan->register_config. rsz_cnt, SET_BIT_YCPOS); } else if (multipass->pix_fmt == RSZ_PIX_FMT_YUYV) { rsz_conf_chan->register_config.rsz_cnt = BITSET(rsz_conf_chan->register_config. rsz_cnt, SET_BIT_YCPOS); } } multipass->vrsz = (multipass->in_vsize * RATIO_MULTIPLIER) / multipass->out_vsize; multipass->hrsz = (multipass->in_hsize * RATIO_MULTIPLIER) / multipass->out_hsize; if (UP_RSZ_RATIO > multipass->vrsz || UP_RSZ_RATIO > multipass->hrsz) { dev_err(rsz_device, "Upscaling ratio not supported!"); goto err_einval; } multipass->vrsz = (multipass->in_vsize - NUM_D2TAPS) * RATIO_MULTIPLIER / (multipass->out_vsize - 1); multipass->hrsz = ((multipass->in_hsize - NUM_D2TAPS) * RATIO_MULTIPLIER) / (multipass->out_hsize - 1); if (multipass->hrsz <= 512) { multipass->hrsz = (multipass->in_hsize - NUM_TAPS) * RATIO_MULTIPLIER / (multipass->out_hsize - 1); if (multipass->hrsz < 64) multipass->hrsz = 64; if (multipass->hrsz > 512) multipass->hrsz = 512; if (multipass->hstph > NUM_PHASES) goto err_einval; multipass->num_htap = 1; } else if (multipass->hrsz >= 513 && multipass->hrsz <= 1024) { if (multipass->hstph > NUM_D2PH) goto err_einval; multipass->num_htap = 0; } if (multipass->vrsz <= 512) { multipass->vrsz = (multipass->in_vsize - NUM_TAPS) * RATIO_MULTIPLIER / (multipass->out_vsize - 1); if (multipass->vrsz < 64) multipass->vrsz = 64; if (multipass->vrsz > 512) multipass->vrsz = 512; if (multipass->vstph > NUM_PHASES) goto err_einval; multipass->num_vtap = 1; } else if (multipass->vrsz >= 513 && multipass->vrsz <= 1024) { if (multipass->vstph > NUM_D2PH) goto err_einval; multipass->num_vtap = 0; } if ((multipass->in_pitch) % ALIGN32) { dev_err(rsz_device, "Invalid input pitch: %d \n", multipass->in_pitch); goto err_einval; } if ((multipass->out_pitch) % ALIGN32) { dev_err(rsz_device, "Invalid output pitch %d \n", multipass->out_pitch); goto err_einval; } if (multipass->vrsz < 256 && (multipass->in_vsize < multipass->out_vsize)) { if (multipass->inptyp == RSZ_INTYPE_PLANAR_8BIT) alignment = ALIGNMENT; else if (multipass->inptyp == RSZ_INTYPE_YCBCR422_16BIT) alignment = (ALIGNMENT / 2); else dev_err(rsz_device, "Invalid input type\n"); if (!(((multipass->out_hsize % PIXEL_EVEN) == 0) && (multipass->out_hsize % alignment) == 0)) { dev_err(rsz_device, "wrong hsize\n"); goto err_einval; } } if (multipass->hrsz >= 64 && multipass->hrsz <= 1024) { if (multipass->out_hsize > MAX_IMAGE_WIDTH) { dev_err(rsz_device, "wrong width\n"); goto err_einval; } multipass->active = 0; } else if (multipass->hrsz > 1024) { if (multipass->out_hsize > MAX_IMAGE_WIDTH) { dev_err(rsz_device, "wrong width\n"); goto err_einval; } if (multipass->hstph > NUM_D2PH) goto err_einval; multipass->num_htap = 0; multipass->out_hsize = multipass->in_hsize * 256 / 1024; if (multipass->out_hsize % ALIGN32) { multipass->out_hsize += abs((multipass->out_hsize % ALIGN32) - ALIGN32); } multipass->out_pitch = ((multipass->inptyp) ? multipass->out_hsize : (multipass->out_hsize * 2)); multipass->hrsz = ((multipass->in_hsize - NUM_D2TAPS) * RATIO_MULTIPLIER) / (multipass->out_hsize - 1); multipass->active = 1; } if (multipass->vrsz > 1024) { if (multipass->out_vsize > MAX_IMAGE_WIDTH_HIGH) { dev_err(rsz_device, "wrong width\n"); goto err_einval; } multipass->out_vsize = multipass->in_vsize * 256 / 1024; multipass->vrsz = ((multipass->in_vsize - NUM_D2TAPS) * RATIO_MULTIPLIER) / (multipass->out_vsize - 1); multipass->active = 1; multipass->num_vtap = 0; } rsz_conf_chan->register_config.rsz_out_size = multipass->out_hsize & ISPRSZ_OUT_SIZE_HORZ_MASK; rsz_conf_chan->register_config.rsz_out_size |= (multipass->out_vsize << ISPRSZ_OUT_SIZE_VERT_SHIFT) & ISPRSZ_OUT_SIZE_VERT_MASK; rsz_conf_chan->register_config.rsz_sdr_inoff = multipass->in_pitch & ISPRSZ_SDR_INOFF_OFFSET_MASK; rsz_conf_chan->register_config.rsz_sdr_outoff = multipass->out_pitch & ISPRSZ_SDR_OUTOFF_OFFSET_MASK; if (multipass->hrsz >= 64 && multipass->hrsz <= 512) { if (multipass->hstph > NUM_PHASES) goto err_einval; } else if (multipass->hrsz >= 64 && multipass->hrsz <= 512) { if (multipass->hstph > NUM_D2PH) goto err_einval; } rsz_conf_chan->register_config.rsz_cnt |= (multipass->hstph << ISPRSZ_CNT_HSTPH_SHIFT) & ISPRSZ_CNT_HSTPH_MASK; if (multipass->vrsz >= 64 && multipass->hrsz <= 512) { if (multipass->vstph > NUM_PHASES) goto err_einval; } else if (multipass->vrsz >= 64 && multipass->vrsz <= 512) { if (multipass->vstph > NUM_D2PH) goto err_einval; } rsz_conf_chan->register_config.rsz_cnt |= (multipass->vstph << ISPRSZ_CNT_VSTPH_SHIFT) & ISPRSZ_CNT_VSTPH_MASK; rsz_conf_chan->register_config.rsz_cnt |= (multipass->hrsz - 1) & ISPRSZ_CNT_HRSZ_MASK; rsz_conf_chan->register_config.rsz_cnt |= ((multipass->vrsz - 1) << ISPRSZ_CNT_VRSZ_SHIFT) & ISPRSZ_CNT_VRSZ_MASK; return 0; err_einval: return -EINVAL; } /** * rsz_config_ratio - Configure ratio * @rsz_conf_chan: Structure containing channel configuration * * Configure ratio **/ static void rsz_config_ratio(struct rsz_mult *multipass, struct channel_config *rsz_conf_chan) { int hsize; int vsize; int coeffcounter; if (multipass->hrsz <= 512) { hsize = ((32 * multipass->hstph + (multipass->out_hsize - 1) * multipass->hrsz + 16) >> 8) + 7; } else { hsize = ((64 * multipass->hstph + (multipass->out_hsize - 1) * multipass->hrsz + 32) >> 8) + 7; } if (multipass->vrsz <= 512) { vsize = ((32 * multipass->vstph + (multipass->out_vsize - 1) * multipass->vrsz + 16) >> 8) + 4; } else { vsize = ((64 * multipass->vstph + (multipass->out_vsize - 1) * multipass->vrsz + 32) >> 8) + 7; } rsz_conf_chan->register_config.rsz_in_size = hsize; rsz_conf_chan->register_config.rsz_in_size |= ((vsize << ISPRSZ_IN_SIZE_VERT_SHIFT) & ISPRSZ_IN_SIZE_VERT_MASK); for (coeffcounter = 0; coeffcounter < MAX_COEF_COUNTER; coeffcounter++) { if (multipass->num_htap) { rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter] = (multipass->tap4filt_coeffs[2 * coeffcounter] & ISPRSZ_HFILT10_COEF0_MASK); rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter] |= ((multipass->tap4filt_coeffs[2 * coeffcounter + 1] << ISPRSZ_HFILT10_COEF1_SHIFT) & ISPRSZ_HFILT10_COEF1_MASK); } else { rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter] = (multipass->tap7filt_coeffs[2 * coeffcounter] & ISPRSZ_HFILT10_COEF0_MASK); rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter] |= ((multipass->tap7filt_coeffs[2 * coeffcounter + 1] << ISPRSZ_HFILT10_COEF1_SHIFT) & ISPRSZ_HFILT10_COEF1_MASK); } if (multipass->num_vtap) { rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter] = (multipass->tap4filt_coeffs[2 * coeffcounter] & ISPRSZ_VFILT10_COEF0_MASK); rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter] |= ((multipass->tap4filt_coeffs[2 * coeffcounter + 1] << ISPRSZ_VFILT10_COEF1_SHIFT) & ISPRSZ_VFILT10_COEF1_MASK); } else { rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter] = (multipass->tap7filt_coeffs[2 * coeffcounter] & ISPRSZ_VFILT10_COEF0_MASK); rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter] |= ((multipass->tap7filt_coeffs[2 * coeffcounter + 1] << ISPRSZ_VFILT10_COEF1_SHIFT) & ISPRSZ_VFILT10_COEF1_MASK); } } } /** * rsz_get_params - Gets the parameter values * @params: Structure containing the Resizer Wrapper parameters * @rsz_conf_chan: Structure containing channel configuration * * Used to get the Resizer hardware settings associated with the * current logical channel represented by fd. **/ static int rsz_get_params(struct rsz_params *params, struct channel_config *rsz_conf_chan) { int coeffcounter; if (rsz_conf_chan->config_state) { dev_err(rsz_device, "state not configured\n"); return -EINVAL; } params->in_hsize = rsz_conf_chan->register_config.rsz_in_size & ISPRSZ_IN_SIZE_HORZ_MASK; params->in_vsize = (rsz_conf_chan->register_config.rsz_in_size & ISPRSZ_IN_SIZE_VERT_MASK) >> ISPRSZ_IN_SIZE_VERT_SHIFT; params->in_pitch = rsz_conf_chan->register_config.rsz_sdr_inoff & ISPRSZ_SDR_INOFF_OFFSET_MASK; params->out_hsize = rsz_conf_chan->register_config.rsz_out_size & ISPRSZ_OUT_SIZE_HORZ_MASK; params->out_vsize = (rsz_conf_chan->register_config.rsz_out_size & ISPRSZ_OUT_SIZE_VERT_MASK) >> ISPRSZ_OUT_SIZE_VERT_SHIFT; params->out_pitch = rsz_conf_chan->register_config.rsz_sdr_outoff & ISPRSZ_SDR_OUTOFF_OFFSET_MASK; params->cbilin = (rsz_conf_chan->register_config.rsz_cnt & SET_BIT_CBLIN) >> SET_BIT_CBLIN; params->inptyp = (rsz_conf_chan->register_config.rsz_cnt & ISPRSZ_CNT_INPTYP_MASK) >> SET_BIT_INPTYP; params->horz_starting_pixel = ((rsz_conf_chan->register_config. rsz_in_start & ISPRSZ_IN_START_HORZ_ST_MASK)); params->vert_starting_pixel = ((rsz_conf_chan->register_config. rsz_in_start & ISPRSZ_IN_START_VERT_ST_MASK) >> ISPRSZ_IN_START_VERT_ST_SHIFT); params->hstph = ((rsz_conf_chan->register_config.rsz_cnt & ISPRSZ_CNT_HSTPH_MASK >> ISPRSZ_CNT_HSTPH_SHIFT)); params->vstph = ((rsz_conf_chan->register_config.rsz_cnt & ISPRSZ_CNT_VSTPH_MASK >> ISPRSZ_CNT_VSTPH_SHIFT)); for (coeffcounter = 0; coeffcounter < MAX_COEF_COUNTER; coeffcounter++) { params->tap4filt_coeffs[2 * coeffcounter] = rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter] & ISPRSZ_HFILT10_COEF0_MASK; params->tap4filt_coeffs[2 * coeffcounter + 1] = (rsz_conf_chan->register_config. rsz_coeff_horz[coeffcounter] & ISPRSZ_HFILT10_COEF1_MASK) >> ISPRSZ_HFILT10_COEF1_SHIFT; params->tap7filt_coeffs[2 * coeffcounter] = rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter] & ISPRSZ_VFILT10_COEF0_MASK; params->tap7filt_coeffs[2 * coeffcounter + 1] = (rsz_conf_chan->register_config. rsz_coeff_vert[coeffcounter] & ISPRSZ_VFILT10_COEF1_MASK) >> ISPRSZ_VFILT10_COEF1_SHIFT; } params->yenh_params.type = (rsz_conf_chan->register_config.rsz_yehn & ISPRSZ_YENH_ALGO_MASK) >> ISPRSZ_YENH_ALGO_SHIFT; params->yenh_params.core = rsz_conf_chan->register_config.rsz_yehn & ISPRSZ_YENH_CORE_MASK; params->yenh_params.gain = (rsz_conf_chan->register_config.rsz_yehn & ISPRSZ_YENH_GAIN_MASK) >> ISPRSZ_YENH_GAIN_SHIFT; params->yenh_params.slop = (rsz_conf_chan->register_config.rsz_yehn & ISPRSZ_YENH_SLOP_MASK) >> ISPRSZ_YENH_SLOP_SHIFT; params->pix_fmt = ((rsz_conf_chan->register_config.rsz_cnt & ISPRSZ_CNT_PIXFMT_MASK) >> SET_BIT_YCPOS); if (params->pix_fmt) params->pix_fmt = RSZ_PIX_FMT_UYVY; else params->pix_fmt = RSZ_PIX_FMT_YUYV; return 0; } /** * rsz_calculate_crop - Calculate Crop values * @rsz_conf_chan: Structure containing channel configuration * @cropsize: Structure containing crop parameters * * Calculate Crop values **/ static void rsz_calculate_crop(struct channel_config *rsz_conf_chan, struct rsz_cropsize *cropsize) { int luma_enable; cropsize->hcrop = 0; cropsize->vcrop = 0; luma_enable = (rsz_conf_chan->register_config.rsz_yehn & ISPRSZ_YENH_ALGO_MASK) >> ISPRSZ_YENH_ALGO_SHIFT; if (luma_enable) cropsize->hcrop += 2; } /** * rsz_vbq_release - Videobuffer queue release * @q: Structure containing the videobuffer queue file handle, and device * structure which contains the actual configuration. * @vb: Structure containing the videobuffer used for resizer processing. **/ static void rsz_vbq_release(struct videobuf_queue *q, struct videobuf_buffer *vb) { int i; struct rsz_fh *fh = q->priv_data; for (i = 0; i < VIDEO_MAX_FRAME; i++) { struct videobuf_dmabuf *dma = NULL; if (!q->bufs[i]) continue; if (q->bufs[i]->memory != V4L2_MEMORY_MMAP) continue; dma = videobuf_to_dma(q->bufs[i]); videobuf_dma_unmap(q, dma); videobuf_dma_free(dma); } ispmmu_unmap(fh->isp_addr_read); ispmmu_unmap(fh->isp_addr_write); fh->isp_addr_read = 0; fh->isp_addr_write = 0; spin_lock(&fh->vbq_lock); vb->state = VIDEOBUF_NEEDS_INIT; spin_unlock(&fh->vbq_lock); } /** * rsz_vbq_setup - Sets up the videobuffer size and validates count. * @q: Structure containing the videobuffer queue file handle, and device * structure which contains the actual configuration. * @cnt: Number of buffers requested * @size: Size in bytes of the buffer used for previewing * * Always returns 0. **/ static int rsz_vbq_setup(struct videobuf_queue *q, unsigned int *cnt, unsigned int *size) { struct rsz_fh *fh = q->priv_data; struct rsz_mult *multipass = fh->multipass; u32 insize, outsize; spin_lock(&fh->vbq_lock); if (*cnt <= 0) *cnt = VIDEO_MAX_FRAME; if (*cnt > VIDEO_MAX_FRAME) *cnt = VIDEO_MAX_FRAME; outsize = multipass->out_pitch * multipass->out_vsize; insize = multipass->in_pitch * multipass->in_vsize; if (*cnt == 1 && (outsize > insize)) { dev_err(rsz_device, "2 buffers are required for Upscaling " "mode\n"); goto err_einval; } if (!fh->params->in_hsize || !fh->params->in_vsize) { dev_err(rsz_device, "Can't setup buffer size\n"); goto err_einval; } else { if (outsize > insize) *size = outsize; else *size = insize; fh->rsz_bufsize = *size; } spin_unlock(&fh->vbq_lock); return 0; err_einval: spin_unlock(&fh->vbq_lock); return -EINVAL; } /** * rsz_vbq_prepare - Videobuffer is prepared and mmapped. * @q: Structure containing the videobuffer queue file handle, and device * structure which contains the actual configuration. * @vb: Structure containing the videobuffer used for resizer processing. * @field: Type of field to set in videobuffer device. * * Returns 0 if successful, or -EINVAL if buffer couldn't get allocated, or * -EIO if the ISP MMU mapping fails **/ static int rsz_vbq_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb, enum v4l2_field field) { struct rsz_fh *fh = q->priv_data; struct channel_config *rsz_conf_chan = fh->config; struct rsz_mult *multipass = fh->multipass; int err = 0; unsigned int isp_addr, insize, outsize; struct videobuf_dmabuf *dma = videobuf_to_dma(vb); spin_lock(&fh->vbq_lock); if (vb->baddr) { vb->size = fh->rsz_bufsize; vb->bsize = fh->rsz_bufsize; } else { spin_unlock(&fh->vbq_lock); dev_err(rsz_device, "No user buffer allocated\n"); goto out; } if (vb->i) { vb->width = fh->params->out_hsize; vb->height = fh->params->out_vsize; } else { vb->width = fh->params->in_hsize; vb->height = fh->params->in_vsize; } vb->field = field; spin_unlock(&fh->vbq_lock); if (vb->state == VIDEOBUF_NEEDS_INIT) { err = videobuf_iolock(q, vb, NULL); if (!err) { isp_addr = ispmmu_map_sg(dma->sglist, dma->sglen); if (!isp_addr) err = -EIO; else { if (vb->i) { rsz_conf_chan->register_config. rsz_sdr_outadd = isp_addr; fh->isp_addr_write = isp_addr; rsz_conf_chan->output_buf_index = vb->i; } else { rsz_conf_chan->register_config. rsz_sdr_inadd = isp_addr; rsz_conf_chan->input_buf_index = vb->i; outsize = multipass->out_pitch * multipass->out_vsize; insize = multipass->in_pitch * multipass->in_vsize; if (outsize < insize) { rsz_conf_chan->register_config. rsz_sdr_outadd = isp_addr; rsz_conf_chan-> output_buf_index = vb->i; } fh->isp_addr_read = isp_addr; } } } } if (!err) { spin_lock(&fh->vbq_lock); vb->state = VIDEOBUF_PREPARED; spin_unlock(&fh->vbq_lock); flush_cache_user_range(NULL, vb->baddr, (vb->baddr + vb->bsize)); } else rsz_vbq_release(q, vb); out: return err; } static void rsz_vbq_queue(struct videobuf_queue *q, struct videobuf_buffer *vb) { return; } /** * rsz_open - Initializes and opens the Resizer Wrapper * @inode: Inode structure associated with the Resizer Wrapper * @filp: File structure associated with the Resizer Wrapper * * Returns 0 if successful, -EBUSY if its already opened or the ISP module is * not available, or -ENOMEM if its unable to allocate the device in kernel * space memory. **/ static int rsz_open(struct inode *inode, struct file *filp) { int ret = 0; struct channel_config *rsz_conf_chan; struct rsz_fh *fh; struct device_params *device = device_config; struct rsz_params *params; struct rsz_mult *multipass; if ((filp->f_flags & O_NONBLOCK) == O_NONBLOCK) { printk(KERN_DEBUG "omap-resizer: Device is opened in " "non blocking mode\n"); } else { printk(KERN_DEBUG "omap-resizer: Device is opened in blocking " "mode\n"); } fh = kzalloc(sizeof(struct rsz_fh), GFP_KERNEL); if (NULL == fh) return -ENOMEM; isp_get(); rsz_conf_chan = kzalloc(sizeof(struct channel_config), GFP_KERNEL); if (rsz_conf_chan == NULL) { dev_err(rsz_device, "\n cannot allocate memory to config"); ret = -ENOMEM; goto err_enomem0; } params = kzalloc(sizeof(struct rsz_params), GFP_KERNEL); if (params == NULL) { dev_err(rsz_device, "\n cannot allocate memory to params"); ret = -ENOMEM; goto err_enomem1; } multipass = kzalloc(sizeof(struct rsz_mult), GFP_KERNEL); if (multipass == NULL) { dev_err(rsz_device, "\n cannot allocate memory to multipass"); ret = -ENOMEM; goto err_enomem2; } fh->multipass = multipass; fh->params = params; fh->config = rsz_conf_chan; if (mutex_lock_interruptible(&device->reszwrap_mutex)) { ret = -EINTR; goto err_enomem2; } device->opened++; mutex_unlock(&device->reszwrap_mutex); rsz_conf_chan->config_state = STATE_NOT_CONFIGURED; rsz_conf_chan->status = CHANNEL_FREE; filp->private_data = fh; fh->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fh->device = device; videobuf_queue_sg_init(&fh->vbq, &device->vbq_ops, NULL, &fh->vbq_lock, fh->type, V4L2_FIELD_NONE, sizeof(struct videobuf_buffer), fh); spin_lock_init(&fh->vbq_lock); mutex_init(&rsz_conf_chan->chanprotection_mutex); return 0; err_enomem2: kfree(params); err_enomem1: kfree(rsz_conf_chan); err_enomem0: kfree(fh); return ret; } /** * rsz_release - Releases Resizer Wrapper and frees up allocated memory * @inode: Inode structure associated with the Resizer Wrapper * @filp: File structure associated with the Resizer Wrapper * * Returns 0 if successful, or -EBUSY if channel is being used. **/ static int rsz_release(struct inode *inode, struct file *filp) { u32 timeout = 0; struct rsz_fh *fh = filp->private_data; struct channel_config *rsz_conf_chan = fh->config; struct rsz_params *params = fh->params; struct rsz_mult *multipass = fh->multipass; struct videobuf_queue *q = &fh->vbq; while ((rsz_conf_chan->status != CHANNEL_FREE) && (timeout < 20)) { timeout++; schedule(); } if (mutex_lock_interruptible(&device_config->reszwrap_mutex)) return -EINTR; device_config->opened--; mutex_unlock(&device_config->reszwrap_mutex); /* This will Free memory allocated to the buffers, * and flushes the queue */ videobuf_queue_cancel(q); fh->params = NULL; fh->config = NULL; fh->rsz_bufsize = 0; filp->private_data = NULL; kfree(rsz_conf_chan); kfree(params); kfree(multipass); kfree(fh); isp_put(); return 0; } /** * rsz_mmap - Memory maps the Resizer Wrapper module. * @file: File structure associated with the Resizer Wrapper * @vma: Virtual memory area structure. * * Returns 0 if successful, or returned value by the videobuf_mmap_mapper() * function. **/ static int rsz_mmap(struct file *file, struct vm_area_struct *vma) { struct rsz_fh *fh = file->private_data; return videobuf_mmap_mapper(&fh->vbq, vma); } /** * rsz_ioctl - I/O control function for Resizer Wrapper * @inode: Inode structure associated with the Resizer Wrapper. * @file: File structure associated with the Resizer Wrapper. * @cmd: Type of command to execute. * @arg: Argument to send to requested command. * * Returns 0 if successful, -EBUSY if channel is being used, -1 if bad command * passed or access is denied, -EFAULT if copy_from_user() or copy_to_user() * fails, -EINVAL if parameter validation fails or parameter structure is not * present. **/ static long rsz_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret = 0; struct rsz_fh *fh = file->private_data; struct device_params *device = fh->device; struct channel_config *rsz_conf_chan = fh->config; if ((_IOC_TYPE(cmd) != RSZ_IOC_BASE) || (_IOC_NR(cmd) > RSZ_IOC_MAXNR)) { dev_err(rsz_device, "Bad command value \n"); goto err_minusone; } if (_IOC_DIR(cmd) & _IOC_READ) ret = !access_ok(VERIFY_WRITE, (void *)arg, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) ret = !access_ok(VERIFY_READ, (void *)arg, _IOC_SIZE(cmd)); if (ret) { dev_err(rsz_device, "Access denied\n"); goto err_minusone; } switch (cmd) { case RSZ_REQBUF: { struct v4l2_requestbuffers req_buf; if (copy_from_user(&req_buf, (struct v4l2_requestbuffers *)arg, sizeof(struct v4l2_requestbuffers))) { goto err_efault; } if (mutex_lock_interruptible(&rsz_conf_chan-> chanprotection_mutex)) goto err_eintr; ret = videobuf_reqbufs(&fh->vbq, (void *)&req_buf); mutex_unlock(&rsz_conf_chan->chanprotection_mutex); break; } case RSZ_QUERYBUF: { struct v4l2_buffer buf; if (copy_from_user(&buf, (struct v4l2_buffer *)arg, sizeof(struct v4l2_buffer))) { goto err_efault; } if (mutex_lock_interruptible(&rsz_conf_chan-> chanprotection_mutex)) goto err_eintr; ret = videobuf_querybuf(&fh->vbq, (void *)&buf); mutex_unlock(&rsz_conf_chan->chanprotection_mutex); if (copy_to_user((struct v4l2_buffer *)arg, &buf, sizeof(struct v4l2_buffer))) ret = -EFAULT; break; } case RSZ_QUEUEBUF: { struct v4l2_buffer buf; if (copy_from_user(&buf, (struct v4l2_buffer *)arg, sizeof(struct v4l2_buffer))) { goto err_efault; } if (mutex_lock_interruptible(&rsz_conf_chan-> chanprotection_mutex)) goto err_eintr; ret = videobuf_qbuf(&fh->vbq, (void *)&buf); mutex_unlock(&rsz_conf_chan->chanprotection_mutex); break; } case RSZ_S_PARAM: { struct rsz_params *params = fh->params; if (copy_from_user(params, (struct rsz_params *)arg, sizeof(struct rsz_params))) { goto err_efault; } if (mutex_lock_interruptible(&rsz_conf_chan-> chanprotection_mutex)) goto err_eintr; ret = rsz_set_params(fh->multipass, params, rsz_conf_chan); mutex_unlock(&rsz_conf_chan->chanprotection_mutex); break; } case RSZ_G_PARAM: ret = rsz_get_params((struct rsz_params *)arg, rsz_conf_chan); break; case RSZ_G_STATUS: { struct rsz_status *status; status = (struct rsz_status *)arg; status->chan_busy = rsz_conf_chan->status; status->hw_busy = ispresizer_busy(); status->src = INPUT_RAM; break; } case RSZ_RESIZE: if (file->f_flags & O_NONBLOCK) { if (ispresizer_busy()) return -EBUSY; else { if (!mutex_trylock(&device->reszwrap_mutex)) return -EBUSY; } } else { if (mutex_lock_interruptible(&device->reszwrap_mutex)) goto err_eintr; } ret = rsz_start((int *)arg, fh); mutex_unlock(&device->reszwrap_mutex); break; case RSZ_GET_CROPSIZE: rsz_calculate_crop(rsz_conf_chan, (struct rsz_cropsize *)arg); break; default: dev_err(rsz_device, "resizer_ioctl: Invalid Command Value"); ret = -EINVAL; } out: return (long)ret; err_minusone: ret = -1; goto out; err_eintr: ret = -EINTR; goto out; err_efault: ret = -EFAULT; goto out; } static struct file_operations rsz_fops = { .owner = THIS_MODULE, .open = rsz_open, .release = rsz_release, .mmap = rsz_mmap, .unlocked_ioctl = rsz_unlocked_ioctl, }; /** * rsz_isr - Interrupt Service Routine for Resizer wrapper * @status: ISP IRQ0STATUS register value * @arg1: Currently not used * @arg2: Currently not used * * Interrupt Service Routine for Resizer wrapper **/ static void rsz_isr(unsigned long status, isp_vbq_callback_ptr arg1, void *arg2) { if ((status & RESZ_DONE) != RESZ_DONE) return; complete(&(device_config->compl_isr)); } /** * resizer_platform_release - Acts when Reference count is zero * @device: Structure containing ISP resizer wrapper global information * * This is called when the reference count goes to zero. **/ static void resizer_platform_release(struct device *device) { } /** * resizer_probe - Checks for device presence * @device: Structure containing details of the current device. * * Always returns 0. **/ static int __init resizer_probe(struct platform_device *device) { return 0; } /** * resizer_remove - Handles the removal of the driver * @omap_resizer_device: Structure containing details of the current device. * * Always returns 0. **/ static int resizer_remove(struct platform_device *omap_resizer_device) { return 0; } static struct class *rsz_class; static struct cdev c_dev; static dev_t dev; static struct platform_device omap_resizer_device = { .name = OMAP_REZR_NAME, .id = 2, .dev = { .release = resizer_platform_release,} }; static struct platform_driver omap_resizer_driver = { .probe = resizer_probe, .remove = resizer_remove, .driver = { .bus = &platform_bus_type, .name = OMAP_REZR_NAME, }, }; /** * omap_rsz_init - Initialization of Resizer Wrapper * * Returns 0 if successful, -ENOMEM if could not allocate memory, -ENODEV if * could not register the wrapper as a character device, or other errors if the * device or driver can't register. **/ static int __init omap_rsz_init(void) { int ret = 0; struct device_params *device; device = kzalloc(sizeof(struct device_params), GFP_KERNEL); if (!device) { dev_err(rsz_device, OMAP_REZR_NAME ": could not allocate " "memory\n"); return -ENOMEM; } ret = alloc_chrdev_region(&dev, 0, 1, OMAP_REZR_NAME); if (ret < 0) { dev_err(rsz_device, OMAP_REZR_NAME ": intialization failed. " "Could not allocate region " "for character device\n"); kfree(device); return -ENODEV; } /* Register the driver in the kernel */ /* Initialize of character device */ cdev_init(&c_dev, &rsz_fops); c_dev.owner = THIS_MODULE; c_dev.ops = &rsz_fops; /* Addding character device */ ret = cdev_add(&c_dev, dev, 1); if (ret) { dev_err(rsz_device, OMAP_REZR_NAME ": Error adding " "device - %d\n", ret); goto fail2; } rsz_major = MAJOR(dev); /* register driver as a platform driver */ ret = platform_driver_register(&omap_resizer_driver); if (ret) { dev_err(rsz_device, OMAP_REZR_NAME ": Failed to register platform driver!\n"); goto fail3; } /* Register the drive as a platform device */ ret = platform_device_register(&omap_resizer_device); if (ret) { dev_err(rsz_device, OMAP_REZR_NAME ": Failed to register platform device!\n"); goto fail4; } rsz_class = class_create(THIS_MODULE, OMAP_REZR_NAME); if (!rsz_class) { dev_err(rsz_device, OMAP_REZR_NAME ": Failed to create class!\n"); goto fail5; } /* make entry in the devfs */ rsz_device = device_create(rsz_class, rsz_device, MKDEV(rsz_major, 0), NULL, OMAP_REZR_NAME); dev_dbg(rsz_device, OMAP_REZR_NAME ": Registered Resizer Wrapper\n"); device->opened = 0; device->vbq_ops.buf_setup = rsz_vbq_setup; device->vbq_ops.buf_prepare = rsz_vbq_prepare; device->vbq_ops.buf_release = rsz_vbq_release; device->vbq_ops.buf_queue = rsz_vbq_queue; init_completion(&device->compl_isr); mutex_init(&device->reszwrap_mutex); device_config = device; return 0; fail5: platform_device_unregister(&omap_resizer_device); fail4: platform_driver_unregister(&omap_resizer_driver); fail3: cdev_del(&c_dev); fail2: unregister_chrdev_region(dev, 1); kfree(device); return ret; } /** * omap_rsz_exit - Close of Resizer Wrapper **/ void __exit omap_rsz_exit(void) { device_destroy(rsz_class, dev); class_destroy(rsz_class); platform_device_unregister(&omap_resizer_device); platform_driver_unregister(&omap_resizer_driver); cdev_del(&c_dev); unregister_chrdev_region(dev, 1); kfree(device_config); } module_init(omap_rsz_init) module_exit(omap_rsz_exit) MODULE_AUTHOR("Texas Instruments"); MODULE_DESCRIPTION("OMAP ISP Resizer"); MODULE_LICENSE("GPL");
csolanol/kernel-morrison
drivers/media/video/oldisp/omap_resizer.c
C
gpl-2.0
45,921
<?php namespace TYPO3\CMS\Core\Tests\Unit\Cache\Fixtures; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Backend for cache manager test getCacheCreatesCacheInstanceWithFallbackToDefaultBackend */ class BackendDefaultFixture extends BackendFixture { public function __construct() { throw new \RuntimeException('', 1464556045); } }
morinfa/TYPO3.CMS
typo3/sysext/core/Tests/Unit/Cache/Fixtures/BackendDefaultFixture.php
PHP
gpl-2.0
721
<?php /** * BuddyPress Groups Actions. * * Action functions are exactly the same as screen functions, however they do * not have a template screen associated with them. Usually they will send the * user back to the default screen after execution. * * @package BuddyPress * @subpackage GroupsActions */ // Exit if accessed directly. defined( 'ABSPATH' ) || exit; /** * Protect access to single groups. * * @since 2.1.0 */ function bp_groups_group_access_protection() { if ( ! bp_is_group() ) { return; } $current_group = groups_get_current_group(); $user_has_access = $current_group->user_has_access; $no_access_args = array(); if ( ! $user_has_access && 'hidden' !== $current_group->status ) { // Always allow access to home and request-membership if ( bp_is_current_action( 'home' ) || bp_is_current_action( 'request-membership' ) ) { $user_has_access = true; // User doesn't have access, so set up redirect args } elseif ( is_user_logged_in() ) { $no_access_args = array( 'message' => __( 'You do not have access to this group.', 'buddypress' ), 'root' => bp_get_group_permalink( $current_group ) . 'home/', 'redirect' => false ); } } // Protect the admin tab from non-admins if ( bp_is_current_action( 'admin' ) && ! bp_is_item_admin() ) { $user_has_access = false; $no_access_args = array( 'message' => __( 'You are not an admin of this group.', 'buddypress' ), 'root' => bp_get_group_permalink( $current_group ), 'redirect' => false ); } /** * Allow plugins to filter whether the current user has access to this group content. * * Note that if a plugin sets $user_has_access to false, it may also * want to change the $no_access_args, to avoid problems such as * logged-in users being redirected to wp-login.php. * * @since 2.1.0 * * @param bool $user_has_access True if the user has access to the * content, otherwise false. * @param array $no_access_args Arguments to be passed to bp_core_no_access() in case * of no access. Note that this value is passed by reference, * so it can be modified by the filter callback. */ $user_has_access = apply_filters_ref_array( 'bp_group_user_has_access', array( $user_has_access, &$no_access_args ) ); // If user has access, we return rather than redirect. if ( $user_has_access ) { return; } // Hidden groups should return a 404 for non-members. // Unset the current group so that you're not redirected // to the default group tab. if ( 'hidden' == $current_group->status ) { buddypress()->groups->current_group = 0; buddypress()->is_single_item = false; bp_do_404(); return; } else { bp_core_no_access( $no_access_args ); } } add_action( 'bp_actions', 'bp_groups_group_access_protection' ); /** * Catch and process group creation form submissions. */ function groups_action_create_group() { // If we're not at domain.org/groups/create/ then return false if ( !bp_is_groups_component() || !bp_is_current_action( 'create' ) ) return false; if ( !is_user_logged_in() ) return false; if ( !bp_user_can_create_groups() ) { bp_core_add_message( __( 'Sorry, you are not allowed to create groups.', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_groups_directory_permalink() ); } $bp = buddypress(); // Make sure creation steps are in the right order groups_action_sort_creation_steps(); // If no current step is set, reset everything so we can start a fresh group creation $bp->groups->current_create_step = bp_action_variable( 1 ); if ( !bp_get_groups_current_create_step() ) { unset( $bp->groups->current_create_step ); unset( $bp->groups->completed_create_steps ); setcookie( 'bp_new_group_id', false, time() - 1000, COOKIEPATH ); setcookie( 'bp_completed_create_steps', false, time() - 1000, COOKIEPATH ); $reset_steps = true; $keys = array_keys( $bp->groups->group_creation_steps ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create/step/' . array_shift( $keys ) ) ); } // If this is a creation step that is not recognized, just redirect them back to the first screen if ( bp_get_groups_current_create_step() && empty( $bp->groups->group_creation_steps[bp_get_groups_current_create_step()] ) ) { bp_core_add_message( __('There was an error saving group details. Please try again.', 'buddypress'), 'error' ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create' ) ); } // Fetch the currently completed steps variable if ( isset( $_COOKIE['bp_completed_create_steps'] ) && !isset( $reset_steps ) ) $bp->groups->completed_create_steps = json_decode( base64_decode( stripslashes( $_COOKIE['bp_completed_create_steps'] ) ) ); // Set the ID of the new group, if it has already been created in a previous step if ( isset( $_COOKIE['bp_new_group_id'] ) ) { $bp->groups->new_group_id = (int) $_COOKIE['bp_new_group_id']; $bp->groups->current_group = groups_get_group( array( 'group_id' => $bp->groups->new_group_id ) ); // Only allow the group creator to continue to edit the new group if ( ! bp_is_group_creator( $bp->groups->current_group, bp_loggedin_user_id() ) ) { bp_core_add_message( __( 'Only the group creator may continue editing this group.', 'buddypress' ), 'error' ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create' ) ); } } // If the save, upload or skip button is hit, lets calculate what we need to save if ( isset( $_POST['save'] ) ) { // Check the nonce check_admin_referer( 'groups_create_save_' . bp_get_groups_current_create_step() ); if ( 'group-details' == bp_get_groups_current_create_step() ) { if ( empty( $_POST['group-name'] ) || empty( $_POST['group-desc'] ) || !strlen( trim( $_POST['group-name'] ) ) || !strlen( trim( $_POST['group-desc'] ) ) ) { bp_core_add_message( __( 'Please fill in all of the required fields', 'buddypress' ), 'error' ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create/step/' . bp_get_groups_current_create_step() ) ); } $new_group_id = isset( $bp->groups->new_group_id ) ? $bp->groups->new_group_id : 0; if ( !$bp->groups->new_group_id = groups_create_group( array( 'group_id' => $new_group_id, 'name' => $_POST['group-name'], 'description' => $_POST['group-desc'], 'slug' => groups_check_slug( sanitize_title( esc_attr( $_POST['group-name'] ) ) ), 'date_created' => bp_core_current_time(), 'status' => 'public' ) ) ) { bp_core_add_message( __( 'There was an error saving group details. Please try again.', 'buddypress' ), 'error' ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create/step/' . bp_get_groups_current_create_step() ) ); } } if ( 'group-settings' == bp_get_groups_current_create_step() ) { $group_status = 'public'; $group_enable_forum = 1; if ( !isset($_POST['group-show-forum']) ) { $group_enable_forum = 0; } else { // Create the forum if enable_forum = 1 if ( bp_is_active( 'forums' ) && !groups_get_groupmeta( $bp->groups->new_group_id, 'forum_id' ) ) { groups_new_group_forum(); } } if ( 'private' == $_POST['group-status'] ) $group_status = 'private'; elseif ( 'hidden' == $_POST['group-status'] ) $group_status = 'hidden'; if ( !$bp->groups->new_group_id = groups_create_group( array( 'group_id' => $bp->groups->new_group_id, 'status' => $group_status, 'enable_forum' => $group_enable_forum ) ) ) { bp_core_add_message( __( 'There was an error saving group details. Please try again.', 'buddypress' ), 'error' ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create/step/' . bp_get_groups_current_create_step() ) ); } /** * Filters the allowed invite statuses. * * @since 1.5.0 * * @param array $value Array of statuses allowed. * Possible values are 'members, * 'mods', and 'admins'. */ $allowed_invite_status = apply_filters( 'groups_allowed_invite_status', array( 'members', 'mods', 'admins' ) ); $invite_status = !empty( $_POST['group-invite-status'] ) && in_array( $_POST['group-invite-status'], (array) $allowed_invite_status ) ? $_POST['group-invite-status'] : 'members'; groups_update_groupmeta( $bp->groups->new_group_id, 'invite_status', $invite_status ); } if ( 'group-invites' === bp_get_groups_current_create_step() ) { if ( ! empty( $_POST['friends'] ) ) { foreach ( (array) $_POST['friends'] as $friend ) { groups_invite_user( array( 'user_id' => (int) $friend, 'group_id' => $bp->groups->new_group_id, ) ); } } groups_send_invites( bp_loggedin_user_id(), $bp->groups->new_group_id ); } /** * Fires before finalization of group creation and cookies are set. * * This hook is a variable hook dependent on the current step * in the creation process. * * @since 1.1.0 */ do_action( 'groups_create_group_step_save_' . bp_get_groups_current_create_step() ); /** * Fires after the group creation step is completed. * * Mostly for clearing cache on a generic action name. * * @since 1.1.0 */ do_action( 'groups_create_group_step_complete' ); /** * Once we have successfully saved the details for this step of the creation process * we need to add the current step to the array of completed steps, then update the cookies * holding the information */ $completed_create_steps = isset( $bp->groups->completed_create_steps ) ? $bp->groups->completed_create_steps : array(); if ( !in_array( bp_get_groups_current_create_step(), $completed_create_steps ) ) $bp->groups->completed_create_steps[] = bp_get_groups_current_create_step(); // Reset cookie info setcookie( 'bp_new_group_id', $bp->groups->new_group_id, time()+60*60*24, COOKIEPATH ); setcookie( 'bp_completed_create_steps', base64_encode( json_encode( $bp->groups->completed_create_steps ) ), time()+60*60*24, COOKIEPATH ); // If we have completed all steps and hit done on the final step we // can redirect to the completed group $keys = array_keys( $bp->groups->group_creation_steps ); if ( count( $bp->groups->completed_create_steps ) == count( $keys ) && bp_get_groups_current_create_step() == array_pop( $keys ) ) { unset( $bp->groups->current_create_step ); unset( $bp->groups->completed_create_steps ); setcookie( 'bp_new_group_id', false, time() - 3600, COOKIEPATH ); setcookie( 'bp_completed_create_steps', false, time() - 3600, COOKIEPATH ); // Once we completed all steps, record the group creation in the activity stream. groups_record_activity( array( 'type' => 'created_group', 'item_id' => $bp->groups->new_group_id ) ); /** * Fires after the group has been successfully created. * * @since 1.1.0 * * @param int $new_group_id ID of the newly created group. */ do_action( 'groups_group_create_complete', $bp->groups->new_group_id ); bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) ); } else { /** * Since we don't know what the next step is going to be (any plugin can insert steps) * we need to loop the step array and fetch the next step that way. */ foreach ( $keys as $key ) { if ( $key == bp_get_groups_current_create_step() ) { $next = 1; continue; } if ( isset( $next ) ) { $next_step = $key; break; } } bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create/step/' . $next_step ) ); } } // Remove invitations if ( 'group-invites' === bp_get_groups_current_create_step() && ! empty( $_REQUEST['user_id'] ) && is_numeric( $_REQUEST['user_id'] ) ) { if ( ! check_admin_referer( 'groups_invite_uninvite_user' ) ) { return false; } $message = __( 'Invite successfully removed', 'buddypress' ); $error = false; if( ! groups_uninvite_user( (int) $_REQUEST['user_id'], $bp->groups->new_group_id ) ) { $message = __( 'There was an error removing the invite', 'buddypress' ); $error = 'error'; } bp_core_add_message( $message, $error ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . 'create/step/group-invites' ) ); } // Group avatar is handled separately if ( 'group-avatar' == bp_get_groups_current_create_step() && isset( $_POST['upload'] ) ) { if ( ! isset( $bp->avatar_admin ) ) { $bp->avatar_admin = new stdClass(); } if ( !empty( $_FILES ) && isset( $_POST['upload'] ) ) { // Normally we would check a nonce here, but the group save nonce is used instead // Pass the file to the avatar upload handler if ( bp_core_avatar_handle_upload( $_FILES, 'groups_avatar_upload_dir' ) ) { $bp->avatar_admin->step = 'crop-image'; // Make sure we include the jQuery jCrop file for image cropping add_action( 'wp_print_scripts', 'bp_core_add_jquery_cropper' ); } } // If the image cropping is done, crop the image and save a full/thumb version if ( isset( $_POST['avatar-crop-submit'] ) && isset( $_POST['upload'] ) ) { // Normally we would check a nonce here, but the group save nonce is used instead if ( !bp_core_avatar_handle_crop( array( 'object' => 'group', 'avatar_dir' => 'group-avatars', 'item_id' => $bp->groups->current_group->id, 'original_file' => $_POST['image_src'], 'crop_x' => $_POST['x'], 'crop_y' => $_POST['y'], 'crop_w' => $_POST['w'], 'crop_h' => $_POST['h'] ) ) ) bp_core_add_message( __( 'There was an error saving the group profile photo, please try uploading again.', 'buddypress' ), 'error' ); else bp_core_add_message( __( 'The group profile photo was uploaded successfully.', 'buddypress' ) ); } } /** * Filters the template to load for the group creation screen. * * @since 1.0.0 * * @param string $value Path to the group creation template to load. */ bp_core_load_template( apply_filters( 'groups_template_create_group', 'groups/create' ) ); } add_action( 'bp_actions', 'groups_action_create_group' ); /** * Catch and process "Join Group" button clicks. */ function groups_action_join_group() { if ( !bp_is_single_item() || !bp_is_groups_component() || !bp_is_current_action( 'join' ) ) return false; // Nonce check if ( !check_admin_referer( 'groups_join_group' ) ) return false; $bp = buddypress(); // Skip if banned or already a member if ( !groups_is_user_member( bp_loggedin_user_id(), $bp->groups->current_group->id ) && !groups_is_user_banned( bp_loggedin_user_id(), $bp->groups->current_group->id ) ) { // User wants to join a group that is not public if ( $bp->groups->current_group->status != 'public' ) { if ( !groups_check_user_has_invite( bp_loggedin_user_id(), $bp->groups->current_group->id ) ) { bp_core_add_message( __( 'There was an error joining the group.', 'buddypress' ), 'error' ); bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) ); } } // User wants to join any group if ( !groups_join_group( $bp->groups->current_group->id ) ) bp_core_add_message( __( 'There was an error joining the group.', 'buddypress' ), 'error' ); else bp_core_add_message( __( 'You joined the group!', 'buddypress' ) ); bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) ); } /** * Filters the template to load for the single group screen. * * @since 1.0.0 * * @param string $value Path to the single group template to load. */ bp_core_load_template( apply_filters( 'groups_template_group_home', 'groups/single/home' ) ); } add_action( 'bp_actions', 'groups_action_join_group' ); /** * Catch and process "Leave Group" button clicks. * * When a group member clicks on the "Leave Group" button from a group's page, * this function is run. * * Note: When leaving a group from the group directory, AJAX is used and * another function handles this. See {@link bp_legacy_theme_ajax_joinleave_group()}. * * @since 1.2.4 */ function groups_action_leave_group() { if ( ! bp_is_single_item() || ! bp_is_groups_component() || ! bp_is_current_action( 'leave-group' ) ) { return false; } // Nonce check if ( ! check_admin_referer( 'groups_leave_group' ) ) { return false; } // User wants to leave any group if ( groups_is_user_member( bp_loggedin_user_id(), bp_get_current_group_id() ) ) { $bp = buddypress(); // Stop sole admins from abandoning their group $group_admins = groups_get_group_admins( bp_get_current_group_id() ); if ( 1 == count( $group_admins ) && $group_admins[0]->user_id == bp_loggedin_user_id() ) { bp_core_add_message( __( 'This group must have at least one admin', 'buddypress' ), 'error' ); } elseif ( ! groups_leave_group( $bp->groups->current_group->id ) ) { bp_core_add_message( __( 'There was an error leaving the group.', 'buddypress' ), 'error' ); } else { bp_core_add_message( __( 'You successfully left the group.', 'buddypress' ) ); } $redirect = bp_get_group_permalink( groups_get_current_group() ); if( 'hidden' == $bp->groups->current_group->status ) { $redirect = trailingslashit( bp_loggedin_user_domain() . bp_get_groups_slug() ); } bp_core_redirect( $redirect ); } /** This filter is documented in bp-groups/bp-groups-actions.php */ bp_core_load_template( apply_filters( 'groups_template_group_home', 'groups/single/home' ) ); } add_action( 'bp_actions', 'groups_action_leave_group' ); /** * Sort the group creation steps. * * @return false|null False on failure. */ function groups_action_sort_creation_steps() { if ( !bp_is_groups_component() || !bp_is_current_action( 'create' ) ) return false; $bp = buddypress(); if ( !is_array( $bp->groups->group_creation_steps ) ) return false; foreach ( (array) $bp->groups->group_creation_steps as $slug => $step ) { while ( !empty( $temp[$step['position']] ) ) $step['position']++; $temp[$step['position']] = array( 'name' => $step['name'], 'slug' => $slug ); } // Sort the steps by their position key ksort($temp); unset($bp->groups->group_creation_steps); foreach( (array) $temp as $position => $step ) $bp->groups->group_creation_steps[$step['slug']] = array( 'name' => $step['name'], 'position' => $position ); /** * Fires after group creation sets have been sorted. * * @since 2.3.0 */ do_action( 'groups_action_sort_creation_steps' ); } /** * Catch requests for a random group page (example.com/groups/?random-group) and redirect. */ function groups_action_redirect_to_random_group() { if ( bp_is_groups_component() && isset( $_GET['random-group'] ) ) { $group = BP_Groups_Group::get_random( 1, 1 ); bp_core_redirect( trailingslashit( bp_get_groups_directory_permalink() . $group['groups'][0]->slug ) ); } } add_action( 'bp_actions', 'groups_action_redirect_to_random_group' ); /** * Load the activity feed for the current group. * * @since 1.2.0 * * @return false|null False on failure. */ function groups_action_group_feed() { // get current group $group = groups_get_current_group(); if ( ! bp_is_active( 'activity' ) || ! bp_is_groups_component() || ! $group || ! bp_is_current_action( 'feed' ) ) return false; // if group isn't public or if logged-in user is not a member of the group, do // not output the group activity feed if ( ! bp_group_is_visible( $group ) ) { return false; } // setup the feed buddypress()->activity->feed = new BP_Activity_Feed( array( 'id' => 'group', /* translators: Group activity RSS title - "[Site Name] | [Group Name] | Activity" */ 'title' => sprintf( __( '%1$s | %2$s | Activity', 'buddypress' ), bp_get_site_name(), bp_get_current_group_name() ), 'link' => bp_get_group_permalink( $group ), 'description' => sprintf( __( "Activity feed for the group, %s.", 'buddypress' ), bp_get_current_group_name() ), 'activity_args' => array( 'object' => buddypress()->groups->id, 'primary_id' => bp_get_current_group_id(), 'display_comments' => 'threaded' ) ) ); } add_action( 'bp_actions', 'groups_action_group_feed' );
NYCPrepared/v2
wp-content/plugins/buddypress/bp-groups/bp-groups-actions.php
PHP
gpl-2.0
20,259
/* * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8168423 * @summary Different types of ClassLoader running with(out) SecurityManager and * (in)valid security policy file. * @library /lib/testlibrary * @modules java.base/jdk.internal.module * @build JarUtils * @build TestClassLoader TestClient * @run main ClassLoaderTest -noPolicy * @run main ClassLoaderTest -validPolicy * @run main ClassLoaderTest -invalidPolicy * @run main ClassLoaderTest -noPolicy -customSCL * @run main ClassLoaderTest -validPolicy -customSCL * @run main ClassLoaderTest -invalidPolicy -customSCL */ import java.io.File; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.stream.Stream; import java.lang.module.ModuleDescriptor; import java.util.Collections; import java.util.LinkedList; import java.util.List; import jdk.internal.module.ModuleInfoWriter; import jdk.testlibrary.ProcessTools; public class ClassLoaderTest { private static final String SRC = System.getProperty("test.src"); private static final Path TEST_CLASSES = Paths.get(System.getProperty("test.classes")); private static final Path ARTIFACT_DIR = Paths.get("jars"); private static final Path VALID_POLICY = Paths.get(SRC, "valid.policy"); private static final Path INVALID_POLICY = Paths.get(SRC, "malformed.policy"); /* * Here is the naming convention followed for each jar. * cl.jar - Regular custom class loader jar. * mcl.jar - Modular custom class loader jar. * c.jar - Regular client jar. * mc.jar - Modular client jar. * amc.jar - Modular client referring automated custom class loader jar. */ private static final Path CL_JAR = ARTIFACT_DIR.resolve("cl.jar"); private static final Path MCL_JAR = ARTIFACT_DIR.resolve("mcl.jar"); private static final Path C_JAR = ARTIFACT_DIR.resolve("c.jar"); private static final Path MC_JAR = ARTIFACT_DIR.resolve("mc.jar"); private static final Path AMC_JAR = ARTIFACT_DIR.resolve("amc.jar"); // Expected output messages private static final String MISSING_MODULE = "Module cl not found, required by mc"; private static final String POLICY_ERROR = "java.security.policy: error parsing file"; private static final String SYSTEM_CL_MSG = "jdk.internal.loader.ClassLoaders$AppClassLoader"; private static final String CUSTOM_CL_MSG = "cl.TestClassLoader"; // Member vars private final boolean useSCL; // Use default system loader, or custom private final String smMsg; // Security manager message, or "" private final String autoAddModArg; // Flag to add cl modules, or "" private final String addmodArg; // Flag to add mcl modules, or "" private final String expectedStatus;// Expected exit status from client private final String expectedMsg; // Expected output message from client // Common set of VM arguments used in all test cases private final List<String> commonArgs; public ClassLoaderTest(Path policy, boolean useSCL) { this.useSCL = useSCL; List<String> argList = new LinkedList<>(); argList.add("-Duser.language=en"); argList.add("-Duser.region=US"); boolean malformedPolicy = false; if (policy == null) { smMsg = "Without SecurityManager"; } else { malformedPolicy = policy.equals(INVALID_POLICY); argList.add("-Djava.security.manager"); argList.add("-Djava.security.policy=" + policy.toFile().getAbsolutePath()); smMsg = "With SecurityManager"; } if (useSCL) { autoAddModArg = ""; addmodArg = ""; } else { argList.add("-Djava.system.class.loader=cl.TestClassLoader"); autoAddModArg = "--add-modules=cl"; addmodArg = "--add-modules=mcl"; } if (malformedPolicy) { expectedStatus = "FAIL"; expectedMsg = POLICY_ERROR; } else if (useSCL) { expectedStatus = "PASS"; expectedMsg = SYSTEM_CL_MSG; } else { expectedStatus = "PASS"; expectedMsg = CUSTOM_CL_MSG; } commonArgs = Collections.unmodifiableList(argList); } public static void main(String[] args) throws Exception { Path policy; if (args[0].equals("-noPolicy")) { policy = null; } else if (args[0].equals("-validPolicy")) { policy = VALID_POLICY; } else if (args[0].equals("-invalidPolicy")) { policy = INVALID_POLICY; } else { throw new RuntimeException("Unknown policy arg: " + args[0]); } boolean useSystemLoader = true; if (args.length > 1) { if (args[1].equals("-customSCL")) { useSystemLoader = false; } else { throw new RuntimeException("Unknown custom loader arg: " + args[1]); } } ClassLoaderTest test = new ClassLoaderTest(policy, useSystemLoader); setUp(); test.processForPolicyFile(); } /** * Test cases are based on the following logic, * given: a policyFile in {none, valid, malformed} and * a classLoader in {SystemClassLoader, CustomClassLoader}: * for (clientModule : {"NAMED", "UNNAMED"}) { * for (classLoaderModule : {"NAMED", "UNNAMED"}) { * Create and run java command for each possible Test case * } * } */ private void processForPolicyFile() throws Exception { final String regLoaderLoc = CL_JAR.toFile().getAbsolutePath(); final String modLoadrLoc = MCL_JAR.toFile().getAbsolutePath(); final String regClientLoc = C_JAR.toFile().getAbsolutePath(); final String modClientLoc = MC_JAR.toFile().getAbsolutePath(); final String autoModCloc = AMC_JAR.toFile().getAbsolutePath(); final String separator = File.pathSeparator; // NAMED-NAMED: System.out.println("Case:- Modular Client and " + ((useSCL) ? "SystemClassLoader" : "Modular CustomClassLoader") + " " + smMsg); execute("--module-path", modClientLoc + separator + modLoadrLoc, "-m", "mc/c.TestClient"); // NAMED-UNNAMED: System.out.println("Case:- Modular Client and " + ((useSCL) ? "SystemClassLoader" : "Unknown modular CustomClassLoader") + " " + smMsg); execute(new String[] {"--module-path", autoModCloc, "-cp", regLoaderLoc, "-m", "mc/c.TestClient"}, "FAIL", MISSING_MODULE); // UNNAMED-NAMED: System.out.println("Case:- Unknown modular Client and " + ((useSCL) ? "SystemClassLoader" : "Modular CustomClassLoader") + " " + smMsg); execute("-cp", regClientLoc, "--module-path", modLoadrLoc, addmodArg, "c.TestClient"); // UNNAMED-UNNAMED: System.out.println("Case:- Unknown modular Client and " + ((useSCL) ? "SystemClassLoader" : "Unknown modular CustomClassLoader") + " " + smMsg); execute("-cp", regClientLoc + separator + regLoaderLoc, "c.TestClient"); // Regular jars in module-path System.out.println("Case:- Regular Client and " + ((useSCL) ? "SystemClassLoader" : "Unknown modular CustomClassLoader") + " inside --module-path " + smMsg); execute("--module-path", regClientLoc + separator + regLoaderLoc, autoAddModArg, "-m", "c/c.TestClient"); // Modular jars in class-path System.out.println("Case:- Modular Client and " + ((useSCL) ? "SystemClassLoader" : "Modular CustomClassLoader") + " in -cp " + smMsg); execute("-cp", modClientLoc + separator + modLoadrLoc, "c.TestClient"); } private void execute(String... args) throws Exception { execute(args, this.expectedStatus, this.expectedMsg); } /** * Execute with command arguments and process the result. */ private void execute(String[] args, String status, String msg) throws Exception { // Combine with commonArgs, and perform sanity check String[] safeArgs = Stream.concat(commonArgs.stream(), Stream.of(args)) .filter(s -> { if (s.contains(" ")) { throw new RuntimeException("No spaces in args");} return !s.isEmpty(); }).toArray(String[]::new); String out = ProcessTools.executeTestJvm(safeArgs).getOutput(); // Handle response. if ("PASS".equals(status) && out.contains(msg)) { System.out.println("PASS: Expected Result: " + msg); } else if ("FAIL".equals(status) && out.contains(msg)) { System.out.printf("PASS: Expected Failure: " + msg); } else if (out.contains("Exception") || out.contains("Error")) { System.out.printf("OUTPUT: %s", out); throw new RuntimeException("FAIL: Unknown Exception."); } else { System.out.printf("OUTPUT: %s", out); throw new RuntimeException("FAIL: Unknown Test case found"); } } /** * Creates regular/modular jar files for TestClient and TestClassLoader. */ private static void setUp() throws Exception { // Generate regular jar files for TestClient and TestClassLoader JarUtils.createJarFile(CL_JAR, TEST_CLASSES, "cl/TestClassLoader.class"); JarUtils.createJarFile(C_JAR, TEST_CLASSES, "c/TestClient.class"); // Generate modular jar files for TestClient and TestClassLoader with // their corresponding ModuleDescriptor. Files.copy(CL_JAR, MCL_JAR, StandardCopyOption.REPLACE_EXISTING); updateModuleDescr(MCL_JAR, ModuleDescriptor.newModule("mcl") .exports("cl").requires("java.base").build()); Files.copy(C_JAR, MC_JAR, StandardCopyOption.REPLACE_EXISTING); updateModuleDescr(MC_JAR, ModuleDescriptor.newModule("mc") .exports("c").requires("java.base").requires("mcl").build()); Files.copy(C_JAR, AMC_JAR, StandardCopyOption.REPLACE_EXISTING); updateModuleDescr(AMC_JAR, ModuleDescriptor.newModule("mc") .exports("c").requires("java.base").requires("cl").build()); } /** * Update regular jars and include module-info.class inside it to make * modular jars. */ private static void updateModuleDescr(Path jar, ModuleDescriptor mDescr) throws Exception { if (mDescr != null) { Path dir = Files.createTempDirectory("tmp"); Path mi = dir.resolve("module-info.class"); try (OutputStream out = Files.newOutputStream(mi)) { ModuleInfoWriter.write(mDescr, out); } System.out.format("Adding 'module-info.class' to jar '%s'%n", jar); JarUtils.updateJarFile(jar, dir); } } }
YouDiSN/OpenJDK-Research
jdk9/jdk/test/java/lang/ClassLoader/securityManager/ClassLoaderTest.java
Java
gpl-2.0
12,452
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <meta http-equiv="Content-Style-Type" content="text/css"> <link rel="up" title="FatFs" href="../00index_j.html"> <link rel="alternate" hreflang="en" title="English" href="../en/getlabel.html"> <link rel="stylesheet" href="../css_j.css" type="text/css" media="screen" title="ELM Default"> <title>FatFs - f_getlabel</title> </head> <body> <div class="para func"> <h2>f_getlabel</h2> <p>ƒ{ƒŠƒ…[ƒ€Eƒ‰ƒxƒ‹‚ðŽæ“¾‚µ‚Ü‚·B</p> <pre> FRESULT f_getlabel ( const TCHAR* <span class="arg">path</span>, <span class="c">/* [IN] ‘Ώۃhƒ‰ƒCƒu */</span> TCHAR* <span class="arg">name</span>, <span class="c">/* [OUT] ƒ{ƒŠƒ…[ƒ€–¼‚ðŠi”[‚·‚éƒoƒbƒtƒ@ */</span> DWORD* <span class="arg">sn</span> <span class="c">/* [OUT] ƒ{ƒŠƒ…[ƒ€EƒVƒŠƒAƒ‹”ԍ†‚ðŠi”[‚·‚é•ϐ” */</span> ); </pre> </div> <div class="para arg"> <h4>ˆø”</h4> <dl class="par"> <dt>path</dt> <dd>‘ΏۂƂȂé˜_—ƒhƒ‰ƒCƒu‚Ì<a href="filename.html">ƒpƒX–¼</a>‚ðŽ¦‚·ƒkƒ‹•¶Žš<tt>'\0'</tt>I’[‚Ì•¶Žš—ñ‚ւ̃|ƒCƒ“ƒ^‚ðŽw’肵‚Ü‚·Bƒkƒ‹•¶Žš—ñ‚̏ꍇ‚́AƒfƒtƒHƒ‹ƒgEƒhƒ‰ƒCƒu‚ðŽw’肵‚½‚±‚ƂɂȂè‚Ü‚·B</dd> <dt>name</dt> <dd>ƒ{ƒŠƒ…[ƒ€–¼‚ðŠi”[‚·‚é”z—ñ‚ւ̃|ƒCƒ“ƒ^‚ðŽw’肵‚Ü‚·B­‚È‚­‚Æ‚à12—v‘f‚̃TƒCƒY‚ª•K—v‚Å‚·Bƒ{ƒŠƒ…[ƒ€–¼‚ª‚È‚¢ê‡‚̓kƒ‹•¶Žš—ñ‚ª•Ô‚³‚ê‚Ü‚·B‚±‚̏î•ñ‚ª•s—v‚ȂƂ«‚̓kƒ‹Eƒ|ƒCƒ“ƒ^‚ðŽw’肵‚Ä‚­‚¾‚³‚¢B</dd> <dt>sn</dt> <dd>ƒ{ƒŠƒ…[ƒ€EƒVƒŠƒAƒ‹”ԍ†‚ðŠi”[‚·‚é<tt>DWORD</tt>•ϐ”‚ւ̃|ƒCƒ“ƒ^‚ðŽw’肵‚Ü‚·B‚±‚̏î•ñ‚ª•s—v‚ȂƂ«‚̓kƒ‹Eƒ|ƒCƒ“ƒ^‚ðŽw’肵‚Ä‚­‚¾‚³‚¢B</dd> </dl> </div> <div class="para ret"> <h4>–ß‚è’l</h4> <p> <a href="rc.html#ok">FR_OK</a>, <a href="rc.html#de">FR_DISK_ERR</a>, <a href="rc.html#ie">FR_INT_ERR</a>, <a href="rc.html#nr">FR_NOT_READY</a>, <a href="rc.html#id">FR_INVALID_DRIVE</a>, <a href="rc.html#ne">FR_NOT_ENABLED</a>, <a href="rc.html#ns">FR_NO_FILESYSTEM</a>, <a href="rc.html#tm">FR_TIMEOUT</a> </p> </div> <div class="para comp"> <h4>‘Ήžî•ñ</h4> <p><tt>_USE_LABEL == 1</tt>‚̂Ƃ«‚ÉŽg—p‰Â”\‚Å‚·B</p> </div> <div class="para use"> <h4>Žg—p—á</h4> <pre> char str[12]; <span class="c">/* ƒfƒtƒHƒ‹ƒgEƒhƒ‰ƒCƒu‚̃{ƒŠƒ…[ƒ€–¼‚𓾂é */</span> f_getlabel("", str, 0); <span class="c">/* ƒhƒ‰ƒCƒu2‚̃{ƒŠƒ…[ƒ€–¼‚𓾂é */</span> f_getlabel("2:", str, 0); </pre> </div> <div class="para ref"> <h4>ŽQÆ</h4> <tt><a href="setlabel.html">f_setlabel</a></tt> </div> <p class="foot"><a href="../00index_j.html">–ß‚é</a></p> </body> </html>
felis/UHS30
libraries/UHS_FS/FAT/FatFS/doc/ja/getlabel.html
HTML
gpl-2.0
2,551
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8180573 * @summary Enhance SecurityTools input line parsing * @library /test/lib */ import jdk.test.lib.Asserts; import jdk.test.lib.SecurityTools; import java.util.List; public class SecurityToolsTest { public static void main(String[] args) { Asserts.assertEQ(SecurityTools.makeList("a b c"), List.of("a", "b", "c")); Asserts.assertEQ(SecurityTools.makeList(" a b c "), List.of("a", "b", "c")); Asserts.assertEQ(SecurityTools.makeList("a\tb\nc"), List.of("a", "b", "c")); Asserts.assertEQ(SecurityTools.makeList("a `b` c"), List.of("a", "b", "c")); Asserts.assertEQ(SecurityTools.makeList("`a` b c"), List.of("a", "b", "c")); Asserts.assertEQ(SecurityTools.makeList("a b `c`"), List.of("a", "b", "c")); Asserts.assertEQ(SecurityTools.makeList("`a b` b c"), List.of("a b", "b", "c")); Asserts.assertEQ(SecurityTools.makeList("`a b c`"), List.of("a b c")); Asserts.assertEQ(SecurityTools.makeList("a ` b ` c"), List.of("a", " b ", "c")); Asserts.assertEQ(SecurityTools.makeList("a`b c"), List.of("a`b", "c")); Asserts.assertEQ(SecurityTools.makeList("a `\"b\"` c"), List.of("a", "\"b\"", "c")); } }
md-5/jdk10
test/jdk/sun/security/tools/keytool/SecurityToolsTest.java
Java
gpl-2.0
2,451
/* lzo1b_xx.c -- LZO1B compression public entry point This file is part of the LZO real-time data compression library. Copyright (C) 2011 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2010 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2009 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <markus@oberhumer.com> http://www.oberhumer.com/opensource/lzo/ */ #include "config1b.h" /*********************************************************************** // ************************************************************************/ static const lzo_compress_t * const c_funcs [9] = { &_lzo1b_1_compress_func, &_lzo1b_2_compress_func, &_lzo1b_3_compress_func, &_lzo1b_4_compress_func, &_lzo1b_5_compress_func, &_lzo1b_6_compress_func, &_lzo1b_7_compress_func, &_lzo1b_8_compress_func, &_lzo1b_9_compress_func }; lzo_compress_t _lzo1b_get_compress_func(int clevel) { const lzo_compress_t *f; if (clevel < LZO1B_BEST_SPEED || clevel > LZO1B_BEST_COMPRESSION) { if (clevel == LZO1B_DEFAULT_COMPRESSION) clevel = LZO1B_BEST_SPEED; else return 0; } f = c_funcs[clevel-1]; assert(f && *f); return *f; } LZO_PUBLIC(int) lzo1b_compress ( const lzo_bytep src, lzo_uint src_len, lzo_bytep dst, lzo_uintp dst_len, lzo_voidp wrkmem, int clevel ) { lzo_compress_t f; f = _lzo1b_get_compress_func(clevel); if (!f) return LZO_E_ERROR; return _lzo1b_do_compress(src,src_len,dst,dst_len,wrkmem,f); } /* vi:ts=4:et */
zarboz/XBMC-PVR-mac
tools/darwin/depends/liblzo2/src/lzo1b_xx.c
C
gpl-2.0
3,211
INSERT INTO spell_bonus_data VALUE (51723, -1, -1, 0.14, -1, 'Rogue - Fan of Knives');
MistCore/MistCore
sql/updates/world/worldpanda_old_world_updates_2012_2013/2012/2012_01_08_world_spell_bonus_data.sql
SQL
gpl-2.0
86
<html lang="en"> <head> <title>Xtensa Relaxation - Using as</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using as"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Xtensa_002dDependent.html#Xtensa_002dDependent" title="Xtensa-Dependent"> <link rel="prev" href="Xtensa-Optimizations.html#Xtensa-Optimizations" title="Xtensa Optimizations"> <link rel="next" href="Xtensa-Directives.html#Xtensa-Directives" title="Xtensa Directives"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU Assembler "as". Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <a name="Xtensa-Relaxation"></a> <p> Next:&nbsp;<a rel="next" accesskey="n" href="Xtensa-Directives.html#Xtensa-Directives">Xtensa Directives</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Xtensa-Optimizations.html#Xtensa-Optimizations">Xtensa Optimizations</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Xtensa_002dDependent.html#Xtensa_002dDependent">Xtensa-Dependent</a> <hr> </div> <h4 class="subsection">9.50.4 Xtensa Relaxation</h4> <p><a name="index-relaxation-2299"></a> When an instruction operand is outside the range allowed for that particular instruction field, <samp><span class="command">as</span></samp> can transform the code to use a functionally-equivalent instruction or sequence of instructions. This process is known as <dfn>relaxation</dfn>. This is typically done for branch instructions because the distance of the branch targets is not known until assembly-time. The Xtensa assembler offers branch relaxation and also extends this concept to function calls, <code>MOVI</code> instructions and other instructions with immediate fields. <ul class="menu"> <li><a accesskey="1" href="Xtensa-Branch-Relaxation.html#Xtensa-Branch-Relaxation">Xtensa Branch Relaxation</a>: Relaxation of Branches. <li><a accesskey="2" href="Xtensa-Call-Relaxation.html#Xtensa-Call-Relaxation">Xtensa Call Relaxation</a>: Relaxation of Function Calls. <li><a accesskey="3" href="Xtensa-Immediate-Relaxation.html#Xtensa-Immediate-Relaxation">Xtensa Immediate Relaxation</a>: Relaxation of other Immediate Fields. </ul> </body></html>
trlsmax/rk3188_kernel_tinyastro
rktools/toolchain/linaro/share/doc/gcc-linaro-arm-linux-gnueabihf/html/as.html/Xtensa-Relaxation.html
HTML
gpl-2.0
3,400
/* Copyright (C) 2011 - 2018 by Mark de Wever <koraq@xs4all.nl> Part of the Battle for Wesnoth Project https://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ #pragma once #include "gui/auxiliary/iterator/walker.hpp" #include "gui/widgets/grid.hpp" namespace gui2 { namespace iteration { /** A walker for a @ref gui2::grid. */ class grid : public walker_base { public: /** * Constructor. * * @param grid The grid which the walker is attached to. */ explicit grid(gui2::grid& grid); /** Inherited from @ref gui2::iteration::walker_base. */ virtual state_t next(const level level); /** Inherited from @ref gui2::iteration::walker_base. */ virtual bool at_end(const level level) const; /** Inherited from @ref gui2::iteration::walker_base. */ virtual gui2::widget* get(const level level); private: /** The grid which the walker is attached to. */ gui2::grid& grid_; /** * The grid which the walker is attached to. * * This variable is used to track whether the @ref * gui2::iteration::walker_base::widget level has been visited. */ gui2::widget* widget_; /** * The iterator to the children of @ref grid_. * * This variable is used to track where the @ref * gui2::iteration::walker_base::child level visiting is. */ gui2::grid::iterator itor_; }; } // namespace iteration } // namespace gui2
spixi/wesnoth
src/gui/auxiliary/iterator/walker_grid.hpp
C++
gpl-2.0
1,729
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ /* * Copyright (C) 2005 Novell, Inc. * * Nemo is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * Nemo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; see the file COPYING. If not, * write to the Free Software Foundation, Inc., 51 Franklin Street - Suite 500, * Boston, MA 02110-1335, USA. * * Author: Anders Carlsson <andersca@imendio.com> * */ #ifndef NEMO_SEARCH_ENGINE_H #define NEMO_SEARCH_ENGINE_H #include <glib-object.h> #include <libnemo-private/nemo-query.h> #define NEMO_TYPE_SEARCH_ENGINE (nemo_search_engine_get_type ()) #define NEMO_SEARCH_ENGINE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NEMO_TYPE_SEARCH_ENGINE, NemoSearchEngine)) #define NEMO_SEARCH_ENGINE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NEMO_TYPE_SEARCH_ENGINE, NemoSearchEngineClass)) #define NEMO_IS_SEARCH_ENGINE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NEMO_TYPE_SEARCH_ENGINE)) #define NEMO_IS_SEARCH_ENGINE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NEMO_TYPE_SEARCH_ENGINE)) #define NEMO_SEARCH_ENGINE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NEMO_TYPE_SEARCH_ENGINE, NemoSearchEngineClass)) typedef struct NemoSearchEngineDetails NemoSearchEngineDetails; typedef struct NemoSearchEngine { GObject parent; NemoSearchEngineDetails *details; } NemoSearchEngine; typedef struct { GObjectClass parent_class; /* VTable */ void (*set_query) (NemoSearchEngine *engine, NemoQuery *query); void (*start) (NemoSearchEngine *engine); void (*stop) (NemoSearchEngine *engine); /* Signals */ void (*hits_added) (NemoSearchEngine *engine, GList *hits); void (*hits_subtracted) (NemoSearchEngine *engine, GList *hits); void (*finished) (NemoSearchEngine *engine); void (*error) (NemoSearchEngine *engine, const char *error_message); } NemoSearchEngineClass; GType nemo_search_engine_get_type (void); gboolean nemo_search_engine_enabled (void); NemoSearchEngine* nemo_search_engine_new (void); void nemo_search_engine_set_query (NemoSearchEngine *engine, NemoQuery *query); void nemo_search_engine_start (NemoSearchEngine *engine); void nemo_search_engine_stop (NemoSearchEngine *engine); void nemo_search_engine_hits_added (NemoSearchEngine *engine, GList *hits); void nemo_search_engine_hits_subtracted (NemoSearchEngine *engine, GList *hits); void nemo_search_engine_finished (NemoSearchEngine *engine); void nemo_search_engine_error (NemoSearchEngine *engine, const char *error_message); #endif /* NEMO_SEARCH_ENGINE_H */
AlirezaNaghizadeh/nemo
libnemo-private/nemo-search-engine.h
C
gpl-2.0
3,078
# machten.sh # This file has been put together by Mark Pease <peasem@primenet.com> # Comments, questions, and improvements welcome! # # MachTen does not support dynamic loading. If you wish to, you # can fetch, compile, and install the dld package. # This ought to work with the ext/DynaLoader/dl_dld.xs in the # perl5 package. Have fun! # Some possible locations for dld: # ftp-swiss.ai.mit.edu:pub/scm/dld-3.2.7.tar.gz # prep.ai.mit.edu:/pub/gnu/jacal/dld-3.2.7.tar.gz # ftp.cs.indiana.edu:/pub/scheme-repository/imp/SCM-support/dld-3.2.7.tar.gz # tsx-11.mit.edu:/pub/linux/sources/libs/dld-3.2.7.tar.gz # # Original version was for MachTen 2.1.1. # Last modified by Andy Dougherty <doughera@lafayette.edu> # Tue Aug 13 12:31:01 EDT 1996 # # Warning about tests which no longer fail # fixed by Tom Phoenix <rootbeer@teleport.com> # March 5, 1997 # # Locale, optimization, and malloc changes by Tom Phoenix Mar 15, 1997 # # groupstype change and note about t/lib/findbin.t by Tom, Mar 24, 1997 # MachTen's ability to have valid filepaths beginning with "//" may # be causing lib/FindBin.pm to fail. I don't know how to fix it, but # the reader is encouraged to do so! :-) -- Tom # There seem to be some hard-to-diagnose problems under MachTen's # malloc, so we'll use Perl's. If you have problems which Perl's # malloc's diagnostics can't help you with, you may wish to use # MachTen's malloc after all. case "$usemymalloc" in '') usemymalloc='y' ;; esac # I (Tom Phoenix) don't know how to test for locales on MachTen. (If # you do, please fix this hints file!) But since mine didn't come # with locales working out of the box, I'll assume that's the case # for most folks. case "$d_setlocale" in '') d_setlocale=undef esac # MachTen doesn't have secure setid scripts d_suidsafe='undef' # groupstype should be gid_t, as near as I can tell, but it only # seems to work right when it's int. groupstype='int' case "$optimize" in '') optimize='-O2' ;; esac so='none' # These are useful only if you have DLD, but harmless otherwise. # Make sure gcc doesn't use -fpic. cccdlflags=' ' # That's an empty space. lddlflags='-r' dlext='o' # MachTen does not support POSIX enough to compile the POSIX module. useposix=false #MachTen might have an incomplete Berkeley DB implementation. i_db=$undef #MachTen versions 2.X have no hard links. This variable is used # by File::Find. # This will generate a harmless message: # Hmm...You had some extra variables I don't know about...I'll try to keep 'em. # Propagating recommended variable dont_use_nlink # Without this, tests io/fs #4 and op/stat #3 will fail. dont_use_nlink=define cat <<'EOM' >&4 During Configure, you may get two "WHOA THERE" messages, for $d_setlocale and $i_db being 'undef'. You may keep the undef value. At the end of Configure, you will see a harmless message Hmm...You had some extra variables I don't know about...I'll try to keep 'em. Propagating recommended variable dont_use_nlink Read the File::Find documentation for more information. It's possible that test t/lib/findbin.t will fail on some configurations of MachTen. EOM
rhuitl/uClinux
user/perl/hints/machten_2.sh
Shell
gpl-2.0
3,127
// MESSAGE POWER_STATUS PACKING package com.MAVLink.Messages.ardupilotmega; import com.MAVLink.Messages.MAVLinkMessage; import com.MAVLink.Messages.MAVLinkPacket; import com.MAVLink.Messages.MAVLinkPayload; //import android.util.Log; /** * Power supply status */ public class msg_power_status extends MAVLinkMessage{ public static final int MAVLINK_MSG_ID_POWER_STATUS = 125; public static final int MAVLINK_MSG_LENGTH = 6; private static final long serialVersionUID = MAVLINK_MSG_ID_POWER_STATUS; /** * 5V rail voltage in millivolts */ public short Vcc; /** * servo rail voltage in millivolts */ public short Vservo; /** * power supply status flags (see MAV_POWER_STATUS enum) */ public short flags; /** * Generates the payload for a mavlink message for a message of this type * @return */ public MAVLinkPacket pack(){ MAVLinkPacket packet = new MAVLinkPacket(); packet.len = MAVLINK_MSG_LENGTH; packet.sysid = 255; packet.compid = 190; packet.msgid = MAVLINK_MSG_ID_POWER_STATUS; packet.payload.putShort(Vcc); packet.payload.putShort(Vservo); packet.payload.putShort(flags); return packet; } /** * Decode a power_status message into this class fields * * @param payload The message to decode */ public void unpack(MAVLinkPayload payload) { payload.resetIndex(); Vcc = payload.getShort(); Vservo = payload.getShort(); flags = payload.getShort(); } /** * Constructor for a new message, just initializes the msgid */ public msg_power_status(){ msgid = MAVLINK_MSG_ID_POWER_STATUS; } /** * Constructor for a new message, initializes the message with the payload * from a mavlink packet * */ public msg_power_status(MAVLinkPacket mavLinkPacket){ this.sysid = mavLinkPacket.sysid; this.compid = mavLinkPacket.compid; this.msgid = MAVLINK_MSG_ID_POWER_STATUS; unpack(mavLinkPacket.payload); //Log.d("MAVLink", "POWER_STATUS"); //Log.d("MAVLINK_MSG_ID_POWER_STATUS", toString()); } /** * Returns a string with the MSG name and data */ public String toString(){ return "MAVLINK_MSG_ID_POWER_STATUS -"+" Vcc:"+Vcc+" Vservo:"+Vservo+" flags:"+flags+""; } }
TShapinsky/droidplanner
Mavlink/src/com/MAVLink/Messages/ardupilotmega/msg_power_status.java
Java
gpl-3.0
2,315
/* Copyright (c) 2001-2009, The HSQL Development Group * 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 HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * 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.hsqldb; import org.hsqldb.HsqlNameManager.HsqlName; import org.hsqldb.result.Result; import org.hsqldb.result.ResultMetaData; import org.hsqldb.store.ValuePool; /** * Implementation of Statement for simple PSM control statements. * * @author Fred Toussi (fredt@users dot sourceforge.net) * @version 1.9.0 * @since 1.9.0 */ public class StatementSimple extends Statement { String sqlState; HsqlName label; Expression expression; // ColumnSchema[] variables; int[] variableIndexes; /** * for RETURN and flow control */ StatementSimple(int type, Expression expression) { super(type, StatementTypes.X_SQL_CONTROL); isTransactionStatement = false; this.expression = expression; } StatementSimple(int type, HsqlName label) { super(type, StatementTypes.X_SQL_CONTROL); isTransactionStatement = false; this.label = label; } StatementSimple(int type, String sqlState) { super(type, StatementTypes.X_SQL_CONTROL); isTransactionStatement = false; this.sqlState = sqlState; } StatementSimple(int type, ColumnSchema[] variables, Expression e, int[] indexes) { super(type, StatementTypes.X_SQL_CONTROL); isTransactionStatement = false; this.expression = e; this.variables = variables; variableIndexes = indexes; } public String getSQL() { StringBuffer sb = new StringBuffer(); switch (type) { /** @todo 1.9.0 - add the exception */ case StatementTypes.SIGNAL : sb.append(Tokens.T_SIGNAL); break; case StatementTypes.RESIGNAL : sb.append(Tokens.T_RESIGNAL); break; case StatementTypes.ITERATE : sb.append(Tokens.T_ITERATE).append(' ').append(label); break; case StatementTypes.LEAVE : sb.append(Tokens.T_LEAVE).append(' ').append(label); break; case StatementTypes.RETURN : /* sb.append(Tokens.T_RETURN); if (expression != null) { sb.append(' ').append(expression.getSQL()); } break; */ return sql; case StatementTypes.CONDITION : sb.append(expression.getSQL()); break; case StatementTypes.ASSIGNMENT : /** @todo - cover row assignment */ sb.append(Tokens.T_SET).append(' '); sb.append(variables[0].getName().statementName).append(' '); sb.append('=').append(' ').append(expression.getSQL()); break; } return sb.toString(); } protected String describe(Session session, int blanks) { StringBuffer sb = new StringBuffer(); sb.append('\n'); for (int i = 0; i < blanks; i++) { sb.append(' '); } sb.append(Tokens.T_STATEMENT); return sb.toString(); } public Result execute(Session session) { Result result = getResult(session); if (result.isError()) { result.getException().setStatementType(group, type); } return result; } Result getResult(Session session) { switch (type) { /** @todo - check sqlState against allowed values */ case StatementTypes.SIGNAL : case StatementTypes.RESIGNAL : HsqlException ex = Error.error("sql routine error", sqlState, -1); return Result.newErrorResult(ex); case StatementTypes.ITERATE : case StatementTypes.LEAVE : case StatementTypes.RETURN : case StatementTypes.CONDITION : return this.getResultValue(session); case StatementTypes.ASSIGNMENT : { try { performAssignment(session); return Result.updateZeroResult; } catch (HsqlException e) { return Result.newErrorResult(e); } } default : throw Error.runtimeError(ErrorCode.U_S0500, ""); } } void performAssignment(Session session) { Object[] values; if (expression.getType() == OpTypes.ROW) { values = expression.getRowValue(session); } else if (expression.getType() == OpTypes.TABLE_SUBQUERY) { values = expression.subQuery.queryExpression.getSingleRowValues( session); if (values == null) { return; } } else { values = new Object[1]; values[0] = expression.getValue(session, variables[0].getDataType()); } for (int j = 0; j < values.length; j++) { Object[] data = ValuePool.emptyObjectArray; switch (variables[j].getType()) { case SchemaObject.PARAMETER : data = session.sessionContext.routineArguments; break; case SchemaObject.VARIABLE : data = session.sessionContext.routineVariables; break; } int colIndex = variableIndexes[j]; data[colIndex] = variables[j].getDataType().convertToDefaultType(session, values[j]); } } public void resolve() { boolean resolved = false; switch (type) { case StatementTypes.SIGNAL : case StatementTypes.RESIGNAL : resolved = true; break; case StatementTypes.RETURN : if (root.isProcedure()) { throw Error.error(ErrorCode.X_42602); } resolved = true; break; case StatementTypes.ITERATE : { StatementCompound statement = parent; while (statement != null) { if (statement.isLoop) { if (label == null) { resolved = true; break; } if (statement.label != null && label.name.equals(statement.label.name)) { resolved = true; break; } } statement = statement.parent; } break; } case StatementTypes.LEAVE : resolved = true; break; case StatementTypes.ASSIGNMENT : resolved = true; break; case StatementTypes.CONDITION : resolved = true; break; default : throw Error.runtimeError(ErrorCode.U_S0500, ""); } if (!resolved) { throw Error.error(ErrorCode.X_42602); } } public void setParent(StatementCompound statement) { parent = statement; } public void setRoot(Routine routine) { root = routine; } public boolean hasGeneratedColumns() { return false; } public String describe(Session session) { return ""; } private Result getResultValue(Session session) { try { Object value = null; if (expression != null) { value = expression.getValue(session); } return Result.newPSMResult(type, label == null ? null : label .name, value); } catch (HsqlException e) { return Result.newErrorResult(e); } } }
apavlo/h-store
src/hsqldb19b3/org/hsqldb/StatementSimple.java
Java
gpl-3.0
9,776
/* SPC5 HAL - Copyright (C) 2013 STMicroelectronics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file SPC5xx/ESCI_v1/hal_serial_lld.c * @brief SPC5xx low level serial driver code. * * @addtogroup SERIAL * @{ */ #include "hal.h" #if HAL_USE_SERIAL || defined(__DOXYGEN__) /*===========================================================================*/ /* Driver exported variables. */ /*===========================================================================*/ /** * @brief eSCI-A serial driver identifier. */ #if SPC5_USE_ESCIA || defined(__DOXYGEN__) SerialDriver SD1; #endif /** * @brief eSCI-B serial driver identifier. */ #if SPC5_USE_ESCIB || defined(__DOXYGEN__) SerialDriver SD2; #endif /** * @brief eSCI-C serial driver identifier. */ #if SPC5_USE_ESCIC || defined(__DOXYGEN__) SerialDriver SD3; #endif /*===========================================================================*/ /* Driver local variables and types. */ /*===========================================================================*/ /** * @brief Driver default configuration. */ static const SerialConfig default_config = { SERIAL_DEFAULT_BITRATE, SD_MODE_NORMAL | SD_MODE_PARITY_NONE }; /*===========================================================================*/ /* Driver local functions. */ /*===========================================================================*/ /** * @brief eSCI initialization. * @details This function must be invoked with interrupts disabled. * * @param[in] sdp pointer to a @p SerialDriver object * @param[in] config the architecture-dependent serial driver configuration */ static void esci_init(SerialDriver *sdp, const SerialConfig *config) { volatile struct ESCI_tag *escip = sdp->escip; uint8_t mode = config->sc_mode; escip->CR2.R = 0; /* MDIS off. */ escip->CR1.R = 0; escip->LCR.R = 0; escip->CR1.B.SBR = SPC5_SYSCLK / (16 * config->sc_speed); if (mode & SD_MODE_LOOPBACK) escip->CR1.B.LOOPS = 1; switch (mode & SD_MODE_PARITY_MASK) { case SD_MODE_PARITY_ODD: escip->CR1.B.PT = 1; case SD_MODE_PARITY_EVEN: escip->CR1.B.PE = 1; escip->CR1.B.M = 1; /* Makes it 8 bits data + 1 bit parity. */ default: ; } escip->LPR.R = 0; escip->CR1.R |= 0x0000002C; /* RIE, TE, RE to 1. */ escip->CR2.R = 0x000F; /* ORIE, NFIE, FEIE, PFIE to 1. */ } /** * @brief eSCI de-initialization. * @details This function must be invoked with interrupts disabled. * * @param[in] escip pointer to an eSCI I/O block */ static void esci_deinit(volatile struct ESCI_tag *escip) { escip->LPR.R = 0; escip->SR.R = 0xFFFFFFFF; escip->CR1.R = 0; escip->CR2.R = 0x8000; /* MDIS on. */ } /** * @brief Error handling routine. * * @param[in] sdp pointer to a @p SerialDriver object * @param[in] sr eSCI SR register value */ static void set_error(SerialDriver *sdp, uint32_t sr) { eventflags_t sts = 0; if (sr & 0x08000000) sts |= SD_OVERRUN_ERROR; if (sr & 0x04000000) sts |= SD_NOISE_ERROR; if (sr & 0x02000000) sts |= SD_FRAMING_ERROR; if (sr & 0x01000000) sts |= SD_PARITY_ERROR; /* if (sr & 0x00000000) sts |= SD_BREAK_DETECTED;*/ osalSysLockFromISR(); chnAddFlagsI(sdp, sts); osalSysUnlockFromISR(); } /** * @brief Common IRQ handler. * * @param[in] sdp pointer to a @p SerialDriver object */ static void serve_interrupt(SerialDriver *sdp) { volatile struct ESCI_tag *escip = sdp->escip; uint32_t sr = escip->SR.R; escip->SR.R = 0x3FFFFFFF; /* Does not clear TDRE | TC.*/ if (sr & 0x0F000000) /* OR | NF | FE | PF. */ set_error(sdp, sr); if (sr & 0x20000000) { /* RDRF. */ osalSysLockFromISR(); sdIncomingDataI(sdp, escip->DR.B.D); osalSysUnlockFromISR(); } if (escip->CR1.B.TIE && (sr & 0x80000000)) { /* TDRE. */ msg_t b; osalSysLockFromISR(); b = oqGetI(&sdp->oqueue); if (b < Q_OK) { chnAddFlagsI(sdp, CHN_OUTPUT_EMPTY); escip->CR1.B.TIE = 0; } else { escip->SR.B.TDRE = 1; escip->DR.R = (uint16_t)b; } osalSysUnlockFromISR(); } } #if SPC5_USE_ESCIA || defined(__DOXYGEN__) static void notify1(io_queue_t *qp) { (void)qp; if (ESCI_A.SR.B.TDRE) { msg_t b = sdRequestDataI(&SD1); if (b != Q_EMPTY) { ESCI_A.SR.B.TDRE = 1; ESCI_A.CR1.B.TIE = 1; ESCI_A.DR.R = (uint16_t)b; } } } #endif #if SPC5_USE_ESCIB || defined(__DOXYGEN__) static void notify2(io_queue_t *qp) { (void)qp; if (ESCI_B.SR.B.TDRE) { msg_t b = sdRequestDataI(&SD2); if (b != Q_EMPTY) { ESCI_B.SR.B.TDRE = 1; ESCI_B.CR1.B.TIE = 1; ESCI_B.DR.R = (uint16_t)b; } } } #endif #if SPC5_USE_ESCIC || defined(__DOXYGEN__) static void notify3(io_queue_t *qp) { (void)qp; if (ESCI_C.SR.B.TDRE) { msg_t b = sdRequestDataI(&SD3); if (b != Q_EMPTY) { ESCI_C.SR.B.TDRE = 1; ESCI_C.CR1.B.TIE = 1; ESCI_C.DR.R = (uint16_t)b; } } } #endif /*===========================================================================*/ /* Driver interrupt handlers. */ /*===========================================================================*/ #if SPC5_USE_ESCIA || defined(__DOXYGEN__) #if !defined(SPC5_ESCIA_HANDLER) #error "SPC5_ESCIA_HANDLER not defined" #endif /** * @brief eSCI-A interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_ESCIA_HANDLER) { OSAL_IRQ_PROLOGUE(); serve_interrupt(&SD1); OSAL_IRQ_EPILOGUE(); } #endif #if SPC5_USE_ESCIB || defined(__DOXYGEN__) #if !defined(SPC5_ESCIB_HANDLER) #error "SPC5_ESCIB_HANDLER not defined" #endif /** * @brief eSCI-B interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_ESCIB_HANDLER) { OSAL_IRQ_PROLOGUE(); serve_interrupt(&SD2); OSAL_IRQ_EPILOGUE(); } #endif #if SPC5_USE_ESCIC || defined(__DOXYGEN__) #if !defined(SPC5_ESCIC_HANDLER) #error "SPC5_ESCIC_HANDLER not defined" #endif /** * @brief eSCI-C interrupt handler. * * @isr */ OSAL_IRQ_HANDLER(SPC5_ESCIC_HANDLER) { OSAL_IRQ_PROLOGUE(); serve_interrupt(&SD3); OSAL_IRQ_EPILOGUE(); } #endif /*===========================================================================*/ /* Driver exported functions. */ /*===========================================================================*/ /** * @brief Low level serial driver initialization. * * @notapi */ void sd_lld_init(void) { #if SPC5_USE_ESCIA sdObjectInit(&SD1, NULL, notify1); SD1.escip = &ESCI_A; ESCI_A.CR2.R = 0x8000; /* MDIS ON. */ INTC.PSR[SPC5_ESCIA_NUMBER].R = SPC5_ESCIA_PRIORITY; #endif #if SPC5_USE_ESCIB sdObjectInit(&SD2, NULL, notify2); SD2.escip = &ESCI_B; ESCI_B.CR2.R = 0x8000; /* MDIS ON. */ INTC.PSR[SPC5_ESCIB_NUMBER].R = SPC5_ESCIB_PRIORITY; #endif #if SPC5_USE_ESCIC sdObjectInit(&SD3, NULL, notify3); SD3.escip = &ESCI_C; ESCI_C.CR2.R = 0x8000; /* MDIS ON. */ INTC.PSR[SPC5_ESCIC_NUMBER].R = SPC5_ESCIC_PRIORITY; #endif } /** * @brief Low level serial driver configuration and (re)start. * * @param[in] sdp pointer to a @p SerialDriver object * @param[in] config the architecture-dependent serial driver configuration. * If this parameter is set to @p NULL then a default * configuration is used. * * @notapi */ void sd_lld_start(SerialDriver *sdp, const SerialConfig *config) { if (config == NULL) config = &default_config; esci_init(sdp, config); } /** * @brief Low level serial driver stop. * * @param[in] sdp pointer to a @p SerialDriver object * * @notapi */ void sd_lld_stop(SerialDriver *sdp) { if (sdp->state == SD_READY) esci_deinit(sdp->escip); } #endif /* HAL_USE_SERIAL */ /** @} */
netik/chibios-orchard
os/hal/ports/SPC5/SPC5xx/ESCI_v1/hal_serial_lld.c
C
gpl-3.0
9,199
<?php /* * Copyright 2014 Google Inc. * * 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. */ /** * The "projects" collection of methods. * Typical usage is: * <code> * $secretmanagerService = new Google_Service_SecretManager(...); * $projects = $secretmanagerService->projects; * </code> */ class Google_Service_SecretManager_Resource_Projects extends Google_Service_Resource { }
ftisunpar/BlueTape
vendor/google/apiclient-services/src/Google/Service/SecretManager/Resource/Projects.php
PHP
gpl-3.0
898
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD * license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Handler.js * @requires OpenLayers/Geometry/Point.js */ /** * Class: OpenLayers.Handler.Point * Handler to draw a point on the map. Point is displayed on mouse down, * moves on mouse move, and is finished on mouse up. The handler triggers * callbacks for 'done', 'cancel', and 'modify'. The modify callback is * called with each change in the sketch and will receive the latest point * drawn. Create a new instance with the <OpenLayers.Handler.Point> * constructor. * * Inherits from: * - <OpenLayers.Handler> */ OpenLayers.Handler.Point = OpenLayers.Class(OpenLayers.Handler, { /** * Property: point * {<OpenLayers.Feature.Vector>} The currently drawn point */ point: null, /** * Property: layer * {<OpenLayers.Layer.Vector>} The temporary drawing layer */ layer: null, /** * APIProperty: multi * {Boolean} Cast features to multi-part geometries before passing to the * layer. Default is false. */ multi: false, /** * Property: drawing * {Boolean} A point is being drawn */ drawing: false, /** * Property: mouseDown * {Boolean} The mouse is down */ mouseDown: false, /** * Property: lastDown * {<OpenLayers.Pixel>} Location of the last mouse down */ lastDown: null, /** * Property: lastUp * {<OpenLayers.Pixel>} */ lastUp: null, /** * APIProperty: persist * {Boolean} Leave the feature rendered until destroyFeature is called. * Default is false. If set to true, the feature remains rendered until * destroyFeature is called, typically by deactivating the handler or * starting another drawing. */ persist: false, /** * Property: layerOptions * {Object} Any optional properties to be set on the sketch layer. */ layerOptions: null, /** * Constructor: OpenLayers.Handler.Point * Create a new point handler. * * Parameters: * control - {<OpenLayers.Control>} The control that owns this handler * callbacks - {Object} An object with a properties whose values are * functions. Various callbacks described below. * options - {Object} An optional object with properties to be set on the * handler * * Named callbacks: * create - Called when a sketch is first created. Callback called with * the creation point geometry and sketch feature. * modify - Called with each move of a vertex with the vertex (point) * geometry and the sketch feature. * done - Called when the point drawing is finished. The callback will * recieve a single argument, the point geometry. * cancel - Called when the handler is deactivated while drawing. The * cancel callback will receive a geometry. */ initialize: function(control, callbacks, options) { if(!(options && options.layerOptions && options.layerOptions.styleMap)) { this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {}); } OpenLayers.Handler.prototype.initialize.apply(this, arguments); }, /** * APIMethod: activate * turn on the handler */ activate: function() { if(!OpenLayers.Handler.prototype.activate.apply(this, arguments)) { return false; } // create temporary vector layer for rendering geometry sketch // TBD: this could be moved to initialize/destroy - setting visibility here var options = OpenLayers.Util.extend({ displayInLayerSwitcher: false, // indicate that the temp vector layer will never be out of range // without this, resolution properties must be specified at the // map-level for this temporary layer to init its resolutions // correctly calculateInRange: OpenLayers.Function.True }, this.layerOptions); this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options); this.map.addLayer(this.layer); return true; }, /** * Method: createFeature * Add temporary features * * Parameters: * pixel - {<OpenLayers.Pixel>} A pixel location on the map. */ createFeature: function(pixel) { var lonlat = this.map.getLonLatFromPixel(pixel); this.point = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat) ); this.callback("create", [this.point.geometry, this.point]); this.point.geometry.clearBounds(); this.layer.addFeatures([this.point], {silent: true}); }, /** * APIMethod: deactivate * turn off the handler */ deactivate: function() { if(!OpenLayers.Handler.prototype.deactivate.apply(this, arguments)) { return false; } // call the cancel callback if mid-drawing if(this.drawing) { this.cancel(); } this.destroyFeature(); // If a layer's map property is set to null, it means that that layer // isn't added to the map. Since we ourself added the layer to the map // in activate(), we can assume that if this.layer.map is null it means // that the layer has been destroyed (as a result of map.destroy() for // example. if (this.layer.map != null) { this.layer.destroy(false); } this.layer = null; return true; }, /** * Method: destroyFeature * Destroy the temporary geometries */ destroyFeature: function() { if(this.layer) { this.layer.destroyFeatures(); } this.point = null; }, /** * Method: finalize * Finish the geometry and call the "done" callback. * * Parameters: * cancel - {Boolean} Call cancel instead of done callback. Default is * false. */ finalize: function(cancel) { var key = cancel ? "cancel" : "done"; this.drawing = false; this.mouseDown = false; this.lastDown = null; this.lastUp = null; this.callback(key, [this.geometryClone()]); if(cancel || !this.persist) { this.destroyFeature(); } }, /** * APIMethod: cancel * Finish the geometry and call the "cancel" callback. */ cancel: function() { this.finalize(true); }, /** * Method: click * Handle clicks. Clicks are stopped from propagating to other listeners * on map.events or other dom elements. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ click: function(evt) { OpenLayers.Event.stop(evt); return false; }, /** * Method: dblclick * Handle double-clicks. Double-clicks are stopped from propagating to other * listeners on map.events or other dom elements. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ dblclick: function(evt) { OpenLayers.Event.stop(evt); return false; }, /** * Method: modifyFeature * Modify the existing geometry given a pixel location. * * Parameters: * pixel - {<OpenLayers.Pixel>} A pixel location on the map. */ modifyFeature: function(pixel) { var lonlat = this.map.getLonLatFromPixel(pixel); this.point.geometry.x = lonlat.lon; this.point.geometry.y = lonlat.lat; this.callback("modify", [this.point.geometry, this.point]); this.point.geometry.clearBounds(); this.drawFeature(); }, /** * Method: drawFeature * Render features on the temporary layer. */ drawFeature: function() { this.layer.drawFeature(this.point, this.style); }, /** * Method: getGeometry * Return the sketch geometry. If <multi> is true, this will return * a multi-part geometry. * * Returns: * {<OpenLayers.Geometry.Point>} */ getGeometry: function() { var geometry = this.point && this.point.geometry; if(geometry && this.multi) { geometry = new OpenLayers.Geometry.MultiPoint([geometry]); } return geometry; }, /** * Method: geometryClone * Return a clone of the relevant geometry. * * Returns: * {<OpenLayers.Geometry>} */ geometryClone: function() { var geom = this.getGeometry(); return geom && geom.clone(); }, /** * Method: mousedown * Handle mouse down. Adjust the geometry and redraw. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mousedown: function(evt) { // check keyboard modifiers if(!this.checkModifiers(evt)) { return true; } // ignore double-clicks if(this.lastDown && this.lastDown.equals(evt.xy)) { return true; } this.drawing = true; if(this.lastDown == null) { if(this.persist) { this.destroyFeature(); } this.createFeature(evt.xy); } else { this.modifyFeature(evt.xy); } this.lastDown = evt.xy; return false; }, /** * Method: mousemove * Handle mouse move. Adjust the geometry and redraw. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mousemove: function (evt) { if(this.drawing) { this.modifyFeature(evt.xy); } return true; }, /** * Method: mouseup * Handle mouse up. Send the latest point in the geometry to the control. * Return determines whether to propagate the event on the map. * * Parameters: * evt - {Event} The browser event * * Returns: * {Boolean} Allow event propagation */ mouseup: function (evt) { if(this.drawing) { this.finalize(); return false; } else { return true; } }, CLASS_NAME: "OpenLayers.Handler.Point" });
guolivar/totus-niwa
web/js/libs/openlayers/lib/OpenLayers/Handler/Point.js
JavaScript
gpl-3.0
10,858
/*********************************************** Copyright 2010, Chris Winberry <chris@winberry.net>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***********************************************/ /* v1.7.2 */ (function () { function runningInNode () { return( (typeof require) == "function" && (typeof exports) == "object" && (typeof module) == "object" && (typeof __filename) == "string" && (typeof __dirname) == "string" ); } if (!runningInNode()) { if (!this.Tautologistics) this.Tautologistics = {}; else if (this.Tautologistics.NodeHtmlParser) return; //NodeHtmlParser already defined! this.Tautologistics.NodeHtmlParser = {}; exports = this.Tautologistics.NodeHtmlParser; } //Types of elements found in the DOM var ElementType = { Text: "text" //Plain text , Directive: "directive" //Special tag <!...> , Comment: "comment" //Special tag <!--...--> , Script: "script" //Special tag <script>...</script> , Style: "style" //Special tag <style>...</style> , Tag: "tag" //Any tag that isn't special } function Parser (handler, options) { this._options = options ? options : { }; if (this._options.includeLocation == undefined) { this._options.includeLocation = false; //Do not track element position in document by default } this.validateHandler(handler); this._handler = handler; this.reset(); } //**"Static"**// //Regular expressions used for cleaning up and parsing (stateless) Parser._reTrim = /(^\s+|\s+$)/g; //Trim leading/trailing whitespace Parser._reTrimComment = /(^\!--|--$)/g; //Remove comment tag markup from comment contents Parser._reWhitespace = /\s/g; //Used to find any whitespace to split on Parser._reTagName = /^\s*(\/?)\s*([^\s\/]+)/; //Used to find the tag name for an element //Regular expressions used for parsing (stateful) Parser._reAttrib = //Find attributes in a tag /([^=<>\"\'\s]+)\s*=\s*"([^"]*)"|([^=<>\"\'\s]+)\s*=\s*'([^']*)'|([^=<>\"\'\s]+)\s*=\s*([^'"\s]+)|([^=<>\"\'\s\/]+)/g; Parser._reTags = /[\<\>]/g; //Find tag markers //**Public**// //Methods// //Parses a complete HTML and pushes it to the handler Parser.prototype.parseComplete = function Parser$parseComplete (data) { this.reset(); this.parseChunk(data); this.done(); } //Parses a piece of an HTML document Parser.prototype.parseChunk = function Parser$parseChunk (data) { if (this._done) this.handleError(new Error("Attempted to parse chunk after parsing already done")); this._buffer += data; //FIXME: this can be a bottleneck this.parseTags(); } //Tells the parser that the HTML being parsed is complete Parser.prototype.done = function Parser$done () { if (this._done) return; this._done = true; //Push any unparsed text into a final element in the element list if (this._buffer.length) { var rawData = this._buffer; this._buffer = ""; var element = { raw: rawData , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") , type: this._parseState }; if (this._parseState == ElementType.Tag || this._parseState == ElementType.Script || this._parseState == ElementType.Style) element.name = this.parseTagName(element.data); this.parseAttribs(element); this._elements.push(element); } this.writeHandler(); this._handler.done(); } //Resets the parser to a blank state, ready to parse a new HTML document Parser.prototype.reset = function Parser$reset () { this._buffer = ""; this._done = false; this._elements = []; this._elementsCurrent = 0; this._current = 0; this._next = 0; this._location = { row: 0 , col: 0 , charOffset: 0 , inBuffer: 0 }; this._parseState = ElementType.Text; this._prevTagSep = ''; this._tagStack = []; this._handler.reset(); } //**Private**// //Properties// Parser.prototype._options = null; //Parser options for how to behave Parser.prototype._handler = null; //Handler for parsed elements Parser.prototype._buffer = null; //Buffer of unparsed data Parser.prototype._done = false; //Flag indicating whether parsing is done Parser.prototype._elements = null; //Array of parsed elements Parser.prototype._elementsCurrent = 0; //Pointer to last element in _elements that has been processed Parser.prototype._current = 0; //Position in data that has already been parsed Parser.prototype._next = 0; //Position in data of the next tag marker (<>) Parser.prototype._location = null; //Position tracking for elements in a stream Parser.prototype._parseState = ElementType.Text; //Current type of element being parsed Parser.prototype._prevTagSep = ''; //Previous tag marker found //Stack of element types previously encountered; keeps track of when //parsing occurs inside a script/comment/style tag Parser.prototype._tagStack = null; //Methods// //Takes an array of elements and parses any found attributes Parser.prototype.parseTagAttribs = function Parser$parseTagAttribs (elements) { var idxEnd = elements.length; var idx = 0; while (idx < idxEnd) { var element = elements[idx++]; if (element.type == ElementType.Tag || element.type == ElementType.Script || element.type == ElementType.style) this.parseAttribs(element); } return(elements); } //Takes an element and adds an "attribs" property for any element attributes found Parser.prototype.parseAttribs = function Parser$parseAttribs (element) { //Only parse attributes for tags if (element.type != ElementType.Script && element.type != ElementType.Style && element.type != ElementType.Tag) return; var tagName = element.data.split(Parser._reWhitespace, 1)[0]; var attribRaw = element.data.substring(tagName.length); if (attribRaw.length < 1) return; var match; Parser._reAttrib.lastIndex = 0; while (match = Parser._reAttrib.exec(attribRaw)) { if (element.attribs == undefined) element.attribs = {}; if (typeof match[1] == "string" && match[1].length) { element.attribs[match[1]] = match[2]; } else if (typeof match[3] == "string" && match[3].length) { element.attribs[match[3].toString()] = match[4].toString(); } else if (typeof match[5] == "string" && match[5].length) { element.attribs[match[5]] = match[6]; } else if (typeof match[7] == "string" && match[7].length) { element.attribs[match[7]] = match[7]; } } } //Extracts the base tag name from the data value of an element Parser.prototype.parseTagName = function Parser$parseTagName (data) { if (data == null || data == "") return(""); var match = Parser._reTagName.exec(data); if (!match) return(""); return((match[1] ? "/" : "") + match[2]); } //Parses through HTML text and returns an array of found elements //I admit, this function is rather large but splitting up had an noticeable impact on speed Parser.prototype.parseTags = function Parser$parseTags () { var bufferEnd = this._buffer.length - 1; while (Parser._reTags.test(this._buffer)) { this._next = Parser._reTags.lastIndex - 1; var tagSep = this._buffer.charAt(this._next); //The currently found tag marker var rawData = this._buffer.substring(this._current, this._next); //The next chunk of data to parse //A new element to eventually be appended to the element list var element = { raw: rawData , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(Parser._reTrim, "") , type: this._parseState }; var elementName = this.parseTagName(element.data); //This section inspects the current tag stack and modifies the current //element if we're actually parsing a special area (script/comment/style tag) if (this._tagStack.length) { //We're parsing inside a script/comment/style tag if (this._tagStack[this._tagStack.length - 1] == ElementType.Script) { //We're currently in a script tag if (elementName == "/script") //Actually, we're no longer in a script tag, so pop it off the stack this._tagStack.pop(); else { //Not a closing script tag if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment //All data from here to script close is now a text element element.type = ElementType.Text; //If the previous element is text, append the current text to it if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { var prevElement = this._elements[this._elements.length - 1]; prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; element.raw = element.data = ""; //This causes the current element to not be added to the element list } } } } else if (this._tagStack[this._tagStack.length - 1] == ElementType.Style) { //We're currently in a style tag if (elementName == "/style") //Actually, we're no longer in a style tag, so pop it off the stack this._tagStack.pop(); else { if (element.raw.indexOf("!--") != 0) { //Make sure we're not in a comment //All data from here to style close is now a text element element.type = ElementType.Text; //If the previous element is text, append the current text to it if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) { var prevElement = this._elements[this._elements.length - 1]; if (element.raw != "") { prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw; element.raw = element.data = ""; //This causes the current element to not be added to the element list } else { //Element is empty, so just append the last tag marker found prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep; } } else { //The previous element was not text if (element.raw != "") { element.raw = element.data = element.raw; } } } } } else if (this._tagStack[this._tagStack.length - 1] == ElementType.Comment) { //We're currently in a comment tag var rawLen = element.raw.length; if (element.raw.charAt(rawLen - 2) == "-" && element.raw.charAt(rawLen - 1) == "-" && tagSep == ">") { //Actually, we're no longer in a style tag, so pop it off the stack this._tagStack.pop(); //If the previous element is a comment, append the current text to it if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { var prevElement = this._elements[this._elements.length - 1]; prevElement.raw = prevElement.data = (prevElement.raw + element.raw).replace(Parser._reTrimComment, ""); element.raw = element.data = ""; //This causes the current element to not be added to the element list element.type = ElementType.Text; } else //Previous element not a comment element.type = ElementType.Comment; //Change the current element's type to a comment } else { //Still in a comment tag element.type = ElementType.Comment; //If the previous element is a comment, append the current text to it if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) { var prevElement = this._elements[this._elements.length - 1]; prevElement.raw = prevElement.data = prevElement.raw + element.raw + tagSep; element.raw = element.data = ""; //This causes the current element to not be added to the element list element.type = ElementType.Text; } else element.raw = element.data = element.raw + tagSep; } } } //Processing of non-special tags if (element.type == ElementType.Tag) { element.name = elementName; if (element.raw.indexOf("!--") == 0) { //This tag is really comment element.type = ElementType.Comment; delete element["name"]; var rawLen = element.raw.length; //Check if the comment is terminated in the current element if (element.raw.charAt(rawLen - 1) == "-" && element.raw.charAt(rawLen - 2) == "-" && tagSep == ">") element.raw = element.data = element.raw.replace(Parser._reTrimComment, ""); else { //It's not so push the comment onto the tag stack element.raw += tagSep; this._tagStack.push(ElementType.Comment); } } else if (element.raw.indexOf("!") == 0 || element.raw.indexOf("?") == 0) { element.type = ElementType.Directive; //TODO: what about CDATA? } else if (element.name == "script") { element.type = ElementType.Script; //Special tag, push onto the tag stack if not terminated if (element.data.charAt(element.data.length - 1) != "/") this._tagStack.push(ElementType.Script); } else if (element.name == "/script") element.type = ElementType.Script; else if (element.name == "style") { element.type = ElementType.Style; //Special tag, push onto the tag stack if not terminated if (element.data.charAt(element.data.length - 1) != "/") this._tagStack.push(ElementType.Style); } else if (element.name == "/style") element.type = ElementType.Style; if (element.name && element.name.charAt(0) == "/") element.data = element.name; } //Add all tags and non-empty text elements to the element list if (element.raw != "" || element.type != ElementType.Text) { if (this._options.includeLocation && !element.location) { element.location = this.getLocation(element.type == ElementType.Tag); } this.parseAttribs(element); this._elements.push(element); //If tag self-terminates, add an explicit, separate closing tag if ( element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive && element.data.charAt(element.data.length - 1) == "/" ) this._elements.push({ raw: "/" + element.name , data: "/" + element.name , name: "/" + element.name , type: element.type }); } this._parseState = (tagSep == "<") ? ElementType.Tag : ElementType.Text; this._current = this._next + 1; this._prevTagSep = tagSep; } if (this._options.includeLocation) { this.getLocation(); this._location.row += this._location.inBuffer; this._location.inBuffer = 0; this._location.charOffset = 0; } this._buffer = (this._current <= bufferEnd) ? this._buffer.substring(this._current) : ""; this._current = 0; this.writeHandler(); } Parser.prototype.getLocation = function Parser$getLocation (startTag) { var c, l = this._location, end = this._current - (startTag ? 1 : 0), chunk = startTag && l.charOffset == 0 && this._current == 0; for (; l.charOffset < end; l.charOffset++) { c = this._buffer.charAt(l.charOffset); if (c == '\n') { l.inBuffer++; l.col = 0; } else if (c != '\r') { l.col++; } } return { line: l.row + l.inBuffer + 1 , col: l.col + (chunk ? 0: 1) }; } //Checks the handler to make it is an object with the right "interface" Parser.prototype.validateHandler = function Parser$validateHandler (handler) { if ((typeof handler) != "object") throw new Error("Handler is not an object"); if ((typeof handler.reset) != "function") throw new Error("Handler method 'reset' is invalid"); if ((typeof handler.done) != "function") throw new Error("Handler method 'done' is invalid"); if ((typeof handler.writeTag) != "function") throw new Error("Handler method 'writeTag' is invalid"); if ((typeof handler.writeText) != "function") throw new Error("Handler method 'writeText' is invalid"); if ((typeof handler.writeComment) != "function") throw new Error("Handler method 'writeComment' is invalid"); if ((typeof handler.writeDirective) != "function") throw new Error("Handler method 'writeDirective' is invalid"); } //Writes parsed elements out to the handler Parser.prototype.writeHandler = function Parser$writeHandler (forceFlush) { forceFlush = !!forceFlush; if (this._tagStack.length && !forceFlush) return; while (this._elements.length) { var element = this._elements.shift(); switch (element.type) { case ElementType.Comment: this._handler.writeComment(element); break; case ElementType.Directive: this._handler.writeDirective(element); break; case ElementType.Text: this._handler.writeText(element); break; default: this._handler.writeTag(element); break; } } } Parser.prototype.handleError = function Parser$handleError (error) { if ((typeof this._handler.error) == "function") this._handler.error(error); else throw error; } //TODO: make this a trully streamable handler function RssHandler (callback) { RssHandler.super_.call(this, callback, { ignoreWhitespace: true, verbose: false, enforceEmptyTags: false }); } inherits(RssHandler, DefaultHandler); RssHandler.prototype.done = function RssHandler$done () { var feed = { }; var feedRoot; var found = DomUtils.getElementsByTagName(function (value) { return(value == "rss" || value == "feed"); }, this.dom, false); if (found.length) { feedRoot = found[0]; } if (feedRoot) { if (feedRoot.name == "rss") { feed.type = "rss"; feedRoot = feedRoot.children[0]; //<channel/> feed.id = ""; try { feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; } catch (ex) { } try { feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].children[0].data; } catch (ex) { } try { feed.description = DomUtils.getElementsByTagName("description", feedRoot.children, false)[0].children[0].data; } catch (ex) { } try { feed.updated = new Date(DomUtils.getElementsByTagName("lastBuildDate", feedRoot.children, false)[0].children[0].data); } catch (ex) { } try { feed.author = DomUtils.getElementsByTagName("managingEditor", feedRoot.children, false)[0].children[0].data; } catch (ex) { } feed.items = []; DomUtils.getElementsByTagName("item", feedRoot.children).forEach(function (item, index, list) { var entry = {}; try { entry.id = DomUtils.getElementsByTagName("guid", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.description = DomUtils.getElementsByTagName("description", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.pubDate = new Date(DomUtils.getElementsByTagName("pubDate", item.children, false)[0].children[0].data); } catch (ex) { } feed.items.push(entry); }); } else { feed.type = "atom"; try { feed.id = DomUtils.getElementsByTagName("id", feedRoot.children, false)[0].children[0].data; } catch (ex) { } try { feed.title = DomUtils.getElementsByTagName("title", feedRoot.children, false)[0].children[0].data; } catch (ex) { } try { feed.link = DomUtils.getElementsByTagName("link", feedRoot.children, false)[0].attribs.href; } catch (ex) { } try { feed.description = DomUtils.getElementsByTagName("subtitle", feedRoot.children, false)[0].children[0].data; } catch (ex) { } try { feed.updated = new Date(DomUtils.getElementsByTagName("updated", feedRoot.children, false)[0].children[0].data); } catch (ex) { } try { feed.author = DomUtils.getElementsByTagName("email", feedRoot.children, true)[0].children[0].data; } catch (ex) { } feed.items = []; DomUtils.getElementsByTagName("entry", feedRoot.children).forEach(function (item, index, list) { var entry = {}; try { entry.id = DomUtils.getElementsByTagName("id", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.title = DomUtils.getElementsByTagName("title", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.link = DomUtils.getElementsByTagName("link", item.children, false)[0].attribs.href; } catch (ex) { } try { entry.description = DomUtils.getElementsByTagName("summary", item.children, false)[0].children[0].data; } catch (ex) { } try { entry.pubDate = new Date(DomUtils.getElementsByTagName("updated", item.children, false)[0].children[0].data); } catch (ex) { } feed.items.push(entry); }); } this.dom = feed; } RssHandler.super_.prototype.done.call(this); } /////////////////////////////////////////////////// function DefaultHandler (callback, options) { this.reset(); this._options = options ? options : { }; if (this._options.ignoreWhitespace == undefined) this._options.ignoreWhitespace = false; //Keep whitespace-only text nodes if (this._options.verbose == undefined) this._options.verbose = true; //Keep data property for tags and raw property for all if (this._options.enforceEmptyTags == undefined) this._options.enforceEmptyTags = true; //Don't allow children for HTML tags defined as empty in spec if ((typeof callback) == "function") this._callback = callback; } //**"Static"**// //HTML Tags that shouldn't contain child nodes DefaultHandler._emptyTags = { area: 1 , base: 1 , basefont: 1 , br: 1 , col: 1 , frame: 1 , hr: 1 , img: 1 , input: 1 , isindex: 1 , link: 1 , meta: 1 , param: 1 , embed: 1 } //Regex to detect whitespace only text nodes DefaultHandler.reWhitespace = /^\s*$/; //**Public**// //Properties// DefaultHandler.prototype.dom = null; //The hierarchical object containing the parsed HTML //Methods// //Resets the handler back to starting state DefaultHandler.prototype.reset = function DefaultHandler$reset() { this.dom = []; this._done = false; this._tagStack = []; this._tagStack.last = function DefaultHandler$_tagStack$last () { return(this.length ? this[this.length - 1] : null); } } //Signals the handler that parsing is done DefaultHandler.prototype.done = function DefaultHandler$done () { this._done = true; this.handleCallback(null); } DefaultHandler.prototype.writeTag = function DefaultHandler$writeTag (element) { this.handleElement(element); } DefaultHandler.prototype.writeText = function DefaultHandler$writeText (element) { if (this._options.ignoreWhitespace) if (DefaultHandler.reWhitespace.test(element.data)) return; this.handleElement(element); } DefaultHandler.prototype.writeComment = function DefaultHandler$writeComment (element) { this.handleElement(element); } DefaultHandler.prototype.writeDirective = function DefaultHandler$writeDirective (element) { this.handleElement(element); } DefaultHandler.prototype.error = function DefaultHandler$error (error) { this.handleCallback(error); } //**Private**// //Properties// DefaultHandler.prototype._options = null; //Handler options for how to behave DefaultHandler.prototype._callback = null; //Callback to respond to when parsing done DefaultHandler.prototype._done = false; //Flag indicating whether handler has been notified of parsing completed DefaultHandler.prototype._tagStack = null; //List of parents to the currently element being processed //Methods// DefaultHandler.prototype.handleCallback = function DefaultHandler$handleCallback (error) { if ((typeof this._callback) != "function") if (error) throw error; else return; this._callback(error, this.dom); } DefaultHandler.prototype.isEmptyTag = function(element) { var name = element.name.toLowerCase(); if (name.charAt(0) == '/') { name = name.substring(1); } return this._options.enforceEmptyTags && !!DefaultHandler._emptyTags[name]; }; DefaultHandler.prototype.handleElement = function DefaultHandler$handleElement (element) { if (this._done) this.handleCallback(new Error("Writing to the handler after done() called is not allowed without a reset()")); if (!this._options.verbose) { // element.raw = null; //FIXME: Not clean //FIXME: Serious performance problem using delete delete element.raw; if (element.type == "tag" || element.type == "script" || element.type == "style") delete element.data; } if (!this._tagStack.last()) { //There are no parent elements //If the element can be a container, add it to the tag stack and the top level list if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { if (element.name.charAt(0) != "/") { //Ignore closing tags that obviously don't have an opening tag this.dom.push(element); if (!this.isEmptyTag(element)) { //Don't add tags to the tag stack that can't have children this._tagStack.push(element); } } } else //Otherwise just add to the top level list this.dom.push(element); } else { //There are parent elements //If the element can be a container, add it as a child of the element //on top of the tag stack and then add it to the tag stack if (element.type != ElementType.Text && element.type != ElementType.Comment && element.type != ElementType.Directive) { if (element.name.charAt(0) == "/") { //This is a closing tag, scan the tagStack to find the matching opening tag //and pop the stack up to the opening tag's parent var baseName = element.name.substring(1); if (!this.isEmptyTag(element)) { var pos = this._tagStack.length - 1; while (pos > -1 && this._tagStack[pos--].name != baseName) { } if (pos > -1 || this._tagStack[0].name == baseName) while (pos < this._tagStack.length - 1) this._tagStack.pop(); } } else { //This is not a closing tag if (!this._tagStack.last().children) this._tagStack.last().children = []; this._tagStack.last().children.push(element); if (!this.isEmptyTag(element)) //Don't add tags to the tag stack that can't have children this._tagStack.push(element); } } else { //This is not a container element if (!this._tagStack.last().children) this._tagStack.last().children = []; this._tagStack.last().children.push(element); } } } var DomUtils = { testElement: function DomUtils$testElement (options, element) { if (!element) { return false; } for (var key in options) { if (key == "tag_name") { if (element.type != "tag" && element.type != "script" && element.type != "style") { return false; } if (!options["tag_name"](element.name)) { return false; } } else if (key == "tag_type") { if (!options["tag_type"](element.type)) { return false; } } else if (key == "tag_contains") { if (element.type != "text" && element.type != "comment" && element.type != "directive") { return false; } if (!options["tag_contains"](element.data)) { return false; } } else { if (!element.attribs || !options[key](element.attribs[key])) { return false; } } } return true; } , getElements: function DomUtils$getElements (options, currentElement, recurse, limit) { recurse = (recurse === undefined || recurse === null) || !!recurse; limit = isNaN(parseInt(limit)) ? -1 : parseInt(limit); if (!currentElement) { return([]); } var found = []; var elementList; function getTest (checkVal) { return(function (value) { return(value == checkVal); }); } for (var key in options) { if ((typeof options[key]) != "function") { options[key] = getTest(options[key]); } } if (DomUtils.testElement(options, currentElement)) { found.push(currentElement); } if (limit >= 0 && found.length >= limit) { return(found); } if (recurse && currentElement.children) { elementList = currentElement.children; } else if (currentElement instanceof Array) { elementList = currentElement; } else { return(found); } for (var i = 0; i < elementList.length; i++) { found = found.concat(DomUtils.getElements(options, elementList[i], recurse, limit)); if (limit >= 0 && found.length >= limit) { break; } } return(found); } , getElementById: function DomUtils$getElementById (id, currentElement, recurse) { var result = DomUtils.getElements({ id: id }, currentElement, recurse, 1); return(result.length ? result[0] : null); } , getElementsByTagName: function DomUtils$getElementsByTagName (name, currentElement, recurse, limit) { return(DomUtils.getElements({ tag_name: name }, currentElement, recurse, limit)); } , getElementsByTagType: function DomUtils$getElementsByTagType (type, currentElement, recurse, limit) { return(DomUtils.getElements({ tag_type: type }, currentElement, recurse, limit)); } } function inherits (ctor, superCtor) { var tempCtor = function(){}; tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; } exports.Parser = Parser; exports.DefaultHandler = DefaultHandler; exports.RssHandler = RssHandler; exports.ElementType = ElementType; exports.DomUtils = DomUtils; })();
tfe/cloud9
support/ace/support/node-htmlparser/lib/node-htmlparser.js
JavaScript
gpl-3.0
30,455
/* * test-svn-fe: Code to exercise the svn import lib */ #include "git-compat-util.h" #include "vcs-svn/svndump.h" #include "vcs-svn/svndiff.h" #include "vcs-svn/sliding_window.h" #include "vcs-svn/line_buffer.h" static const char test_svnfe_usage[] = "test-svn-fe (<dumpfile> | [-d] <preimage> <delta> <len>)"; static int apply_delta(int argc, char *argv[]) { struct line_buffer preimage = LINE_BUFFER_INIT; struct line_buffer delta = LINE_BUFFER_INIT; struct sliding_view preimage_view = SLIDING_VIEW_INIT(&preimage, -1); if (argc != 5) usage(test_svnfe_usage); if (buffer_init(&preimage, argv[2])) die_errno("cannot open preimage"); if (buffer_init(&delta, argv[3])) die_errno("cannot open delta"); if (svndiff0_apply(&delta, (off_t) strtoull(argv[4], NULL, 0), &preimage_view, stdout)) return 1; if (buffer_deinit(&preimage)) die_errno("cannot close preimage"); if (buffer_deinit(&delta)) die_errno("cannot close delta"); buffer_reset(&preimage); strbuf_release(&preimage_view.buf); buffer_reset(&delta); return 0; } int main(int argc, char *argv[]) { if (argc == 2) { if (svndump_init(argv[1])) return 1; svndump_read(NULL); svndump_deinit(); svndump_reset(); return 0; } if (argc >= 2 && !strcmp(argv[1], "-d")) return apply_delta(argc, argv); usage(test_svnfe_usage); }
TextusData/Mover
thirdparty/git-1.7.11.3/test-svn-fe.c
C
gpl-3.0
1,336
/* ** Bytecode dump definitions. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_BCDUMP_H #define _LJ_BCDUMP_H #include "lj_obj.h" #include "lj_lex.h" /* -- Bytecode dump format ------------------------------------------------ */ /* ** dump = header proto+ 0U ** header = ESC 'L' 'J' versionB flagsU [namelenU nameB*] ** proto = lengthU pdata ** pdata = phead bcinsW* uvdataH* kgc* knum* [debugB*] ** phead = flagsB numparamsB framesizeB numuvB numkgcU numknU numbcU ** [debuglenU [firstlineU numlineU]] ** kgc = kgctypeU { ktab | (loU hiU) | (rloU rhiU iloU ihiU) | strB* } ** knum = intU0 | (loU1 hiU) ** ktab = narrayU nhashU karray* khash* ** karray = ktabk ** khash = ktabk ktabk ** ktabk = ktabtypeU { intU | (loU hiU) | strB* } ** ** B = 8 bit, H = 16 bit, W = 32 bit, U = ULEB128 of W, U0/U1 = ULEB128 of W+1 */ /* Bytecode dump header. */ #define BCDUMP_HEAD1 0x1b #define BCDUMP_HEAD2 0x4c #define BCDUMP_HEAD3 0x4a /* If you perform *any* kind of private modifications to the bytecode itself ** or to the dump format, you *must* set BCDUMP_VERSION to 0x80 or higher. */ #define BCDUMP_VERSION 2 /* Compatibility flags. */ #define BCDUMP_F_BE 0x01 #define BCDUMP_F_STRIP 0x02 #define BCDUMP_F_FFI 0x04 #define BCDUMP_F_FR2 0x08 #define BCDUMP_F_KNOWN (BCDUMP_F_FR2*2-1) /* Type codes for the GC constants of a prototype. Plus length for strings. */ enum { BCDUMP_KGC_CHILD, BCDUMP_KGC_TAB, BCDUMP_KGC_I64, BCDUMP_KGC_U64, BCDUMP_KGC_COMPLEX, BCDUMP_KGC_STR }; /* Type codes for the keys/values of a constant table. */ enum { BCDUMP_KTAB_NIL, BCDUMP_KTAB_FALSE, BCDUMP_KTAB_TRUE, BCDUMP_KTAB_INT, BCDUMP_KTAB_NUM, BCDUMP_KTAB_STR }; /* -- Bytecode reader/writer ---------------------------------------------- */ LJ_FUNC int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer, void *data, int strip); LJ_FUNC GCproto *lj_bcread_proto(LexState *ls); LJ_FUNC GCproto *lj_bcread(LexState *ls); #endif
huncrys/mtasa-blue
vendor/luajit/src/lj_bcdump.h
C
gpl-3.0
2,011
""" Internal subroutines for e.g. aborting execution with an error message, or performing indenting on multiline output. """ import sys import textwrap def abort(msg): """ Abort execution, print ``msg`` to stderr and exit with error status (1.) This function currently makes use of `sys.exit`_, which raises `SystemExit`_. Therefore, it's possible to detect and recover from inner calls to `abort` by using ``except SystemExit`` or similar. .. _sys.exit: http://docs.python.org/library/sys.html#sys.exit .. _SystemExit: http://docs.python.org/library/exceptions.html#exceptions.SystemExit """ from fabric.state import output if output.aborts: print >> sys.stderr, "\nFatal error: " + str(msg) print >> sys.stderr, "\nAborting." sys.exit(1) def warn(msg): """ Print warning message, but do not abort execution. This function honors Fabric's :doc:`output controls <../../usage/output_controls>` and will print the given ``msg`` to stderr, provided that the ``warnings`` output level (which is active by default) is turned on. """ from fabric.state import output if output.warnings: print >> sys.stderr, "\nWarning: %s\n" % msg def indent(text, spaces=4, strip=False): """ Return ``text`` indented by the given number of spaces. If text is not a string, it is assumed to be a list of lines and will be joined by ``\\n`` prior to indenting. When ``strip`` is ``True``, a minimum amount of whitespace is removed from the left-hand side of the given string (so that relative indents are preserved, but otherwise things are left-stripped). This allows you to effectively "normalize" any previous indentation for some inputs. """ # Normalize list of strings into a string for dedenting. "list" here means # "not a string" meaning "doesn't have splitlines". Meh. if not hasattr(text, 'splitlines'): text = '\n'.join(text) # Dedent if requested if strip: text = textwrap.dedent(text) prefix = ' ' * spaces output = '\n'.join(prefix + line for line in text.splitlines()) # Strip out empty lines before/aft output = output.strip() # Reintroduce first indent (which just got stripped out) output = prefix + output return output def puts(text, show_prefix=True, end="\n", flush=False): """ An alias for ``print`` whose output is managed by Fabric's output controls. In other words, this function simply prints to ``sys.stdout``, but will hide its output if the ``user`` :doc:`output level </usage/output_controls>` is set to ``False``. If ``show_prefix=False``, `puts` will omit the leading ``[hostname]`` which it tacks on by default. (It will also omit this prefix if ``env.host_string`` is empty.) Newlines may be disabled by setting ``end`` to the empty string (``''``). (This intentionally mirrors Python 3's ``print`` syntax.) You may force output flushing (e.g. to bypass output buffering) by setting ``flush=True``. .. versionadded:: 0.9.2 .. seealso:: `~fabric.utils.fastprint` """ from fabric.state import output, env if output.user: prefix = "" if env.host_string and show_prefix: prefix = "[%s] " % env.host_string sys.stdout.write(prefix + str(text) + end) if flush: sys.stdout.flush() def fastprint(text, show_prefix=False, end="", flush=True): """ Print ``text`` immediately, without any prefix or line ending. This function is simply an alias of `~fabric.utils.puts` with different default argument values, such that the ``text`` is printed without any embellishment and immediately flushed. It is useful for any situation where you wish to print text which might otherwise get buffered by Python's output buffering (such as within a processor intensive ``for`` loop). Since such use cases typically also require a lack of line endings (such as printing a series of dots to signify progress) it also omits the traditional newline by default. .. note:: Since `~fabric.utils.fastprint` calls `~fabric.utils.puts`, it is likewise subject to the ``user`` :doc:`output level </usage/output_controls>`. .. versionadded:: 0.9.2 .. seealso:: `~fabric.utils.puts` """ return puts(text=text, show_prefix=show_prefix, end=end, flush=flush) def handle_prompt_abort(): import fabric.state if fabric.state.env.abort_on_prompts: abort("Needed to prompt, but abort-on-prompts was set to True!")
apavlo/h-store
third_party/python/fabric/utils.py
Python
gpl-3.0
4,636
<?php namespace App\Repositories\Criteria\Error; use Bosnadev\Repositories\Criteria\Criteria; use Bosnadev\Repositories\Contracts\RepositoryInterface as Repository; class ErrorByCreatedDateDescending extends Criteria { /** * @param $model * @param Repository $repository * * @return mixed */ public function apply( $model, Repository $repository ) { $model = $model->orderBy('created_at', 'DESC'); return $model; } }
eddieluis37/lesk
app/Repositories/Criteria/Error/ErrorByCreatedDateDescending.php
PHP
gpl-3.0
479
/* Copyright 2013 Google Inc 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. */ namespace Google.Apis.Auth.OAuth2.Responses { /// <summary> /// OAuth 2.0 model for a unsuccessful access token response as specified in /// http://tools.ietf.org/html/rfc6749#section-5.2. /// </summary> public class TokenErrorResponse { /// <summary> /// Gets or sets error code (e.g. "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", /// "unsupported_grant_type", "invalid_scope") as specified in http://tools.ietf.org/html/rfc6749#section-5.2. /// </summary> [Newtonsoft.Json.JsonProperty("error")] public string Error { get; set; } /// <summary> /// Gets or sets a human-readable text which provides additional information used to assist the client /// developer in understanding the error occurred. /// </summary> [Newtonsoft.Json.JsonProperty("error_description")] public string ErrorDescription { get; set; } /// <summary> /// Gets or sets the URI identifying a human-readable web page with provides information about the error. /// </summary> [Newtonsoft.Json.JsonProperty("error_uri")] public string ErrorUri { get; set; } public override string ToString() { return string.Format("Error:\"{0}\", Description:\"{1}\", Uri:\"{2}\"", Error, ErrorDescription, ErrorUri); } /// <summary>Constructs a new empty token error response.</summary> public TokenErrorResponse() { } /// <summary>Constructs a new token error response from the given authorization code response.</summary> public TokenErrorResponse(AuthorizationCodeResponseUrl authorizationCode) { Error = authorizationCode.Error; ErrorDescription = authorizationCode.ErrorDescription; ErrorUri = authorizationCode.ErrorUri; } } }
galets/SelfDecryptingImage
postsdi/Google/OAuth2/Responses/TokenErrorResponse.cs
C#
gpl-3.0
2,488
/* Copyright (C) 2014,2015,2016 The ESPResSo project This file is part of ESPResSo. ESPResSo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESPResSo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ACTOR_HARMONICORIENTATIONWELL_HPP #define _ACTOR_HARMONICORIENTATIONWELL_HPP #include "config.hpp" #ifdef CUDA #ifdef ROTATION #include "Actor.hpp" #include "SystemInterface.hpp" #include <iostream> void HarmonicOrientationWell_kernel_wrapper(float x, float y, float z, float k, int n, float *quatu, float *torque); class HarmonicOrientationWell : public Actor { public: HarmonicOrientationWell(float x1, float x2, float x3, float _k, SystemInterface &s); virtual void computeTorques(SystemInterface &s) { HarmonicOrientationWell_kernel_wrapper(x,y,z,k,s.npart_gpu(), s.quatuGpuBegin(), s.torqueGpuBegin()); }; virtual ~HarmonicOrientationWell() {} protected: float x,y,z; float k; }; #endif #endif #endif
KonradBreitsprecher/espresso
src/core/actor/HarmonicOrientationWell.hpp
C++
gpl-3.0
1,456
<html> <head> <script src='underscore.js'></script> <script src='slate-mock.js'></script> <script src='initialize.js'></script> </head> <body> </body> </html>
raxbg/slate
Slate/slate-test.html
HTML
gpl-3.0
179
##Changelog ###v1.1.3 - removed IDE stuff from npm package ###v1.1.2 - Added deprecation warning for client-side bundlers - Updated package.json for node v0.10 ###v1.1.1 - Fixed bug with modules that had a comment on the last line ###v1.1.0 - Added Coffee-Script support - Removed Makefile: Use `npm test` instead. ###v1.0.4 - Improved client-side rewire() with webpack ###v1.0.3 - Fixed error with client-side bundlers when a module was ending with a comment ###v1.0.2 - Improved strict mode detection ###v1.0.1 - Fixed crash when a global module has been used in the browser ###v1.0.0 - Removed caching functionality. Now rewire doesn't modify `require.cache` at all - Added support for [webpack](https://github.com/webpack/webpack)-bundler - Moved browserify-middleware from `rewire.browserify` to `rewire.bundlers.browserify` - Reached stable state :)
sneumann/shiny-server
node_modules/rewire/CHANGELOG.md
Markdown
agpl-3.0
865