answer
stringlengths
15
1.25M
<!doctype html> <html lang="en"> <head> <title>Code coverage report for ol/interaction/dragboxinteraction.js</title> <meta charset="utf-8" /> <link rel="stylesheet" href="../../prettify.css" /> <link rel="stylesheet" href="../../base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(../../sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> <a href="../../index.html">all files</a> / <a href="index.html">ol/interaction/</a> dragboxinteraction.js </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">55.1% </span> <span class="quiet">Statements</span> <span class='fraction'>27/49</span> </div> <div class='fl pad1y space-right2'> <span class="strong">22.22% </span> <span class="quiet">Branches</span> <span class='fraction'>4/18</span> </div> <div class='fl pad1y space-right2'> <span class="strong">50% </span> <span class="quiet">Functions</span> <span class='fraction'>3/6</span> </div> <div class='fl pad1y space-right2'> <span class="strong">55.1% </span> <span class="quiet">Lines</span> <span class='fraction'>27/49</span> </div> </div> </div> <div class='status-line medium'></div> <pre><table class="coverage"> <tr><td class="line-count quiet">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201</td><td class="line-coverage quiet"><span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">60×</span> <span class="cline-any cline-yes">60×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">// FIXME draw drag box goog.provide('ol.DragBoxEvent'); goog.provide('ol.interaction.DragBox'); &nbsp; goog.require('goog.events.Event'); goog.require('ol'); goog.require('ol.events.ConditionType'); goog.require('ol.events.condition'); goog.require('ol.interaction.Pointer'); goog.require('ol.render.Box'); &nbsp; &nbsp; /** * @const * @type {number} */ ol.<API key> = ol.<API key> * ol.<API key>; &nbsp; &nbsp; /** * @enum {string} */ ol.DragBoxEventType = { /** * Triggered upon drag box start. * @event ol.DragBoxEvent#boxstart * @api stable */ BOXSTART: 'boxstart', /** * Triggered upon drag box end. * @event ol.DragBoxEvent#boxend * @api stable */ BOXEND: 'boxend' }; &nbsp; &nbsp; &nbsp; /** * @classdesc * Events emitted by {@link ol.interaction.DragBox} instances are instances of * this type. * * @param {string} type The event type. * @param {ol.Coordinate} coordinate The event coordinate. * @extends {goog.events.Event} * @constructor * @implements {oli.DragBoxEvent} */ ol.DragBoxEvent = <span class="fstat-no" title="function not covered" >function(type, coordinate) {</span> <span class="cstat-no" title="statement not covered" > goog.base(this, type);</span> &nbsp; /** * The coordinate of the drag event. * @const * @type {ol.Coordinate} * @api stable */ <span class="cstat-no" title="statement not covered" > this.coordinate = coordinate;</span> &nbsp; }; goog.inherits(ol.DragBoxEvent, goog.events.Event); &nbsp; &nbsp; &nbsp; /** * @classdesc * Allows the user to draw a vector box by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits * it to when the shift or other key is held down. This is used, for example, * for zooming to a specific area of the map * (see {@link ol.interaction.DragZoom} and * {@link ol.interaction.DragRotateAndZoom}). * * This interaction is only supported for mouse devices. * * @constructor * @extends {ol.interaction.Pointer} * @fires ol.DragBoxEvent * @param {olx.interaction.DragBoxOptions=} opt_options Options. * @api stable */ ol.interaction.DragBox = function(opt_options) { &nbsp; goog.base(this, { handleDownEvent: ol.interaction.DragBox.handleDownEvent_, handleDragEvent: ol.interaction.DragBox.handleDragEvent_, handleUpEvent: ol.interaction.DragBox.handleUpEvent_ }); &nbsp; var options = opt_options ? opt_options : <span class="branch-1 cbranch-no" title="branch not covered" >{};</span> &nbsp; /** * @type {ol.render.Box} * @private */ this.box_ = new ol.render.Box(options.className || <span class="branch-1 cbranch-no" title="branch not covered" >'ol-dragbox')</span>; &nbsp; /** * @type {ol.Pixel} * @private */ this.startPixel_ = null; &nbsp; /** * @private * @type {ol.events.ConditionType} */ this.condition_ = options.condition ? options.condition : <span class="branch-1 cbranch-no" title="branch not covered" >ol.events.condition.always;</span> &nbsp; }; goog.inherits(ol.interaction.DragBox, ol.interaction.Pointer); &nbsp; &nbsp; /** * @param {ol.<API key>} mapBrowserEvent Event. * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleDragEvent_ = <span class="fstat-no" title="function not covered" >function(mapBrowserEvent) {</span> <span class="cstat-no" title="statement not covered" > if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > return;</span> } &nbsp; <span class="cstat-no" title="statement not covered" > this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);</span> }; &nbsp; &nbsp; /** * Returns geometry of last drawn box. * @return {ol.geom.Polygon} Geometry. * @api stable */ ol.interaction.DragBox.prototype.getGeometry = function() { return this.box_.getGeometry(); }; &nbsp; &nbsp; /** * To be overriden by child classes. * FIXME: use constructor option instead of relying on overridding. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @protected */ ol.interaction.DragBox.prototype.onBoxEnd = ol.nullFunction; &nbsp; &nbsp; /** * @param {ol.<API key>} mapBrowserEvent Event. * @return {boolean} Stop drag sequence? * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleUpEvent_ = <span class="fstat-no" title="function not covered" >function(mapBrowserEvent) {</span> <span class="cstat-no" title="statement not covered" > if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > return true;</span> } &nbsp; <span class="cstat-no" title="statement not covered" > this.box_.setMap(null);</span> &nbsp; <span class="cstat-no" title="statement not covered" > var deltaX = mapBrowserEvent.pixel[0] - this.startPixel_[0];</span> <span class="cstat-no" title="statement not covered" > var deltaY = mapBrowserEvent.pixel[1] - this.startPixel_[1];</span> &nbsp; <span class="cstat-no" title="statement not covered" > if (deltaX * deltaX + deltaY * deltaY &gt;=</span> ol.<API key>) { <span class="cstat-no" title="statement not covered" > this.onBoxEnd(mapBrowserEvent);</span> <span class="cstat-no" title="statement not covered" > this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXEND,</span> mapBrowserEvent.coordinate)); } <span class="cstat-no" title="statement not covered" > return false;</span> }; &nbsp; &nbsp; /** * @param {ol.<API key>} mapBrowserEvent Event. * @return {boolean} Start drag sequence? * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleDownEvent_ = function(mapBrowserEvent) { <span class="missing-if-branch" title="else path not taken" >E</span>if (!ol.events.condition.mouseOnly(mapBrowserEvent)) { return false; } &nbsp; <span class="cstat-no" title="statement not covered" > var browserEvent = mapBrowserEvent.browserEvent;</span> <span class="cstat-no" title="statement not covered" > if (browserEvent.isMouseActionButton() &amp;&amp; this.condition_(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > this.startPixel_ = mapBrowserEvent.pixel;</span> <span class="cstat-no" title="statement not covered" > this.box_.setMap(mapBrowserEvent.map);</span> <span class="cstat-no" title="statement not covered" > this.box_.setPixels(this.startPixel_, this.startPixel_);</span> <span class="cstat-no" title="statement not covered" > this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXSTART,</span> mapBrowserEvent.coordinate)); <span class="cstat-no" title="statement not covered" > return true;</span> } else { <span class="cstat-no" title="statement not covered" > return false;</span> } }; &nbsp;</pre></td></tr> </table></pre> <div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Fri Nov 06 2015 19:36:11 GMT+0100 (CET) </div> </div> <script src="../../prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="../../sorter.js"></script> </body> </html>
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class <API key> { private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('<API key>')); projectSettingsLink = element(by.id('<API key>')); // Get the projectSettings for project projectName get(projectName: string) { this.projectsPage.get(); this.projectsPage.clickOnProject(projectName); browser.wait(ExpectedConditions.visibilityOf(this.settingsMenuLink), this.conditionTimeout); this.settingsMenuLink.click(); browser.wait(ExpectedConditions.visibilityOf(this.projectSettingsLink), this.conditionTimeout); this.projectSettingsLink.click(); } noticeList = element.all(by.repeater('notice in $ctrl.notices()')); <API key> = this.noticeList.first().element(by.buttonText('×')); tabDivs = element.all(by.className('tab-pane')); activePane = element(by.css('div.tab-pane.active')); /* Would like to use id locators, but the pui-tab directive that is used in the project settingsPage in scripture forge is currently making it hard to assign an id to the tab element. This should be updated, but due to time shortage, it will be left as is. - Mark W 2018-01-15 */ tabs = { project: element(by.linkText('Project Properties')), // reports: element(by.linkText('Reports')), // This feature is never tested // archive: element(by.linkText('Archive')), // This is a disabled feature remove: element(by.linkText('Delete')) }; projectTab = { name: element(by.model('project.projectName')), code: element(by.model('project.projectCode')), projectOwner: element(by.binding('project.ownerRef.username')), saveButton: element(by.id('<API key>')) }; // placeholder since we don't have Reports tests reportsTab = { }; // Archive tab currently disabled // this.archiveTab = { // archiveButton: this.activePane.element(by.buttonText('Archive this project')) deleteTab = { deleteBoxText: this.activePane.element(by.id('deletebox')), deleteButton: this.activePane.element(by.id('deleteProject')) }; }
#ifndef AC_GEPT3DAR_H #define AC_GEPT3DAR_H // object code form for any purpose and without fee is hereby granted, // restricted rights notice below appear in all supporting // documentation. // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // (Rights in Technical Data and Computer Software), as applicable. // DESCRIPTION: // This file contains the definition for a dynamic array, called // AcGePoint3dArray, of objects of type "AcGePoint3d". // "Dynamic array" means that the array can grow without bounds, // unlike declaring an array of objects of type "AcGePoint3d" in the // usual manner. For example declaring "AcGePoint3d myArray[10]" // is limited to holding only ten entries. // In order to use the class AcGePoint3dArray, you need to understand // a couple of simple, yet key, concepts: // 1) The logical length of the array. // - How many entries have been placed into the array, // initially always zero. // 2) The physical length of the array. // - How many entries the array will hold before it // automatically "grows" larger. // 3) The grow length of the array. // - How much the array will grow when required. // The physical length of the array is the actual length of the // physically allocated, but perhaps not fully used, array. // As a point of clarification, the size in bytes of the array // buffer for an array called `myArray' would be: // sizeOf(AcGePoint3d) * myArray.physicalLength(). // The physical length of the array can be zero or any positive // integer. // The logical length of the array (or just the "length()") reflects // how many elements of AcGePoint3d have been placed into the array // with, for example, append() or insertAt(). Many member-functions // are only valid for indices that are greater than or equal to // zero AND less than length(). For example, indexing into the // array with the operator[] is only valid for indices in this range. // You can explicitly set the logical length() to any value and // if the physical length is not large enough the array will grow to // that length. Note that if the logical length is explicitly reset // to a larger value, then all the entries from the old length up // to the new length may contain garbage values, therefor they must be // initialized explicitly. // The logical length is always less than or equal to the physical // length. NOTE that the array ALWAYS starts out empty, i.e., the // length() always starts at zero regardless of the initial physical // length. // If you add an element to the array causing the logical length // to become greater than the physical length of the array then // the "grow length" determines how much additional space to // allocate, and the physical length will increase by the grow length. // grow length. #include "adesk.h" #include "assert.h" #include "gepnt3d.h" #include "acarray.h" typedef AcArray<AcGePoint3d> AcGePoint3dArray; #if GE_LOCATED_NEW GE_DLLEXPIMPORT AcGe::metaTypeIndex <API key>(AcGePoint3dArray* pT); #endif #endif
/** * Framework APIs (global - app.*) * * Note: View APIs are in view.js (view - view.*) * * @author Tim Lauv * @created 2015.07.29 * @updated 2017.04.04 */ ;(function(app){ app.create = function(type, config){ console.warn('DEV::Application::create() method is deprecated, use methods listed in ', app._apis, ' for alternatives'); }; _.extend(app, { //pass in [name,] options to define view (named view will be registered) //pass in name to get registered view def //pass in options, true to create anonymous view view: function(name /*or options*/, options /*or instance flag*/){ if(_.isString(name) && _.isPlainObject(options)){ return app.Core.View.register(name, options); } if(_.isPlainObject(name)){ var instance = options; options = name; var Def = app.Core.View.register(options); if(_.isBoolean(instance) && instance) return Def.create(); return Def; } return app.Core.View.get(name); }, //pass in [name,] options to register (always requires a name) //pass in [name] to get (name can be of path form) context: function(name /*or options*/, options){ if(!options) { if(_.isString(name) || !name) return app.Core.Context.get(name); else options = name; } else _.extend(options, {name: name}); console.warn('DEV::Application::context() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.Core.Context.register(options); }, //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) widget: function(name, options /*or factory*/){ if(!options) return app.Core.Widget.get(name); if(_.isFunction(options)) //register return app.Core.Widget.register(name, options); return app.Core.Widget.create(name, options); //you can not register the definition when providing name, options. }, //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) editor: function(name, options /*or factory*/){ if(!options) return app.Core.Editor.get(name); if(_.isFunction(options)) //register return app.Core.Editor.register(name, options); return app.Core.Editor.create(name, options); //you can not register the definition when providing name, options. }, regional: function(name, options){ options = options || {}; if(_.isString(name)) _.extend(options, {name: name}); else _.extend(options, name); console.warn('DEV::Application::regional() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.view(options, !options.name); }, //(name can be of path form) has: function(name, type){ type = type || 'View'; if(name) return app.Core[type] && app.Core[type].has(name); _.each(['Context', 'View', 'Widget', 'Editor'], function(t){ if(!type && app.Core[t].has(name)) type = t; }); return type; }, //(name can be of path form) //always return View definition. get: function(name, type, options){ if(!name) return { 'Context': app.Core.Context.get(), 'View': app.Core.View.get(), 'Widget': app.Core.Widget.get(), 'Editor': app.Core.Editor.get() }; if(_.isPlainObject(type)){ options = type; type = undefined; } var Reusable, t = type || 'View'; options = _.extend({fallback: false, override: false}, options); //try local if(!options.override) Reusable = (app.Core[t] && app.Core[t].get(name)) || (options.fallback && app.Core['View'].get(name)); //try remote, if we have app.viewSrcs set to load the View def dynamically if(!Reusable && app.config && app.config.viewSrcs){ var targetJS = _.compact([app.config.viewSrcs, t.toLowerCase()/*not view.category yet*/, app.nameToPath(name)]).join('/') + '.js'; app.inject.js( targetJS, true //sync ).done(function(){ app.debug(t, name, 'injected', 'from', app.config.viewSrcs); if(app.has(name, t) || (options.fallback && app.has(name))) Reusable = app.get(name, t, {fallback: true}); else throw new Error('DEV::Application::get() loaded definitions other than required ' + name + ' of type ' + t + ' from ' + targetJS + ', please check your view name in that file!'); }).fail(function(jqXHR, settings, e){ if(!options.fallback || (t === 'View')) throw new Error('DEV::Application::get() can NOT load definition for ' + name + ' - [' + e + ']'); else Reusable = app.get(name, 'View'); }); } return Reusable; }, spray: function($anchor, View /*or template or name or instance or options or svg draw(paper){} func */, options, parentCt){ remote: function(options /*or url*/, payload, restOpt){ download: function(ticket /*or url*/, options /*{params:{...}} only*/){ ws: function(socketPath, coopEvent /*or callback or options*/){ if(!app.detect('websockets')) throw new Error('DEV::Application::ws() Websocket is not supported by your browser!'); socketPath = socketPath || app.config.defaultWebsocket || '/ws'; var reconnect = false; if(_.string.endsWith(socketPath, '+')){ socketPath = socketPath.slice(0, socketPath.length - 1); reconnect = true; } var d = $.Deferred(); if(!app._websockets[socketPath]) { app._websockets[socketPath] = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.host + socketPath); app._websockets[socketPath].path = socketPath; app._websockets[socketPath].reconnect = reconnect; //events: 'open', 'error', 'close', 'message' = e.data //apis: send(), +json(), +channel().json(), close() app._websockets[socketPath].json = function(data){ app._websockets[socketPath].send(JSON.stringify(data)); }; app._websockets[socketPath].channel = function(channel){ return { name: channel, websocket: app._websockets[socketPath], json: function(data){ app._websockets[socketPath].json({ channel: channel, stream: channel, //alias for ASGI backends payload: data }); } }; }; app._websockets[socketPath].stream = app._websockets[socketPath].channel; //alias for ASGI backends app._websockets[socketPath].onclose = function(){ var ws = app._websockets[socketPath]; delete app._websockets[socketPath]; if(ws.reconnect) app.ws(ws.path + '+'); }; app._websockets[socketPath].onopen = function(){ return d.resolve(app._websockets[socketPath]); }; //general ws data stub //server need to always send default json contract string {"channel/stream": "...", "payload": "..."} //Opt: override this through app.ws(path).then(function(ws){ws.onmessage=...}); app._websockets[socketPath].onmessage = function(e){ //opt a. override app.onWsData to active otherwise app.trigger('app:ws-data', {websocket: app._websockets[socketPath], raw: e.data}); //opt b. use global coop event 'ws-data-[channel]' in views directly (default json contract) try { var data = JSON.parse(e.data); app.coop('ws-data-' + (data.channel || data.stream), data.payload, app._websockets[socketPath].channel(data.channel || data.stream)); }catch(ex){ console.warn('DEV::Application::ws() Websocket is getting non-default {channel: ..., payload: ...} json contract strings...'); } }; //register coopEvent or callback function or callback options if(coopEvent){ //onmessage callback function if(_.isFunction(coopEvent)){ //overwrite onmessage callback function defined by framework app._websockets[socketPath].onmessage = function(e){ coopEvent(e.data, e, app._websockets[socketPath]); }; } //object may contain onmessage, onerror, since onopen and onclose is done by the framework else if(_.isPlainObject(coopEvent)){ //traverse through object to register all callback events _.each(coopEvent, function(fn, eventName){ //guard events if(_.contains(['onmessage', 'onerror'], eventName)) app._websockets[socketPath][eventName] = fn; }); } //app coop event else if(_.isString(coopEvent)){ //trigger coop event with data from sse's onmessage callback app._websockets[socketPath].onmessage = function(e){ app.coop('ws-data-' + coopEvent, e.data, e, app._websockets[socketPath]); }; } //type is not right else console.warn('DEV::Application::ws() The coopEvent or callback function or callbacks\' options you give is not right.'); } }else d.resolve(app._websockets[socketPath]); return d.promise(); }, //data polling //(through later.js) and emit data events/or invoke callback _polls: {}, poll: function(url /*or {options} for app.remote()*/, occurrence, coopEvent /*or callback or options*/) { //stop everything if (url === false){ return _.map(this._polls, function(card) { return card.cancel(); }); } var schedule; if (_.isString(occurrence) && !Number.parseInt(occurrence)) { schedule = app.later.parse.text(occurrence); if (schedule.error !== -1) throw new Error('DEV::Application::poll() occurrence string unrecognizable...'); } else if (_.isPlainObject(occurrence)) schedule = occurrence; else //number schedule = Number(occurrence); //make a key from url, or {url: ..., params/querys} var key = url; if (_.isPlainObject(key)) key = [key.url, _.reduce((_.map(key.params || key.querys, function(qV, qKey) { return [qKey, qV].join('='); })).sort(), function(qSignature, more) { return [more, qSignature].join('&'); }, '')].join('?'); //cancel polling if (occurrence === false) { if (this._polls[key]) return this._polls[key].cancel(); console.warn('DEV::Application::poll() No polling card registered yet for ' + key); return; } //cancel previous polling if (this._polls[key]) this._polls[key].cancel(); //register polling card if (!occurrence || !coopEvent) throw new Error('DEV::Application::poll() You must specify an occurrence and a coop event or callback...'); var card = { _key: key, url: url, eof: coopEvent, timerId: undefined, failed: 0, valid: true, occurrence: occurrence, //info only }; this._polls[key] = card; var call = _.isNumber(schedule) ? window.setTimeout : app.later.setTimeout; //if coopEvent is an object. register options events before calling app.remote if(_.isPlainObject(coopEvent)){ //save url var temp = url; //build url as an object for app.remote url = { url: temp }; _.each(coopEvent, function(fn, eventName){ //guard for only allowing $.ajax events if(_.contains(['beforeSend', 'error', 'dataFilter', 'success', 'complete'], eventName)) url[eventName] = fn; }); } var worker = function() { app.remote(url).done(function(data) { //callback if (_.isFunction(card.eof)) card.eof(data, card); //coop event else app.coop('poll-data-' + card.eof, data, card); }).fail(function() { card.failed++; //Warning: Hardcoded 3 attemps here! if (card.failed >= 3) card.cancel(); }).always(function() { //go schedule the next call if (card.valid) card.timerId = call(worker, schedule); }); }; //+timerType card.timerType = (call === window.setTimeout) ? 'native' : 'later.js'; //+cancel() var that = this; card.cancel = function() { this.valid = false; if (this.timerType === 'native') !_.isUndefined(this.timerId) && window.clearTimeout(this.timerId); else !_.isUndefined(this.timerId) && this.timerId.clear(); delete that._polls[this._key]; return this; }; //make the 1st call (eagerly) worker(); }, //use start('stateB') or trigger('stateA-->stateB') to swap between states //use ['stateA-->stateB', 'stateC<-->stateB', 'stateA<--stateC', ...] in edges to constrain state changes. ee: function(data, evtmap, edges){ //+on/once, off, +start/reset/stop/getState/getEdges; +listenTo/Once, stopListening; +trigger*; var dispatcher; data = _.extend({}, data, {cid: _.uniqueId('ee')}); evtmap = _.extend({ 'initialize': _.noop, 'finalize': _.noop, }, evtmap); edges = _.reduce(edges || {}, function(mem, val, index){ var bi = val.match('(.*)< left = val.match('(.*)< right = val.match('(.*) if(bi){ mem[bi[1] + '-->' + bi[2]] = true; mem[bi[2] + '-->' + bi[1]] = true; } else if (left) mem[left[2] + '-->' + left[1]] = true; else if (right) mem[val] = true; else console.warn('DEV::Application::ee() illegal edge format: ' + val); return mem; }, {}); if(!_.size(edges)) edges = undefined; dispatcher = _.extend(data, Backbone.Events); var oldTriggerFn = dispatcher.trigger; var currentState = ''; //add a state-machine friendly .trigger method; dispatcher.trigger = function(){ var changeOfStates = arguments[0] && arguments[0].match('(.*) if(changeOfStates && changeOfStates.length){ var from = _.string.trim(changeOfStates[1]), to = _.string.trim(changeOfStates[2]); //check edge constraints if(from && to && edges && !edges[arguments[0]]){ console.warn('DEV::Application::ee() edge constraint: ' + from + '-x->' + to); return this; } //check current state if(from != currentState){ console.warn('DEV::Application::ee() current state is ' + (currentState || '\'\'') + ' not ' + from); return this; } this.trigger('leave', {to: to}); //unregister event listeners in [from] state _.each(evtmap[from], function(listener, e){ dispatcher.off(from + ':' + e); }); //register event listeners in [to] state _.each(evtmap[to], function(listener, e){ dispatcher.on(to + ':' + e, listener); }); currentState = to; this.trigger('enter', {from: from}); } else { if(evtmap[currentState] && evtmap[currentState][arguments[0]]) arguments[0] = currentState + ':' + arguments[0]; oldTriggerFn.apply(this, arguments); } return this; }; //add an internal worker swap method; dispatcher._swap = function(targetState){ targetState = targetState || ''; this.trigger(currentState + '-->' + targetState); return this; }; //add a start method; (start at any state) dispatcher.start = function(targetState){ targetState = targetState || currentState; return this._swap(targetState); }; //add a reset method; (reset to '' state) dispatcher.reset = function(){ return this._swap(); }; //add a clean-up method; dispatcher.stop = function(){ this.trigger('finalize'); this.off(); this.stopListening(); }; //add some getters; dispatcher.getState = function(){ return currentState; }; dispatcher.getEdges = function(){ return edges; }; //mount shared events _.each(evtmap, function(listener, eOrStateName){ if(!_.isFunction(listener)) return; dispatcher.on(eOrStateName, listener); }); this.trigger('initialize'); return dispatcher; }, model: function(data, flat){ if(_.isBoolean(data)){ flat = data; data = undefined; } if(flat) return new Backbone.Model(data); //Warning: Possible performance impact...(default) return new Backbone.DeepModel(data); }, collection: function(data){ if(data && !_.isArray(data)) throw new Error('DEV::Application::collection You need to specify an array to init a collection'); return new Backbone.Collection(data); }, //bridge extract from app.Util.deepObjectKeys extract: function(keypath, from){ return app.Util.deepObjectKeys.extract(keypath, from); }, //bridge pack from app.Util.deepObjectKeys pack: function(keypathObj, to){ return app.Util.deepObjectKeys.pack(keypathObj, to); }, mock: function(schema, provider/*optional*/, url/*optional*/){ return app.Util.mock(schema, provider, url); }, param: function(key, defaultVal){ var params = app.uri(window.location.href).search(true) || {}; if(key) return params[key] || defaultVal; return params; }, //(specifically, don't call $.animate() inside updateFn) //(you also can NOT control the rate the browser calls updateFn, its 60 FPS all the time...) animation: function(updateFn, condition, ctx){ var id; var stepFn = function(t){ updateFn.call(ctx);//...update...(1 tick) if(!condition || (condition && condition.call(ctx)))//...condition...(to continue) move(); }; var move = function(){ if(id === undefined) return; id = app._nextFrame(stepFn); }; var stop = function(){ app._cancelFrame(id); id = undefined; }; return { start: function(){id = -1; move();}, stop: stop }; }, _nextFrame: function(stepFn){ //return request id return window.<API key>(stepFn); }, _cancelFrame: function(id){ return window.<API key>(id); }, //sample usage: 'ready' --> app.animateItems(); animateItems: function(selector /*or $items*/, effect, stagger){ var $selector = $(selector); if(_.isNumber(effect)){ stagger = effect; effect = undefined; } effect = effect || 'flipInX'; stagger = stagger || 150; var inOrOut = /In/.test(effect)? 1: (/Out/.test(effect)? -1: 0); $selector.each(function(i, el){ var $el = $(el); ///////////////different than region.show effect because of stagger delay////////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 0); else $el.css('opacity', 1); _.delay(function($el){ var fxName = effect + ' animated'; $el.anyone(app.ADE, function(){ $el.removeClass(fxName); }).addClass(fxName); ////////////reset opacity immediately, not after ADE/////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 1); else $el.css('opacity', 0); }, i * stagger, $el); }); }, //Built-in web worker utility, bridged from app.Util.worker. worker: function(name/*web worker's name*/, <API key>){ return app.Util.worker(name, <API key>); }, //Built-in Server-Sent Event(SSE) utility, bridged from app.Util.sse sse: function(url/*sse's url*/, topics/*['...', '...']*/, <API key>){ return app.Util.sse(url, topics, <API key>); }, markdown: function(md, $anchor /*or options*/, options){ notify: function(title /*or options*/, msg, type /*or otherOptions*/, otherOptions){ locate: function(name /*el or $el*/){ profile: function(name /*el or $el*/){ mark: function(name /*el or $el*/){ reload: function(name, override/*optional*/){ detect: function(feature, provider/*optional*/){ /** * API summary */ app._apis = [ 'ee', 'model', 'collection', 'mock', //view registery 'view', 'widget', 'editor', 'editor.validator - @alias:editor.rule', //global action locks 'lock', 'unlock', 'available', //utils 'has', 'get', 'spray', 'coop', 'navigate', 'navPathArray', 'icing/curtain', 'i18n', 'param', 'animation', 'animateItems', 'throttle', 'debounce', 'preventDefaultE', 'until', //com 'remote', 'download', 'upload', 'ws', 'poll', 'worker', 'sse', //3rd-party lib short-cut 'extract', 'markdown', 'notify', 'prompt', //wraps 'cookie', 'store', 'moment', 'uri', 'validator', 'later', 'faker', //direct refs //supportive 'debug', 'detect', 'reload', 'locate', 'profile', 'mark', 'nameToPath', 'pathToName', 'inject.js', 'inject.tpl', 'inject.css', //@deprecated 'create - @deprecated', 'regional - @deprecated', 'context - @alias:page - @deprecated' ]; /** * Statics */ //animation done events used in Animate.css //Caveat: if you use $el.one(app.ADE) but still got 2+ callback calls, the browser is firing the default and prefixed events at the same time... //use $el.anyone() to fix the problem in using $el.one() app.ADE = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'; //notification template app.NOTIFYTPL = Handlebars.compile('<div class="alert alert-dismissable alert-{{type}}"><button data-dismiss="alert" class="close" type="button">×</button><strong>{{title}}</strong> {{{message}}}</div>'); })(Application);
// Base64 encoder/decoder with UTF-8 support // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. // Based on original artworks of base64 encoder/decoder by [Mozilla][1] 'use strict'; /* eslint-env browser */ /* eslint-disable no-bitwise */ function noop() {} var logger = { warn: noop, error: noop }, padding = '=', chrTable = '<API key>' + '0123456789+/', binTable = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; if (window.console) { logger = window.console; logger.warn = logger.warn || logger.error || logger.log || noop; logger.error = logger.error || logger.warn || logger.log || noop; } // internal helpers ////////////////////////////////////////////////////////// function utf8Encode(str) { var bytes = [], offset = 0, length, char; str = encodeURI(str); length = str.length; while (offset < length) { char = str.charAt(offset); offset += 1; if (char !== '%') { bytes.push(char.charCodeAt(0)); } else { char = str.charAt(offset) + str.charAt(offset + 1); bytes.push(parseInt(char, 16)); offset += 2; } } return bytes; } function utf8Decode(bytes) { var chars = [], offset = 0, length = bytes.length, c1, c2, c3; while (offset < length) { c1 = bytes[offset]; c2 = bytes[offset + 1]; c3 = bytes[offset + 2]; if (c1 < 128) { chars.push(String.fromCharCode(c1)); offset += 1; } else if (191 < c1 && c1 < 224) { chars.push(String.fromCharCode(((c1 & 31) << 6) | (c2 & 63))); offset += 2; } else { chars.push(String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))); offset += 3; } } return chars.join(''); } // public api //////////////////////////////////////////////////////////////// function encode(str) { var result = '', bytes = utf8Encode(str), length = bytes.length, i; // Convert every three bytes to 4 ascii characters. for (i = 0; i < (length - 2); i += 3) { result += chrTable[bytes[i] >> 2]; result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[((bytes[i + 1] & 0x0f) << 2) + (bytes[i + 2] >> 6)]; result += chrTable[bytes[i + 2] & 0x3f]; } // Convert the remaining 1 or 2 bytes, pad out to 4 characters. if (length % 3) { i = length - (length % 3); result += chrTable[bytes[i] >> 2]; if ((length % 3) === 2) { result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[(bytes[i + 1] & 0x0f) << 2]; result += padding; } else { result += chrTable[(bytes[i] & 0x03) << 4]; result += padding + padding; } } return result; } function decode(data) { var value, code, idx = 0, bytes = [], leftbits = 0, // number of bits decoded, but yet to be appended leftdata = 0; // bits decoded, but yet to be appended // Convert one by one. for (idx = 0; idx < data.length; idx += 1) { code = data.charCodeAt(idx); value = binTable[code & 0x7F]; if (value === -1) { logger.warn('Illegal characters (code=' + code + ') in position ' + idx); } else { // Collect data into leftdata, update bitcount leftdata = (leftdata << 6) | value; leftbits += 6; // If we have 8 or more bits, append 8 bits to the result if (leftbits >= 8) { leftbits -= 8; // Append if not padding. if (padding !== data.charAt(idx)) { bytes.push((leftdata >> leftbits) & 0xFF); } leftdata &= (1 << leftbits) - 1; } } } // If there are any bits left, the base64 string was corrupted if (leftbits) { logger.error('Corrupted base64 string'); return null; } return utf8Decode(bytes); } exports.encode = encode; exports.decode = decode;
module.exports = require("npm:acorn@2.4.0/dist/acorn");
require 'rr' require 'awesome_print' %w"xiki/core/core_ext xiki/core/ol".each {|o| require o} # RSpec::Runner.configure do |config| RSpec.configure do |config| config.mock_with :rr end module Xiki def self.dir File.expand_path("#{File.dirname(__FILE__)}/..") + "/" end end def stub_menu_path_dirs xiki_dir = Xiki.dir list = ["#{xiki_dir}spec/fixtures/menu", "#{xiki_dir}menu"] stub(Xiki).menu_path_dirs {list} end # Put this here until we can put it in a better place # - Maybe so it'll be used by main xiki and conf AwesomePrint.defaults = { :indent => -2, # left-align hash keys :index => false, :multiline => true, } include Xiki # Allows all specs to use classes in the Xiki module without "Xiki::"
#ifndef BITSEND_WARNINGS_H #define BITSEND_WARNINGS_H #include <stdlib.h> #include <string> void SetMiscWarning(const std::string& strWarning); void <API key>(bool flag); bool <API key>(); void <API key>(bool flag); bool <API key>(); std::string GetWarnings(const std::string& strFor); static const bool <API key> = false; #endif // BITSEND_WARNINGS_H
# -*- coding: utf-8 -*- # This file is part of Invenio. # Invenio is free software; you can redistribute it and/or modify it """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils from alembic import op from sqlalchemy.engine.reflection import Inspector # revision identifiers, used by Alembic. revision = '97bbc733896c' down_revision = '44ab9963e8cf' branch_labels = () depends_on = '9848d0149abd' def upgrade(): """Upgrade database.""" op.create_table( 'o<API key>, sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'extra_data', sqlalchemy_utils.JSONType(), nullable=False), sa.<API key>(['user_id'], [u'accounts_user.id'], ), sa.<API key>('id'), sa.UniqueConstraint('user_id', 'client_id') ) op.create_table( 'o<API key>, sa.Column('id', sa.String(length=255), nullable=False), sa.Column('method', sa.String(length=255), nullable=False), sa.Column('id_user', sa.Integer(), nullable=False), sa.<API key>(['id_user'], [u'accounts_user.id'], ), sa.<API key>('id', 'method') ) op.create_index( '<API key>', 'o<API key>, ['id_user', 'method'], unique=True ) op.create_table( 'o<API key>, sa.Column('id_remote_account', sa.Integer(), nullable=False), sa.Column('token_type', sa.String(length=40), nullable=False), sa.Column( 'access_token', sqlalchemy_utils.EncryptedType(), nullable=False), sa.Column('secret', sa.Text(), nullable=False), sa.<API key>( ['id_remote_account'], [u'o<API key>.id'], name='fk_o<API key> ), sa.<API key>('id_remote_account', 'token_type') ) def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('o<API key>) for fk in insp.get_foreign_keys('o<API key>): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'o<API key>, type_='foreignkey' ) op.drop_index( '<API key>', table_name='o<API key>) op.drop_table('o<API key>) op.drop_table('o<API key>)
using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { protected override string Header => "Updates"; [<API key>] private void load(Storage storage, OsuConfigManager config) { Children = new Drawable[] { new <API key><ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }, new SettingsButton { Text = "Open osu! folder", Action = storage.<API key>, } }; } } }
package com.microsoft.azure.management.eventhubs.v2017_04_01.implementation; import java.util.List; import org.joda.time.DateTime; import com.microsoft.azure.management.eventhubs.v2017_04_01.EntityStatus; import com.microsoft.azure.management.eventhubs.v2017_04_01.CaptureDescription; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.ProxyResource; /** * Single item in List or Get Event Hub operation. */ @JsonFlatten public class EventhubInner extends ProxyResource { /** * Current number of shards on the Event Hub. */ @JsonProperty(value = "properties.partitionIds", access = JsonProperty.Access.WRITE_ONLY) private List<String> partitionIds; /** * Exact time the Event Hub was created. */ @JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime createdAt; /** * The exact time the message was updated. */ @JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime updatedAt; /** * Number of days to retain the events for this Event Hub, value should be * 1 to 7 days. */ @JsonProperty(value = "properties.<API key>") private Long <API key>; /** * Number of partitions created for the Event Hub, allowed values are from * 1 to 32 partitions. */ @JsonProperty(value = "properties.partitionCount") private Long partitionCount; /** * Enumerates the possible values for the status of the Event Hub. Possible * values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', * 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. */ @JsonProperty(value = "properties.status") private EntityStatus status; /** * Properties of capture description. */ @JsonProperty(value = "properties.captureDescription") private CaptureDescription captureDescription; /** * Get current number of shards on the Event Hub. * * @return the partitionIds value */ public List<String> partitionIds() { return this.partitionIds; } /** * Get exact time the Event Hub was created. * * @return the createdAt value */ public DateTime createdAt() { return this.createdAt; } /** * Get the exact time the message was updated. * * @return the updatedAt value */ public DateTime updatedAt() { return this.updatedAt; } /** * Get number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @return the <API key> value */ public Long <API key>() { return this.<API key>; } /** * Set number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @param <API key> the <API key> value to set * @return the EventhubInner object itself. */ public EventhubInner <API key>(Long <API key>) { this.<API key> = <API key>; return this; } /** * Get number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @return the partitionCount value */ public Long partitionCount() { return this.partitionCount; } /** * Set number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @param partitionCount the partitionCount value to set * @return the EventhubInner object itself. */ public EventhubInner withPartitionCount(Long partitionCount) { this.partitionCount = partitionCount; return this; } /** * Get enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @return the status value */ public EntityStatus status() { return this.status; } /** * Set enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @param status the status value to set * @return the EventhubInner object itself. */ public EventhubInner withStatus(EntityStatus status) { this.status = status; return this; } /** * Get properties of capture description. * * @return the captureDescription value */ public CaptureDescription captureDescription() { return this.captureDescription; } /** * Set properties of capture description. * * @param captureDescription the captureDescription value to set * @return the EventhubInner object itself. */ public EventhubInner <API key>(CaptureDescription captureDescription) { this.captureDescription = captureDescription; return this; } }
import actionTypes from '../../client/actions/types'; const defaultState = { data: {}, errors: 'Not Found', }; export default function domainDetailReducer(state = defaultState, action = {}) { switch (action.type) { case actionTypes.getDomainDetail: return Object.assign({}, state, { data: action.data.domain, errors: action.errors, }); default: return state; } }
import {createStore, combineReducers} from 'redux'; import {todos} from '../reducers/todos'; export function configureStore() { const store = createStore(combineReducers({todos})); return store; }
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="style.css" > <script src="options.js"></script> </head> <body> <div id="options_content"> <span id="message"></span> <h4></h4> <input type="checkbox" name="auto" id="auto"> <label for="auto"></label> <h4></h4> <input type="checkbox" name="zh_definitions" id="zh_definitions"> <label for="zh_definitions"></label> <input type="checkbox" name="en_definitions" id="en_definitions"> <label for="en_definitions"></label> <br /> <br /> <button id="reset"></button> <button id="save"></button> <a href="popup.html" id="return"></a> </div> </body> </html>
#include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "transfer.h" #include "url.h" #include "connect.h" #include "progress.h" #include "easyif.h" #include "share.h" #include "psl.h" #include "multiif.h" #include "sendf.h" #include "timeval.h" #include "http.h" #include "select.h" #include "warnless.h" #include "speedcheck.h" #include "conncache.h" #include "multihandle.h" #include "sigpipe.h" #include "vtls/vtls.h" #include "connect.h" #include "http_proxy.h" #include "http2.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* <API key> should be a prime number. Increasing it from 97 to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every CURL handle takes 45-50 K memory, therefore this 3K are not significant. */ #ifndef <API key> #define <API key> 911 #endif #ifndef <API key> #define <API key> 97 #endif #define CURL_MULTI_HANDLE 0x000bab1e #define GOOD_MULTI_HANDLE(x) \ ((x) && (x)->type == CURL_MULTI_HANDLE) static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data); static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d); static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms); static void <API key>(struct Curl_multi *multi); static void detach_connnection(struct Curl_easy *data); #ifdef DEBUGBUILD static const char * const statename[]={ "INIT", "CONNECT_PEND", "CONNECT", "WAITRESOLVE", "WAITCONNECT", "WAITPROXYCONNECT", "SENDPROTOCONNECT", "PROTOCONNECT", "DO", "DOING", "DO_MORE", "DO_DONE", "PERFORM", "TOOFAST", "DONE", "COMPLETED", "MSGSENT", }; #endif /* function pointer called once when switching TO a state */ typedef void (*<API key>)(struct Curl_easy *data); static void Curl_init_completed(struct Curl_easy *data) { /* this is a completed transfer */ /* Important: reset the conn pointer so that we don't point to memory that could be freed anytime */ detach_connnection(data); Curl_expire_clear(data); /* stop all timers */ } /* always use this function to change state, to make debugging easier */ static void mstate(struct Curl_easy *data, CURLMstate state #ifdef DEBUGBUILD , int lineno #endif ) { CURLMstate oldstate = data->mstate; static const <API key> finit[CURLM_STATE_LAST] = { NULL, /* INIT */ NULL, /* CONNECT_PEND */ Curl_init_CONNECT, /* CONNECT */ NULL, /* WAITRESOLVE */ NULL, /* WAITCONNECT */ NULL, /* WAITPROXYCONNECT */ NULL, /* SENDPROTOCONNECT */ NULL, /* PROTOCONNECT */ Curl_connect_free, NULL, /* DOING */ NULL, /* DO_MORE */ NULL, /* DO_DONE */ NULL, /* PERFORM */ NULL, /* TOOFAST */ NULL, /* DONE */ Curl_init_completed, /* COMPLETED */ NULL /* MSGSENT */ }; #if defined(DEBUGBUILD) && defined(<API key>) (void) lineno; #endif if(oldstate == state) /* don't bother when the new state is the same as the old state */ return; data->mstate = state; #if defined(DEBUGBUILD) && !defined(<API key>) if(data->mstate >= <API key> && data->mstate < <API key>) { long connection_id = -5000; if(data->conn) connection_id = data->conn->connection_id; infof(data, "STATE: %s => %s handle %p; line %d (connection #%ld)\n", statename[oldstate], statename[data->mstate], (void *)data, lineno, connection_id); } #endif if(state == <API key>) /* changing to COMPLETED means there's one less easy handle 'alive' */ data->multi->num_alive /* if this state has an init-function, run it */ if(finit[state]) finit[state](data); } #ifndef DEBUGBUILD #define multistate(x,y) mstate(x,y) #else #define multistate(x,y) mstate(x,y, __LINE__) #endif /* * We add one of these structs to the sockhash for each socket */ struct Curl_sh_entry { struct curl_hash transfers; /* hash of transfers using this socket */ unsigned int action; /* what combined action READ/WRITE this socket waits for */ void *socketp; /* settable by users with curl_multi_assign() */ unsigned int users; /* number of transfers using this */ unsigned int readers; /* this many transfers want to read */ unsigned int writers; /* this many transfers want to write */ }; /* bits for 'action' having no bits means this socket is not expecting any action */ #define SH_READ 1 #define SH_WRITE 2 /* look up a given socket in the socket hash, skip invalid sockets */ static struct Curl_sh_entry *sh_getentry(struct curl_hash *sh, curl_socket_t s) { if(s != CURL_SOCKET_BAD) { /* only look for proper sockets */ return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); } return NULL; } #define TRHASH_SIZE 13 static size_t trhash(void *key, size_t key_length, size_t slots_num) { size_t keyval = (size_t)*(struct Curl_easy **)key; (void) key_length; return (keyval % slots_num); } static size_t trhash_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void)k1_len; (void)k2_len; return *(struct Curl_easy **)k1 == *(struct Curl_easy **)k2; } static void trhash_dtor(void *nada) { (void)nada; } /* make sure this socket is present in the hash for this handle */ static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh, curl_socket_t s) { struct Curl_sh_entry *there = sh_getentry(sh, s); struct Curl_sh_entry *check; if(there) { /* it is present, return fine */ return there; } /* not present, add it */ check = calloc(1, sizeof(struct Curl_sh_entry)); if(!check) return NULL; /* major failure */ if(Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash, trhash_compare, trhash_dtor)) { free(check); return NULL; } /* make/add new hash entry */ if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) { free(check); return NULL; /* major failure */ } return check; /* things are good in sockhash land */ } /* delete the given socket + handle from the hash */ static void sh_delentry(struct Curl_sh_entry *entry, struct curl_hash *sh, curl_socket_t s) { Curl_hash_destroy(&entry->transfers); /* We remove the hash entry. This will end up in a call to sh_freeentry(). */ Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); } /* * free a sockhash entry */ static void sh_freeentry(void *freethis) { struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis; free(p); } static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void) k1_len; (void) k2_len; return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2)); } static size_t hash_fd(void *key, size_t key_length, size_t slots_num) { curl_socket_t fd = *((curl_socket_t *) key); (void) key_length; return (fd % slots_num); } /* * sh_init() creates a new socket hash and returns the handle for it. * * Quote from README.multi_socket: * * "Some tests at 7000 and 9000 connections showed that the socket hash lookup * is somewhat of a bottle neck. Its current implementation may be a bit too * limiting. It simply has a fixed-size array, and on each entry in the array * it has a linked list with entries. So the hash only checks which list to * scan through. The code I had used so for used a list with merely 7 slots * (as that is what the DNS hash uses) but with 7000 connections that would * make an average of 1000 nodes in each list to run through. I upped that to * 97 slots (I believe a prime is suitable) and noticed a significant speed * increase. I need to reconsider the hash implementation or use a rather * large default value like this. At 9000 connections I was still below 10us * per call." * */ static int sh_init(struct curl_hash *hash, int hashsize) { return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare, sh_freeentry); } /* * multi_addmsg() * * Called when a transfer is completed. Adds the given msg pointer to * the list kept in the multi handle. */ static CURLMcode multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg) { <API key>(&multi->msglist, multi->msglist.tail, msg, &msg->list); return CURLM_OK; } struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */ int chashsize) /* connection hash */ { struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi)); if(!multi) return NULL; multi->type = CURL_MULTI_HANDLE; if(Curl_mk_dnscache(&multi->hostcache)) goto error; if(sh_init(&multi->sockhash, hashsize)) goto error; if(Curl_conncache_init(&multi->conn_cache, chashsize)) goto error; Curl_llist_init(&multi->msglist, NULL); Curl_llist_init(&multi->pending, NULL); multi->multiplexing = CURLPIPE_MULTIPLEX; /* -1 means it not set by user, use the default value */ multi->maxconnects = -1; return multi; error: Curl_hash_destroy(&multi->sockhash); Curl_hash_destroy(&multi->hostcache); <API key>(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); free(multi); return NULL; } struct Curl_multi *curl_multi_init(void) { return Curl_multi_handle(<API key>, <API key>); } CURLMcode <API key>(struct Curl_multi *multi, struct Curl_easy *data) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return <API key>; /* Prevent users from adding same easy handle more than once and prevent adding to more than one multi stack */ if(data->multi) return CURLM_ADDED_ALREADY; if(multi->in_callback) return <API key>; /* Initialize timeout list for this handle */ Curl_llist_init(&data->state.timeoutlist, NULL); /* * No failure allowed in this function beyond this point. And no * modification of easy nor multi handle allowed before this except for * potential multi's connection cache growing which won't be undone in this * function no matter what. */ if(data->set.errorbuffer) data->set.errorbuffer[0] = 0; /* set the easy handle */ multistate(data, CURLM_STATE_INIT); /* for multi interface connections, we share DNS cache automatically if the easy handle's one is currently not set. */ if(!data->dns.hostcache || (data->dns.hostcachetype == HCACHE_NONE)) { data->dns.hostcache = &multi->hostcache; data->dns.hostcachetype = HCACHE_MULTI; } /* Point to the shared or multi handle connection cache */ if(data->share && (data->share->specifier & (1<< <API key>))) data->state.conn_cache = &data->share->conn_cache; else data->state.conn_cache = &multi->conn_cache; #ifdef USE_LIBPSL /* Do the same for PSL. */ if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL))) data->psl = &data->share->psl; else data->psl = &multi->psl; #endif /* We add the new entry last in the list. */ data->next = NULL; /* end of the line */ if(multi->easyp) { struct Curl_easy *last = multi->easylp; last->next = data; data->prev = last; multi->easylp = data; /* the new last node */ } else { /* first node, make prev NULL! */ data->prev = NULL; multi->easylp = multi->easyp = data; /* both first and last */ } /* make the Curl_easy refer back to this multi handle */ data->multi = multi; /* Set the timeout for this handle to expire really soon so that it will be taken care of even when this handle is added in the midst of operation when only the curl_multi_socket() API is used. During that flow, only sockets that time-out or have actions will be dealt with. Since this handle has no action yet, we make sure it times out to get things to happen. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* increase the node-counter */ multi->num_easy++; /* increase the alive-counter */ multi->num_alive++; /* A somewhat crude work-around for a little glitch in Curl_update_timer() that happens if the lastcall time is set to the same time when the handle is removed as when the next handle is added, as then the check in Curl_update_timer() that prevents calling the application multiple times with the same timer info will not trigger and then the new handle's timeout will not be notified to the app. The work-around is thus simply to clear the 'lastcall' variable to force Curl_update_timer() to always trigger a callback to the app when a new easy handle is added */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); /* The closure handle only ever has default timeouts set. To improve the state somewhat we clone the timeouts from each added handle so that the closure handle always has the same timeouts as the most recently added easy handle. */ data->state.conn_cache->closure_handle->set.timeout = data->set.timeout; data->state.conn_cache->closure_handle->set.<API key> = data->set.<API key>; data->state.conn_cache->closure_handle->set.no_signal = data->set.no_signal; Curl_update_timer(multi); return CURLM_OK; } #if 0 /* Debug-function, used like this: * * Curl_hash_print(multi->sockhash, <API key>); * * Enable the hash print function first by editing hash.c */ static void <API key>(void *p) { struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p; fprintf(stderr, " [easy %p/magic %x/socket %d]", (void *)sh->data, sh->data->magic, (int)sh->socket); } #endif static CURLcode multi_done(struct Curl_easy *data, CURLcode status, /* an error if this is called after an error was detected */ bool premature) { CURLcode result; struct connectdata *conn = data->conn; unsigned int i; DEBUGF(infof(data, "multi_done\n")); if(data->state.done) /* Stop if multi_done() has already been called */ return CURLE_OK; /* Stop the resolver and free its own resources (but not dns_entry yet). */ Curl_resolver_kill(conn); /* Cleanup possible redirect junk */ Curl_safefree(data->req.newurl); Curl_safefree(data->req.location); switch(status) { case <API key>: case CURLE_READ_ERROR: case CURLE_WRITE_ERROR: /* When we're aborted due to a callback return code it basically have to be counted as premature as there is trouble ahead if we don't. We have many callbacks and protocols work differently, we could potentially do this more fine-grained in the future. */ premature = TRUE; default: break; } /* this calls the protocol-specific function pointer previously set */ if(conn->handler->done) result = conn->handler->done(conn, status, premature); else result = status; if(<API key> != result) { /* avoid this if we already aborted by callback to avoid this calling another callback */ CURLcode rc = Curl_pgrsDone(conn); if(!result && rc) result = <API key>; } <API key>(data->multi); /* connection / multiplex */ detach_connnection(data); if(CONN_INUSE(conn)) { /* Stop if still used. */ DEBUGF(infof(data, "Connection still in use %zu, " "no more multi_done now!\n", conn->easyq.size)); return CURLE_OK; } data->state.done = TRUE; /* called just now! */ if(conn->dns_entry) { Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ conn->dns_entry = NULL; } <API key>(data); Curl_safefree(data->state.ulbuf); /* if the transfer was completed in a paused state there can be buffered data left to free */ for(i = 0; i < data->state.tempcount; i++) { free(data->state.tempwrite[i].buf); } data->state.tempcount = 0; /* if data->set.reuse_forbid is TRUE, it means the libcurl client has forced us to close this connection. This is ignored for requests taking place in a NTLM/NEGOTIATE authentication handshake if conn->bits.close is TRUE, it means that the connection should be closed in spite of all our efforts to be nice, due to protocol restrictions in our or the server's end if premature is TRUE, it means this connection was said to be DONE before the entire request operation is complete and thus we can't know in what state it is for re-using, so we're forced to close it. In a perfect world we can add code that keep track of if we really must close it here or not, but currently we have no such detail knowledge. */ if((data->set.reuse_forbid #if defined(USE_NTLM) && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 || conn->proxy_ntlm_state == NTLMSTATE_TYPE2) #endif #if defined(USE_SPNEGO) && !(conn-><API key> == GSS_AUTHRECV || conn-><API key> == GSS_AUTHRECV) #endif ) || conn->bits.close || (premature && !(conn->handler->flags & PROTOPT_STREAM))) { CURLcode res2 = Curl_disconnect(data, conn, premature); /* If we had an error already, make sure we return that one. But if we got a new error, return that. */ if(!result && res2) result = res2; } else { char buffer[256]; /* create string before returning the connection */ msnprintf(buffer, sizeof(buffer), "Connection #%ld to host %s left intact", conn->connection_id, conn->bits.socksproxy ? conn->socks_proxy.host.dispname : conn->bits.httpproxy ? conn->http_proxy.host.dispname : conn->bits.conn_to_host ? conn->conn_to_host.dispname : conn->host.dispname); /* the connection is no longer in use by this transfer */ if(<API key>(conn)) { /* remember the most recently used connection */ data->state.lastconnect = conn; infof(data, "%s\n", buffer); } else data->state.lastconnect = NULL; } <API key>(data); return result; } CURLMcode <API key>(struct Curl_multi *multi, struct Curl_easy *data) { struct Curl_easy *easy = data; bool premature; bool easy_owns_conn; struct curl_llist_element *e; /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return <API key>; /* Prevent users from trying to remove same easy handle more than once */ if(!data->multi) return CURLM_OK; /* it is already removed so let's say it is fine! */ if(multi->in_callback) return <API key>; premature = (data->mstate < <API key>) ? TRUE : FALSE; easy_owns_conn = (data->conn && (data->conn->data == easy)) ? TRUE : FALSE; /* If the 'state' is not INIT or COMPLETED, we might need to do something nice to put the easy_handle in a good known state when this returns. */ if(premature) { /* this handle is "alive" so we need to count down the total number of alive connections when this is removed */ multi->num_alive } if(data->conn && data->mstate > CURLM_STATE_DO && data->mstate < <API key>) { /* Set connection owner so that the DONE function closes it. We can safely do this here since connection is killed. */ data->conn->data = easy; streamclose(data->conn, "Removed with partial response"); easy_owns_conn = TRUE; } /* The timer must be shut down before data->multi is set to NULL, else the timenode will remain in the splay tree after curl_easy_cleanup is called. */ Curl_expire_clear(data); if(data->conn) { /* we must call multi_done() here (if we still own the connection) so that we don't leave a half-baked one around */ if(easy_owns_conn) { /* multi_done() clears the conn->data field to lose the association between the easy handle and the connection Note that this ignores the return code simply because there's nothing really useful to do with it anyway! */ (void)multi_done(data, data->result, premature); } } if(data->connect_queue.ptr) /* the handle was in the pending list waiting for an available connection, so go ahead and remove it */ Curl_llist_remove(&multi->pending, &data->connect_queue, NULL); if(data->dns.hostcachetype == HCACHE_MULTI) { /* stop using the multi handle's DNS cache, *after* the possible multi_done() call above */ data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } Curl_wildcard_dtor(&data->wildcard); /* destroy the timeout list that is held in the easy handle, do this *after* multi_done() as that may actually call Curl_expire that uses this */ Curl_llist_destroy(&data->state.timeoutlist, NULL); /* as this was using a shared connection cache we clear the pointer to that since we're not part of that multi handle anymore */ data->state.conn_cache = NULL; /* change state without using multistate(), only to make singlesocket() do what we want */ data->mstate = <API key>; singlesocket(multi, easy); /* to let the application know what sockets that vanish with this handle */ /* Remove the association between the connection and the handle */ if(data->conn) { data->conn->data = NULL; detach_connnection(data); } #ifdef USE_LIBPSL /* Remove the PSL association. */ if(data->psl == &multi->psl) data->psl = NULL; #endif data->multi = NULL; /* clear the association to this multi handle */ /* make sure there's no pending message in the queue sent from this easy handle */ for(e = multi->msglist.head; e; e = e->next) { struct Curl_message *msg = e->ptr; if(msg->extmsg.easy_handle == easy) { Curl_llist_remove(&multi->msglist, e, NULL); /* there can only be one from this specific handle */ break; } } /* make the previous node point to our next */ if(data->prev) data->prev->next = data->next; else multi->easyp = data->next; /* point to first node */ /* make our next point to our previous node */ if(data->next) data->next->prev = data->prev; else multi->easylp = data->prev; /* point to last node */ /* NOTE NOTE NOTE We do not touch the easy handle here! */ multi->num_easy--; /* one less to care about now */ Curl_update_timer(multi); return CURLM_OK; } /* Return TRUE if the application asked for multiplexing */ bool <API key>(const struct Curl_multi *multi) { return (multi && (multi->multiplexing)); } /* This is the only function that should clear data->conn. This will occasionally be called with the pointer already cleared. */ static void detach_connnection(struct Curl_easy *data) { struct connectdata *conn = data->conn; if(conn) Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL); data->conn = NULL; } /* This is the only function that should assign data->conn */ void <API key>(struct Curl_easy *data, struct connectdata *conn) { DEBUGASSERT(!data->conn); DEBUGASSERT(conn); data->conn = conn; <API key>(&conn->easyq, conn->easyq.tail, data, &data->conn_queue); } static int waitconnect_getsock(struct connectdata *conn, curl_socket_t *sock) { int i; int s = 0; int rc = 0; #ifdef USE_SSL if(<API key>()) return Curl_ssl_getsock(conn, sock); #endif for(i = 0; i<2; i++) { if(conn->tempsock[i] != CURL_SOCKET_BAD) { sock[s] = conn->tempsock[i]; rc |= GETSOCK_WRITESOCK(s); #ifdef ENABLE_QUIC if(conn->transport == TRNSPRT_QUIC) /* when connecting QUIC, we want to read the socket too */ rc |= GETSOCK_READSOCK(s); #endif s++; } } return rc; } static int <API key>(struct connectdata *conn, curl_socket_t *sock) { sock[0] = conn->sock[FIRSTSOCKET]; /* when we've sent a CONNECT to a proxy, we should rather wait for the socket to become readable to be able to get the response headers */ if(conn->connect_state) return GETSOCK_READSOCK(0); return GETSOCK_WRITESOCK(0); } static int domore_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn && conn->handler->domore_getsock) return conn->handler->domore_getsock(conn, socks); return GETSOCK_BLANK; } static int doing_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn && conn->handler->doing_getsock) return conn->handler->doing_getsock(conn, socks); return GETSOCK_BLANK; } static int protocol_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn->handler->proto_getsock) return conn->handler->proto_getsock(conn, socks); /* Backup getsock logic. Since there is a live socket in use, we must wait for it or it will be removed from watching when the multi_socket API is used. */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } /* returns bitmapped flags for this handle and its sockets. The 'socks[]' array contains <API key> entries. */ static int multi_getsock(struct Curl_easy *data, curl_socket_t *socks) { /* The no connection case can happen when this is called from <API key>() => singlesocket() => multi_getsock(). */ if(!data->conn) return 0; if(data->mstate > CURLM_STATE_CONNECT && data->mstate < <API key>) { /* Set up ownership correctly */ data->conn->data = data; } switch(data->mstate) { default: #if 0 /* switch back on these cases to get the compiler to check for all enums to be present */ case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */ case <API key>: case CURLM_STATE_MSGSENT: case CURLM_STATE_INIT: case CURLM_STATE_CONNECT: case CURLM_STATE_WAITDO: case CURLM_STATE_DONE: case CURLM_STATE_LAST: /* this will get called with <API key> when a handle is removed */ #endif return 0; case <API key>: return Curl_resolv_getsock(data->conn, socks); case <API key>: case <API key>: return protocol_getsock(data->conn, socks); case CURLM_STATE_DO: case CURLM_STATE_DOING: return doing_getsock(data->conn, socks); case <API key>: return <API key>(data->conn, socks); case <API key>: return waitconnect_getsock(data->conn, socks); case CURLM_STATE_DO_MORE: return domore_getsock(data->conn, socks); case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch to waiting for the same as the *PERFORM states */ case CURLM_STATE_PERFORM: return Curl_single_getsock(data->conn, socks); } } CURLMcode curl_multi_fdset(struct Curl_multi *multi, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *exc_fd_set, int *max_fd) { /* Scan through all the easy handles to get the file descriptors set. Some easy handles may not have connected to the remote host yet, and then we must make sure that is done. */ struct Curl_easy *data; int this_max_fd = -1; curl_socket_t sockbunch[<API key>]; int i; (void)exc_fd_set; /* not used */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return <API key>; data = multi->easyp; while(data) { int bitmap = multi_getsock(data, sockbunch); for(i = 0; i< <API key>; i++) { curl_socket_t s = CURL_SOCKET_BAD; if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], read_fd_set); s = sockbunch[i]; } if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], write_fd_set); s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) /* this socket is unused, break out of loop */ break; if((int)s > this_max_fd) this_max_fd = (int)s; } data = data->next; /* check next handle */ } *max_fd = this_max_fd; return CURLM_OK; } #define NUM_POLLS_ON_STACK 10 static CURLMcode Curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret, bool extrawait) /* when no socket, wait */ { struct Curl_easy *data; curl_socket_t sockbunch[<API key>]; int bitmap; unsigned int i; unsigned int nfds = 0; unsigned int curlfds; bool ufds_malloc = FALSE; long timeout_internal; int retcode = 0; struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; struct pollfd *ufds = &a_few_on_stack[0]; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return <API key>; /* Count up how many fds we have from the multi handle */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch); for(i = 0; i< <API key>; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } /* If the internally desired timeout is actually shorter than requested from the outside, then use the shorter time! But only if the internal timer is actually larger than -1! */ (void)multi_timeout(multi, &timeout_internal); if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms)) timeout_ms = (int)timeout_internal; curlfds = nfds; /* number of internal file descriptors */ nfds += extra_nfds; /* add the externally provided ones */ if(nfds > NUM_POLLS_ON_STACK) { /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes big, so at 2^29 sockets this value might wrap. When a process gets the capability to actually handle over 500 million sockets this calculation needs a integer overflow check. */ ufds = malloc(nfds * sizeof(struct pollfd)); if(!ufds) return CURLM_OUT_OF_MEMORY; ufds_malloc = TRUE; } nfds = 0; /* only do the second loop if we found descriptors in the first stage run above */ if(curlfds) { /* Add the curl handles to our pollfds first */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch); for(i = 0; i< <API key>; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLIN; ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLOUT; ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } } /* Add external file descriptions from poll-like struct curl_waitfd */ for(i = 0; i < extra_nfds; i++) { ufds[nfds].fd = extra_fds[i].fd; ufds[nfds].events = 0; if(extra_fds[i].events & CURL_WAIT_POLLIN) ufds[nfds].events |= POLLIN; if(extra_fds[i].events & CURL_WAIT_POLLPRI) ufds[nfds].events |= POLLPRI; if(extra_fds[i].events & CURL_WAIT_POLLOUT) ufds[nfds].events |= POLLOUT; ++nfds; } if(nfds) { int pollrc; /* wait... */ pollrc = Curl_poll(ufds, nfds, timeout_ms); if(pollrc > 0) { retcode = pollrc; /* copy revents results from the poll to the curl_multi_wait poll struct, the bit values of the actual underlying poll() implementation may not be the same as the ones in the public libcurl API! */ for(i = 0; i < extra_nfds; i++) { unsigned short mask = 0; unsigned r = ufds[curlfds + i].revents; if(r & POLLIN) mask |= CURL_WAIT_POLLIN; if(r & POLLOUT) mask |= CURL_WAIT_POLLOUT; if(r & POLLPRI) mask |= CURL_WAIT_POLLPRI; extra_fds[i].revents = mask; } } } if(ufds_malloc) free(ufds); if(ret) *ret = retcode; if(!extrawait || extra_fds || curlfds) /* if any socket was checked */ ; else { long sleep_ms = 0; /* Avoid busy-looping when there's nothing particular to wait for */ if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) { if(sleep_ms > timeout_ms) sleep_ms = timeout_ms; Curl_wait_ms((int)sleep_ms); } } return CURLM_OK; } CURLMcode curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE); } CURLMcode curl_multi_poll(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE); } /* * multi_ischanged() is called * * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND * => CONNECT action. * * Set 'clear' to TRUE to have it also clear the state variable. */ static bool multi_ischanged(struct Curl_multi *multi, bool clear) { bool retval = multi->recheckstate; if(clear) multi->recheckstate = FALSE; return retval; } CURLMcode <API key>(struct Curl_multi *multi, struct Curl_easy *data, struct connectdata *conn) { CURLMcode rc; if(multi->in_callback) return <API key>; rc = <API key>(multi, data); if(!rc) { struct SingleRequest *k = &data->req; /* pass in NULL for 'conn' here since we don't want to init the connection, only this transfer */ Curl_init_do(data, NULL); /* take this handle to the perform state right away */ multistate(data, CURLM_STATE_PERFORM); <API key>(data, conn); k->keepon |= KEEP_RECV; /* setup to receive! */ } return rc; } /* * do_complete is called when the DO actions are complete. * * We init chunking and trailer bits to their default values here immediately * before receiving any header data for the current request. */ static void do_complete(struct connectdata *conn) { conn->data->req.chunk = FALSE; Curl_pgrsTime(conn->data, TIMER_PRETRANSFER); } static CURLcode multi_do(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; DEBUGASSERT(conn); DEBUGASSERT(conn->handler); if(conn->handler->do_it) { /* generic protocol-specific function pointer set in curl_connect() */ result = conn->handler->do_it(conn, done); if(!result && *done) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); } return result; } /* * multi_do_more() is called during the DO_MORE multi state. It is basically a * second stage DO state which (wrongly) was introduced to support FTP's * second connection. * * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to * DOING state there's more work to do! */ static CURLcode multi_do_more(struct connectdata *conn, int *complete) { CURLcode result = CURLE_OK; *complete = 0; if(conn->handler->do_more) result = conn->handler->do_more(conn, complete); if(!result && (*complete == 1)) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); return result; } /* * We are doing protocol-specific connecting and this is being called over and * over from the multi interface until the connection phase is done on * protocol layer. */ static CURLcode protocol_connecting(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->connecting) { *done = FALSE; result = conn->handler->connecting(conn, done); } else *done = TRUE; return result; } /* * We are DOING this is being called over and over from the multi interface * until the DOING phase is done on protocol layer. */ static CURLcode protocol_doing(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->doing) { *done = FALSE; result = conn->handler->doing(conn, done); } else *done = TRUE; return result; } /* * We have discovered that the TCP connection has been successful, we can now * proceed with some action. * */ static CURLcode protocol_connect(struct connectdata *conn, bool *protocol_done) { CURLcode result = CURLE_OK; DEBUGASSERT(conn); DEBUGASSERT(protocol_done); *protocol_done = FALSE; if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) { /* We already are connected, get back. This may happen when the connect worked fine in the first call, like when we connect to a local server or proxy. Note that we don't know if the protocol is actually done. Unless this protocol doesn't have any protocol-connect callback, as then we know we're done. */ if(!conn->handler->connecting) *protocol_done = TRUE; return CURLE_OK; } if(!conn->bits.protoconnstart) { result = Curl_proxy_connect(conn, FIRSTSOCKET); if(result) return result; if(<API key>()) /* wait for HTTPS proxy SSL initialization to complete */ return CURLE_OK; if(conn->bits.tunnel_proxy && conn->bits.httpproxy && <API key>(conn)) /* when using an HTTP tunnel proxy, await complete tunnel establishment before proceeding further. Return CURLE_OK so we'll be called again */ return CURLE_OK; if(conn->handler->connect_it) { /* is there a protocol-specific connect() procedure? */ /* Call the protocol-specific connect function */ result = conn->handler->connect_it(conn, protocol_done); } else *protocol_done = TRUE; /* it has started, possibly even completed but that knowledge isn't stored in this bit! */ if(!result) conn->bits.protoconnstart = TRUE; } return result; /* pass back status */ } static CURLMcode multi_runsingle(struct Curl_multi *multi, struct curltime now, struct Curl_easy *data) { struct Curl_message *msg = NULL; bool connected; bool async; bool protocol_connected = FALSE; bool dophase_done = FALSE; bool done = FALSE; CURLMcode rc; CURLcode result = CURLE_OK; timediff_t timeout_ms; timediff_t recv_timeout_ms; timediff_t send_timeout_ms; int control; if(!GOOD_EASY_HANDLE(data)) return <API key>; do { /* A "stream" here is a logical stream if the protocol can handle that (HTTP/2), or the full connection for older protocols */ bool stream_error = FALSE; rc = CURLM_OK; DEBUGASSERT((data->mstate <= CURLM_STATE_CONNECT) || (data->mstate >= CURLM_STATE_DONE) || data->conn); if(!data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_DONE) { /* In all these states, the code will blindly access 'data->conn' so this is precaution that it isn't NULL. And it silences static analyzers. */ failf(data, "In state %d with no conn, bail out!\n", data->mstate); return <API key>; } if(multi_ischanged(multi, TRUE)) { DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n")); <API key>(multi); /* multiplexed */ } if(data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < <API key>) { /* Make sure we set the connection's current owner */ data->conn->data = data; } if(data->conn && (data->mstate >= CURLM_STATE_CONNECT) && (data->mstate < <API key>)) { /* we need to wait for the connect state as only then is the start time stored, but we must not check already completed handles */ timeout_ms = Curl_timeleft(data, &now, (data->mstate <= CURLM_STATE_DO)? TRUE:FALSE); if(timeout_ms < 0) { /* Handle timed out */ if(data->mstate == <API key>) failf(data, "Resolving timed out after %" <API key> " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else if(data->mstate == <API key>) failf(data, "Connection timed out after %" <API key> " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else { struct SingleRequest *k = &data->req; if(k->size != -1) { failf(data, "Operation timed out after %" <API key> " milliseconds with %" <API key> " out of %" <API key> " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount, k->size); } else { failf(data, "Operation timed out after %" <API key> " milliseconds with %" <API key> " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount); } } /* Force connection closed if the connection has indeed been used */ if(data->mstate > CURLM_STATE_DO) { streamclose(data->conn, "Disconnected with pending data"); stream_error = TRUE; } result = <API key>; (void)multi_done(data, result, TRUE); /* Skip the statemachine and go directly to error handling section. */ goto statemachine_end; } } switch(data->mstate) { case CURLM_STATE_INIT: /* init this transfer. */ result = Curl_pretransfer(data); if(!result) { /* after init, go CONNECT */ multistate(data, CURLM_STATE_CONNECT); Curl_pgrsTime(data, TIMER_STARTOP); rc = <API key>; } break; case <API key>: /* We will stay here until there is a connection available. Then we try again in the CURLM_STATE_CONNECT state. */ break; case CURLM_STATE_CONNECT: /* Connect. We want to get a connection identifier filled in. */ Curl_pgrsTime(data, TIMER_STARTSINGLE); if(data->set.timeout) Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT); if(data->set.connecttimeout) Curl_expire(data, data->set.connecttimeout, <API key>); result = Curl_connect(data, &async, &protocol_connected); if(<API key> == result) { /* There was no connection available. We will go to the pending state and wait for an available connection. */ multistate(data, <API key>); /* add this handle to the list of connect-pending handles */ <API key>(&multi->pending, multi->pending.tail, data, &data->connect_queue); result = CURLE_OK; break; } else if(data->state.previouslypending) { /* this transfer comes from the pending queue so try move another */ infof(data, "Transfer was pending, now try another\n"); <API key>(data->multi); } if(!result) { if(async) /* We're now waiting for an asynchronous name lookup */ multistate(data, <API key>); else { /* after the connect has been sent off, go WAITCONNECT unless the protocol connect is already done and we can go directly to WAITDO or DO! */ rc = <API key>; if(protocol_connected) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(<API key>(data->conn)) multistate(data, <API key>); else #endif multistate(data, <API key>); } } } break; case <API key>: /* awaiting an asynch name resolve to complete */ { struct Curl_dns_entry *dns = NULL; struct connectdata *conn = data->conn; const char *hostname; DEBUGASSERT(conn); if(conn->bits.httpproxy) hostname = conn->http_proxy.host.name; else if(conn->bits.conn_to_host) hostname = conn->conn_to_host.name; else hostname = conn->host.name; /* check if we have the name resolved by now */ dns = Curl_fetch_addr(conn, hostname, (int)conn->port); if(dns) { #ifdef CURLRES_ASYNCH conn->async.dns = dns; conn->async.done = TRUE; #endif result = CURLE_OK; infof(data, "Hostname '%s' was found in DNS cache\n", hostname); } if(!dns) result = Curl_resolv_check(data->conn, &dns); /* Update sockets here, because the socket(s) may have been closed and the application thus needs to be told, even if it is likely that the same socket(s) will again be used further down. If the name has not yet been resolved, it is likely that new sockets have been opened in an attempt to contact another resolver. */ singlesocket(multi, data); if(dns) { /* Perform the next step in the connection phase, and then move on to the WAITCONNECT state */ result = Curl_once_resolved(data->conn, &protocol_connected); if(result) /* if Curl_once_resolved() returns failure, the connection struct is already freed and gone */ data->conn = NULL; /* no more connection */ else { /* call again please so that we get the next socket setup */ rc = <API key>; if(protocol_connected) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(<API key>(data->conn)) multistate(data, <API key>); else #endif multistate(data, <API key>); } } } if(result) { /* failure detected */ stream_error = TRUE; break; } } break; #ifndef CURL_DISABLE_HTTP case <API key>: /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */ DEBUGASSERT(data->conn); result = Curl_http_connect(data->conn, &protocol_connected); if(data->conn->bits.<API key>) { rc = <API key>; /* connect back to proxy again */ result = CURLE_OK; multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_CONNECT); } else if(!result) { if((data->conn->http_proxy.proxytype != CURLPROXY_HTTPS || data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) && <API key>(data->conn)) { rc = <API key>; /* initiate protocol connect phase */ multistate(data, <API key>); } } else if(result) stream_error = TRUE; break; #endif case <API key>: /* awaiting a completion of an asynch TCP connect */ DEBUGASSERT(data->conn); result = Curl_is_connected(data->conn, FIRSTSOCKET, &connected); if(connected && !result) { #ifndef CURL_DISABLE_HTTP if((data->conn->http_proxy.proxytype == CURLPROXY_HTTPS && !data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) || <API key>(data->conn)) { multistate(data, <API key>); break; } #endif rc = <API key>; multistate(data, data->conn->bits.tunnel_proxy? <API key>: <API key>); } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; break; } break; case <API key>: result = protocol_connect(data->conn, &protocol_connected); if(!result && !protocol_connected) /* switch to waiting state */ multistate(data, <API key>); else if(!result) { /* protocol connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = <API key>; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case <API key>: /* protocol-specific connect phase */ result = protocol_connecting(data->conn, &protocol_connected); if(!result && protocol_connected) { /* after the connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = <API key>; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_DO: if(data->set.connect_only) { /* keep connection open for application to use the socket */ connkeep(data->conn, "CONNECT_ONLY"); multistate(data, CURLM_STATE_DONE); result = CURLE_OK; rc = <API key>; } else { /* Perform the protocol's DO action */ result = multi_do(data, &dophase_done); /* When multi_do() returns failure, data->conn might be NULL! */ if(!result) { if(!dophase_done) { #ifndef CURL_DISABLE_FTP /* some steps needed for wildcard matching */ if(data->state.wildcardmatch) { struct WildcardData *wc = &data->wildcard; if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { /* skip some states if it is important */ multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_DONE); rc = <API key>; break; } } #endif /* DO was not completed in one function call, we must continue DOING... */ multistate(data, CURLM_STATE_DOING); rc = CURLM_OK; } /* after DO, go DO_DONE... or DO_MORE */ else if(data->conn->bits.do_more) { /* we're supposed to do more, but we need to sit down, relax and wait a little while first */ multistate(data, CURLM_STATE_DO_MORE); rc = CURLM_OK; } else { /* we're done with the DO, now DO_DONE */ multistate(data, CURLM_STATE_DO_DONE); rc = <API key>; } } else if((CURLE_SEND_ERROR == result) && data->conn->bits.reuse) { /* * In this situation, a connection that we were trying to use * may have unexpectedly died. If possible, send the connection * back to the CONNECT phase so we can try again. */ char *newurl = NULL; followtype follow = FOLLOW_NONE; CURLcode drc; drc = Curl_retry_request(data->conn, &newurl); if(drc) { /* a failure here pretty much implies an out of memory */ result = drc; stream_error = TRUE; } Curl_posttransfer(data); drc = multi_done(data, result, FALSE); /* When set to retry the connection, we must to go back to * the CONNECT state */ if(newurl) { if(!drc || (drc == CURLE_SEND_ERROR)) { follow = FOLLOW_RETRY; drc = Curl_follow(data, newurl, follow); if(!drc) { multistate(data, CURLM_STATE_CONNECT); rc = <API key>; result = CURLE_OK; } else { /* Follow failed */ result = drc; } } else { /* done didn't return OK or SEND_ERROR */ result = drc; } } else { /* Have error handler disconnect conn if we can't retry */ stream_error = TRUE; } free(newurl); } else { /* failure detected */ Curl_posttransfer(data); if(data->conn) multi_done(data, result, FALSE); stream_error = TRUE; } } break; case CURLM_STATE_DOING: /* we continue DOING until the DO phase is complete */ DEBUGASSERT(data->conn); result = protocol_doing(data->conn, &dophase_done); if(!result) { if(dophase_done) { /* after DO, go DO_DONE or DO_MORE */ multistate(data, data->conn->bits.do_more? CURLM_STATE_DO_MORE: CURLM_STATE_DO_DONE); rc = <API key>; } /* dophase_done */ } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_MORE: /* * When we are connected, DO MORE and then go DO_DONE */ DEBUGASSERT(data->conn); result = multi_do_more(data->conn, &control); if(!result) { if(control) { /* if positive, advance to DO_DONE if negative, go back to DOING */ multistate(data, control == 1? CURLM_STATE_DO_DONE: CURLM_STATE_DOING); rc = <API key>; } else /* stay in DO_MORE */ rc = CURLM_OK; } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_DONE: DEBUGASSERT(data->conn); if(data->conn->bits.multiplex) /* Check if we can move pending requests to send pipe */ <API key>(multi); /* multiplexed */ /* Only perform the transfer if there's a good socket to work with. Having both BAD is a signal to skip immediately to DONE */ if((data->conn->sockfd != CURL_SOCKET_BAD) || (data->conn->writesockfd != CURL_SOCKET_BAD)) multistate(data, CURLM_STATE_PERFORM); else { #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch && ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) { data->wildcard.state = CURLWC_DONE; } #endif multistate(data, CURLM_STATE_DONE); } rc = <API key>; break; case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */ DEBUGASSERT(data->conn); /* if both rates are within spec, resume transfer */ if(Curl_pgrsUpdate(data->conn)) result = <API key>; else result = Curl_speedcheck(data, now); if(!result) { send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = <API key>(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = <API key>(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(!send_timeout_ms && !recv_timeout_ms) { multistate(data, CURLM_STATE_PERFORM); Curl_ratelimit(data, now); } else if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); } break; case CURLM_STATE_PERFORM: { char *newurl = NULL; bool retry = FALSE; bool comeback = FALSE; /* check if over send speed */ send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = <API key>(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); /* check if over recv speed */ recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = <API key>(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(send_timeout_ms || recv_timeout_ms) { Curl_ratelimit(data, now); multistate(data, CURLM_STATE_TOOFAST); if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); break; } /* read/write data if it is ready to do so */ result = Curl_readwrite(data->conn, data, &done, &comeback); if(done || (result == CURLE_RECV_ERROR)) { /* If CURLE_RECV_ERROR happens early enough, we assume it was a race * condition and the server closed the re-used connection exactly when * we wanted to use it, so figure out if that is indeed the case. */ CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) retry = (newurl)?TRUE:FALSE; else if(!result) result = ret; if(retry) { /* if we are to retry, set the result to OK and consider the request as done */ result = CURLE_OK; done = TRUE; } } else if((CURLE_HTTP2_STREAM == result) && <API key>(data->conn)) { CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) { infof(data, "Downgrades to HTTP/1.1!\n"); data->set.httpversion = <API key>; /* clear the error message bit too as we ignore the one we got */ data->state.errorbuf = FALSE; if(!newurl) /* typically for HTTP_1_1_REQUIRED error on first flight */ newurl = strdup(data->change.url); /* if we are to retry, set the result to OK and consider the request as done */ retry = TRUE; result = CURLE_OK; done = TRUE; } else result = ret; } if(result) { /* * The transfer phase returned error, we mark the connection to get * closed to prevent being re-used. This is because we can't possibly * know if the connection is in a good shape or not now. Unless it is * a protocol which uses two "channels" like FTP, as then the error * happened in the data connection. */ if(!(data->conn->handler->flags & PROTOPT_DUAL) && result != CURLE_HTTP2_STREAM) streamclose(data->conn, "Transfer returned error"); Curl_posttransfer(data); multi_done(data, result, TRUE); } else if(done) { followtype follow = FOLLOW_NONE; /* call this even if the readwrite function returned error */ Curl_posttransfer(data); /* When we follow redirects or is set to retry the connection, we must to go back to the CONNECT state */ if(data->req.newurl || retry) { if(!retry) { /* if the URL is a follow-location and not just a retried request then figure out the URL here */ free(newurl); newurl = data->req.newurl; data->req.newurl = NULL; follow = FOLLOW_REDIR; } else follow = FOLLOW_RETRY; (void)multi_done(data, CURLE_OK, FALSE); /* multi_done() might return CURLE_GOT_NOTHING */ result = Curl_follow(data, newurl, follow); if(!result) { multistate(data, CURLM_STATE_CONNECT); rc = <API key>; } free(newurl); } else { /* after the transfer is done, go DONE */ /* but first check to see if we got a location info even though we're not following redirects */ if(data->req.location) { free(newurl); newurl = data->req.location; data->req.location = NULL; result = Curl_follow(data, newurl, FOLLOW_FAKE); free(newurl); if(result) { stream_error = TRUE; result = multi_done(data, result, TRUE); } } if(!result) { multistate(data, CURLM_STATE_DONE); rc = <API key>; } } } else if(comeback) rc = <API key>; break; } case CURLM_STATE_DONE: /* this state is highly transient, so run another loop after this */ rc = <API key>; if(data->conn) { CURLcode res; if(data->conn->bits.multiplex) /* Check if we can move pending requests to connection */ <API key>(multi); /* multiplexing */ /* post-transfer command */ res = multi_done(data, result, FALSE); /* allow a previously set error code take precedence */ if(!result) result = res; /* * If there are other handles on the connection, multi_done won't set * conn to NULL. In such a case, <API key>() can * access free'd data, if the connection is free'd and the handle * removed before we perform the processing in <API key> */ if(data->conn) detach_connnection(data); } #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch) { if(data->wildcard.state != CURLWC_DONE) { /* if a wildcard is set and we are not ending -> lets start again with CURLM_STATE_INIT */ multistate(data, CURLM_STATE_INIT); break; } } #endif /* after we have DONE what we're supposed to do, go COMPLETED, and it doesn't matter what the multi_done() returned! */ multistate(data, <API key>); break; case <API key>: break; case CURLM_STATE_MSGSENT: data->result = result; return CURLM_OK; /* do nothing */ default: return <API key>; } statemachine_end: if(data->mstate < <API key>) { if(result) { /* * If an error was returned, and we aren't in completed state now, * then we go to completed and consider this transfer aborted. */ /* NOTE: no attempt to disconnect connections must be made in the case blocks above - cleanup happens only here */ /* Check if we can move pending requests to send pipe */ <API key>(multi); /* connection */ if(data->conn) { if(stream_error) { /* Don't attempt to send data over a connection that timed out */ bool dead_connection = result == <API key>; struct connectdata *conn = data->conn; /* This is where we make sure that the conn pointer is reset. We don't have to do this in every case block above where a failure is detected */ detach_connnection(data); /* disconnect properly */ Curl_disconnect(data, conn, dead_connection); } } else if(data->mstate == CURLM_STATE_CONNECT) { /* Curl_connect() failed */ (void)Curl_posttransfer(data); } multistate(data, <API key>); rc = <API key>; } /* if there's still a connection to use, call the progress function */ else if(data->conn && Curl_pgrsUpdate(data->conn)) { /* aborted due to progress callback return code must close the connection */ result = <API key>; streamclose(data->conn, "Aborted by callback"); /* if not yet in DONE state, go there, otherwise COMPLETED */ multistate(data, (data->mstate < CURLM_STATE_DONE)? CURLM_STATE_DONE: <API key>); rc = <API key>; } } if(<API key> == data->mstate) { if(data->set.fmultidone) { /* signal via callback instead */ data->set.fmultidone(data, result); } else { /* now fill in the Curl_message with this info */ msg = &data->msg; msg->extmsg.msg = CURLMSG_DONE; msg->extmsg.easy_handle = data; msg->extmsg.data.result = result; rc = multi_addmsg(multi, msg); DEBUGASSERT(!data->conn); } multistate(data, CURLM_STATE_MSGSENT); } } while((rc == <API key>) || multi_ischanged(multi, FALSE)); data->result = result; return rc; } CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles) { struct Curl_easy *data; CURLMcode returncode = CURLM_OK; struct Curl_tree *t; struct curltime now = Curl_now(); if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return <API key>; data = multi->easyp; while(data) { CURLMcode result; SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(result) returncode = result; data = data->next; /* operate on next handle */ } /* * Simply remove all expired timers from the splay since handles are dealt * with unconditionally by this function and curl_multi_timeout() requires * that already passed/handled expire times are removed from the splay. * * It is important that the 'now' value is set at the entry of this function * and not for the current time as it may have ticked a little while since * then and then we risk this loop to remove timers that actually have not * been handled! */ do { multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) /* the removed may have another timeout in queue */ (void)add_next_timeout(now, multi, t->payload); } while(t); *running_handles = multi->num_alive; if(CURLM_OK >= returncode) Curl_update_timer(multi); return returncode; } CURLMcode curl_multi_cleanup(struct Curl_multi *multi) { struct Curl_easy *data; struct Curl_easy *nextdata; if(GOOD_MULTI_HANDLE(multi)) { if(multi->in_callback) return <API key>; multi->type = 0; /* not good anymore */ /* Firsrt remove all remaining easy handles */ data = multi->easyp; while(data) { nextdata = data->next; if(!data->state.done && data->conn) /* if DONE was never called for this handle */ (void)multi_done(data, CURLE_OK, TRUE); if(data->dns.hostcachetype == HCACHE_MULTI) { /* clear out the usage of the shared DNS cache */ <API key>(data, data->dns.hostcache); data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } /* Clear the pointer to the connection cache */ data->state.conn_cache = NULL; data->multi = NULL; /* clear the association */ #ifdef USE_LIBPSL if(data->psl == &multi->psl) data->psl = NULL; #endif data = nextdata; } /* Close all the connections in the connection cache */ <API key>(&multi->conn_cache); Curl_hash_destroy(&multi->sockhash); <API key>(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); Curl_hash_destroy(&multi->hostcache); Curl_psl_destroy(&multi->psl); free(multi); return CURLM_OK; } return CURLM_BAD_HANDLE; } /* * <API key>() * * This function is the primary way for a multi/multi_socket application to * figure out if a transfer has ended. We MUST make this function as fast as * possible as it will be polled frequently and we MUST NOT scan any lists in * here to figure out things. We must scale fine to thousands of handles and * beyond. The current design is fully O(1). */ CURLMsg *<API key>(struct Curl_multi *multi, int *msgs_in_queue) { struct Curl_message *msg; *msgs_in_queue = 0; /* default to none */ if(GOOD_MULTI_HANDLE(multi) && !multi->in_callback && Curl_llist_count(&multi->msglist)) { /* there is one or more messages in the list */ struct curl_llist_element *e; /* extract the head of the list to return */ e = multi->msglist.head; msg = e->ptr; /* remove the extracted entry */ Curl_llist_remove(&multi->msglist, e, NULL); *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist)); return &msg->extmsg; } return NULL; } /* * singlesocket() checks what sockets we deal with and their "action state" * and if we have a different state in any of those sockets from last time we * call the callback accordingly. */ static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data) { curl_socket_t socks[<API key>]; int i; struct Curl_sh_entry *entry; curl_socket_t s; int num; unsigned int curraction; int actions[<API key>]; for(i = 0; i< <API key>; i++) socks[i] = CURL_SOCKET_BAD; /* Fill in the 'current' struct with the state as it is now: what sockets to supervise and for what actions */ curraction = multi_getsock(data, socks); /* We have 0 .. N sockets already and we get to know about the 0 .. M sockets we should have from now on. Detect the differences, remove no longer supervised ones and add new ones */ /* walk over the sockets we got right now */ for(i = 0; (i< <API key>) && (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i))); i++) { unsigned int action = CURL_POLL_NONE; unsigned int prevaction = 0; unsigned int comboaction; bool sincebefore = FALSE; s = socks[i]; /* get it from the hash */ entry = sh_getentry(&multi->sockhash, s); if(curraction & GETSOCK_READSOCK(i)) action |= CURL_POLL_IN; if(curraction & GETSOCK_WRITESOCK(i)) action |= CURL_POLL_OUT; actions[i] = action; if(entry) { /* check if new for this transfer */ int j; for(j = 0; j< data->numsocks; j++) { if(s == data->sockets[j]) { prevaction = data->actions[j]; sincebefore = TRUE; break; } } } else { /* this is a socket we didn't have before, add it to the hash! */ entry = sh_addentry(&multi->sockhash, s); if(!entry) /* fatal */ return CURLM_OUT_OF_MEMORY; } if(sincebefore && (prevaction != action)) { /* Socket was used already, but different action now */ if(prevaction & CURL_POLL_IN) entry->readers if(prevaction & CURL_POLL_OUT) entry->writers if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; } else if(!sincebefore) { /* a new user */ entry->users++; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; /* add 'data' to the transfer hash on this socket! */ if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */ sizeof(struct Curl_easy *), data)) return CURLM_OUT_OF_MEMORY; } comboaction = (entry->writers? CURL_POLL_OUT : 0) | (entry->readers ? CURL_POLL_IN : 0); /* socket existed before and has the same action set as before */ if(sincebefore && (entry->action == comboaction)) /* same, continue */ continue; if(multi->socket_cb) multi->socket_cb(data, s, comboaction, multi->socket_userp, entry->socketp); entry->action = comboaction; /* store the current action state */ } num = i; /* number of sockets */ /* when we've walked over all the sockets we should have right now, we must make sure to detect sockets that are removed */ for(i = 0; i< data->numsocks; i++) { int j; bool stillused = FALSE; s = data->sockets[i]; for(j = 0; j < num; j++) { if(s == socks[j]) { /* this is still supervised */ stillused = TRUE; break; } } if(stillused) continue; entry = sh_getentry(&multi->sockhash, s); /* if this is NULL here, the socket has been closed and notified so already by Curl_multi_closed() */ if(entry) { int oldactions = data->actions[i]; /* this socket has been removed. Decrease user count */ entry->users if(oldactions & CURL_POLL_OUT) entry->writers if(oldactions & CURL_POLL_IN) entry->readers if(!entry->users) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); sh_delentry(entry, &multi->sockhash, s); } else { /* still users, but remove this handle as a user of this socket */ if(Curl_hash_delete(&entry->transfers, (char *)&data, sizeof(struct Curl_easy *))) { DEBUGASSERT(NULL); } } } } /* for loop over numsocks */ memcpy(data->sockets, socks, num*sizeof(curl_socket_t)); memcpy(data->actions, actions, num*sizeof(int)); data->numsocks = num; return CURLM_OK; } void Curl_updatesocket(struct Curl_easy *data) { singlesocket(data->multi, data); } /* * Curl_multi_closed() * * Used by the connect code to tell the multi_socket code that one of the * sockets we were using is about to be closed. This function will then * remove it from the sockethash for this handle to make the multi_socket API * behave properly, especially for the case when libcurl will create another * socket again and it gets the same file descriptor number. */ void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s) { if(data) { /* if there's still an easy handle associated with this connection */ struct Curl_multi *multi = data->multi; if(multi) { /* this is set if this connection is part of a handle that is added to a multi handle, and only then this is necessary */ struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(entry) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); /* now remove it from the socket hash */ sh_delentry(entry, &multi->sockhash, s); } } } } /* * add_next_timeout() * * Each Curl_easy has a list of timeouts. The add_next_timeout() is called * when it has just been removed from the splay tree because the timeout has * expired. This function is then to advance in the list to pick the next * timeout to use (skip the already expired ones) and add this node back to * the splay tree again. * * The splay tree only has each sessionhandle as a single node and the nearest * timeout is used to sort it on. */ static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d) { struct curltime *tv = &d->state.expiretime; struct curl_llist *list = &d->state.timeoutlist; struct curl_llist_element *e; struct time_node *node = NULL; /* move over the timeout list for this specific handle and remove all timeouts that are now passed tense and store the next pending timeout in *tv */ for(e = list->head; e;) { struct curl_llist_element *n = e->next; timediff_t diff; node = (struct time_node *)e->ptr; diff = Curl_timediff(node->time, now); if(diff <= 0) /* remove outdated entry */ Curl_llist_remove(list, e, NULL); else /* the list is sorted so get out on the first mismatch */ break; e = n; } e = list->head; if(!e) { /* clear the expire times within the handles that we remove from the splay tree */ tv->tv_sec = 0; tv->tv_usec = 0; } else { /* copy the first entry to 'tv' */ memcpy(tv, &node->time, sizeof(*tv)); /* Insert this node again into the splay. Keep the timer in the list in case we need to recompute future timers. */ multi->timetree = Curl_splayinsert(*tv, multi->timetree, &d->state.timenode); } return CURLM_OK; } static CURLMcode multi_socket(struct Curl_multi *multi, bool checkall, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result = CURLM_OK; struct Curl_easy *data = NULL; struct Curl_tree *t; struct curltime now = Curl_now(); if(checkall) { /* *perform() deals with running_handles on its own */ result = curl_multi_perform(multi, running_handles); /* walk through each easy handle and do the socket state change magic and callbacks */ if(result != CURLM_BAD_HANDLE) { data = multi->easyp; while(data && !result) { result = singlesocket(multi, data); data = data->next; } } /* or should we fall-through and do the timer-based stuff? */ return result; } if(s != CURL_SOCKET_TIMEOUT) { struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(!entry) /* Unmatched socket, we can't act on it but we ignore this fact. In real-world tests it has been proved that libevent can in fact give the application actions even though the socket was just previously asked to get removed, so thus we better survive stray socket actions and just move on. */ ; else { struct curl_hash_iterator iter; struct curl_hash_element *he; /* the socket can be shared by many transfers, iterate */ <API key>(&entry->transfers, &iter); for(he = <API key>(&iter); he; he = <API key>(&iter)) { data = (struct Curl_easy *)he->ptr; DEBUGASSERT(data); DEBUGASSERT(data->magic == <API key>); if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK)) /* set socket event bitmask if they're not locked */ data->conn->cselect_bits = ev_bitmask; Curl_expire(data, 0, EXPIRE_RUN_NOW); } /* Now we fall-through and do the timer-based stuff, since we don't want to force the user to have to deal with timeouts as long as at least one connection in fact has traffic. */ data = NULL; /* set data to NULL again to avoid calling multi_runsingle() in case there's no need to */ now = Curl_now(); /* get a newer time since the multi_runsingle() loop may have taken some time */ } } else { /* Asked to run due to time-out. Clear the 'lastcall' variable to force Curl_update_timer() to trigger a callback to the app again even if the same timeout is still the one to run after this call. That handles the case when the application asks libcurl to run the timeout prematurely. */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); } /* * The loop following here will go on as long as there are expire-times left * to process in the splay and 'data' will be re-assigned for every expired * handle we deal with. */ do { /* the first loop lap 'data' can be NULL */ if(data) { SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(CURLM_OK >= result) { /* get the socket(s) and check if the state has been changed since last */ result = singlesocket(multi, data); if(result) return result; } } /* Check if there's one (more) expired timer to deal with! This function extracts a matching node if there is one */ multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) { data = t->payload; /* assign this for next loop */ (void)add_next_timeout(now, multi, t->payload); } } while(t); *running_handles = multi->num_alive; return result; } #undef curl_multi_setopt CURLMcode curl_multi_setopt(struct Curl_multi *multi, CURLMoption option, ...) { CURLMcode res = CURLM_OK; va_list param; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return <API key>; va_start(param, option); switch(option) { case <API key>: multi->socket_cb = va_arg(param, <API key>); break; case CURLMOPT_SOCKETDATA: multi->socket_userp = va_arg(param, void *); break; case <API key>: multi->push_cb = va_arg(param, curl_push_callback); break; case CURLMOPT_PUSHDATA: multi->push_userp = va_arg(param, void *); break; case CURLMOPT_PIPELINING: multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX; break; case <API key>: multi->timer_cb = va_arg(param, <API key>); break; case CURLMOPT_TIMERDATA: multi->timer_userp = va_arg(param, void *); break; case <API key>: multi->maxconnects = va_arg(param, long); break; case <API key>: multi-><API key> = va_arg(param, long); break; case <API key>: multi-><API key> = va_arg(param, long); break; /* options formerly used for pipelining */ case <API key>: break; case <API key>: break; case <API key>: break; case <API key>: break; case <API key>: break; default: res = <API key>; break; } va_end(param); return res; } /* we define curl_multi_socket() in the public multi.h header */ #undef curl_multi_socket CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s, int *running_handles) { CURLMcode result; if(multi->in_callback) return <API key>; result = multi_socket(multi, FALSE, s, 0, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } CURLMcode <API key>(struct Curl_multi *multi, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result; if(multi->in_callback) return <API key>; result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } CURLMcode <API key>(struct Curl_multi *multi, int *running_handles) { CURLMcode result; if(multi->in_callback) return <API key>; result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms) { static struct curltime tv_zero = {0, 0}; if(multi->timetree) { /* we have a tree of expire times */ struct curltime now = Curl_now(); /* splay the lowest to the bottom */ multi->timetree = Curl_splay(tv_zero, multi->timetree); if(<API key>(multi->timetree->key, now) > 0) { /* some time left before expiration */ timediff_t diff = Curl_timediff(multi->timetree->key, now); if(diff <= 0) /* * Since we only provide millisecond resolution on the returned value * and the diff might be less than one millisecond here, we don't * return zero as that may cause short bursts of busyloops on fast * processors while the diff is still present but less than one * millisecond! instead we return 1 until the time is ripe. */ *timeout_ms = 1; else /* this should be safe even on 64 bit archs, as we don't use that overly long timeouts */ *timeout_ms = (long)diff; } else /* 0 means immediately */ *timeout_ms = 0; } else *timeout_ms = -1; return CURLM_OK; } CURLMcode curl_multi_timeout(struct Curl_multi *multi, long *timeout_ms) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return <API key>; return multi_timeout(multi, timeout_ms); } /* * Tell the application it should update its timers, if it subscribes to the * update timer callback. */ void Curl_update_timer(struct Curl_multi *multi) { long timeout_ms; if(!multi->timer_cb) return; if(multi_timeout(multi, &timeout_ms)) { return; } if(timeout_ms < 0) { static const struct curltime none = {0, 0}; if(<API key>(none, multi->timer_lastcall)) { multi->timer_lastcall = none; /* there's no timeout now but there was one previously, tell the app to disable it */ multi->timer_cb(multi, -1, multi->timer_userp); return; } return; } /* When multi_timeout() is done, multi->timetree points to the node with the * timeout we got the (relative) time-out time for. We can thus easily check * if this is the same (fixed) time as we got in a previous call and then * avoid calling the callback again. */ if(<API key>(multi->timetree->key, multi->timer_lastcall) == 0) return; multi->timer_lastcall = multi->timetree->key; multi->timer_cb(multi, timeout_ms, multi->timer_userp); } /* * multi_deltimeout() * * Remove a given timestamp from the list of timeouts. */ static void multi_deltimeout(struct Curl_easy *data, expire_id eid) { struct curl_llist_element *e; struct curl_llist *timeoutlist = &data->state.timeoutlist; /* find and remove the specific node from the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *n = (struct time_node *)e->ptr; if(n->eid == eid) { Curl_llist_remove(timeoutlist, e, NULL); return; } } } /* * multi_addtimeout() * * Add a timestamp to the list of timeouts. Keep the list sorted so that head * of list is always the timeout nearest in time. * */ static CURLMcode multi_addtimeout(struct Curl_easy *data, struct curltime *stamp, expire_id eid) { struct curl_llist_element *e; struct time_node *node; struct curl_llist_element *prev = NULL; size_t n; struct curl_llist *timeoutlist = &data->state.timeoutlist; node = &data->state.expires[eid]; /* copy the timestamp and id */ memcpy(&node->time, stamp, sizeof(*stamp)); node->eid = eid; /* also marks it as in use */ n = Curl_llist_count(timeoutlist); if(n) { /* find the correct spot in the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *check = (struct time_node *)e->ptr; timediff_t diff = Curl_timediff(check->time, node->time); if(diff > 0) break; prev = e; } } /* else this is the first timeout on the list */ <API key>(timeoutlist, prev, node, &node->list); return CURLM_OK; } /* * Curl_expire() * * given a number of milliseconds from now to use to set the 'act before * this'-time for the transfer, to be extracted by curl_multi_timeout() * * The timeout will be added to a queue of timeouts if it defines a moment in * time that is later than the current head of queue. * * Expire replaces a former timeout using the same id if already set. */ void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; struct curltime set; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; DEBUGASSERT(id < EXPIRE_LAST); set = Curl_now(); set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */ set.tv_usec += (unsigned int)(milli%1000)*1000; if(set.tv_usec >= 1000000) { set.tv_sec++; set.tv_usec -= 1000000; } /* Remove any timer with the same id just in case. */ multi_deltimeout(data, id); /* Add it to the timer list. It must stay in the list until it has expired in case we need to recompute the minimum timer later. */ multi_addtimeout(data, &set, id); if(nowp->tv_sec || nowp->tv_usec) { /* This means that the struct is added as a node in the splay tree. Compare if the new time is earlier, and only remove-old/add-new if it is. */ timediff_t diff = Curl_timediff(set, *nowp); int rc; if(diff > 0) { /* The current splay tree entry is sooner than this new expiry time. We don't need to update our splay tree entry. */ return; } /* Since this is an updated time, we must remove the previous entry from the splay tree first and then re-add the new value */ rc = <API key>(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error removing splay node = %d\n", rc); } /* Indicate that we are in the splay tree and insert the new timer expiry value since it is our local minimum. */ *nowp = set; data->state.timenode.payload = data; multi->timetree = Curl_splayinsert(*nowp, multi->timetree, &data->state.timenode); } /* * Curl_expire_done() * * Removes the expire timer. Marks it as done. * */ void Curl_expire_done(struct Curl_easy *data, expire_id id) { /* remove the timer, if there */ multi_deltimeout(data, id); } /* * Curl_expire_clear() * * Clear ALL timeout values for this handle. */ void Curl_expire_clear(struct Curl_easy *data) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; if(nowp->tv_sec || nowp->tv_usec) { /* Since this is an cleared time, we must remove the previous entry from the splay tree */ struct curl_llist *list = &data->state.timeoutlist; int rc; rc = <API key>(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error clearing splay node = %d\n", rc); /* flush the timeout list too */ while(list->size > 0) { Curl_llist_remove(list, list->tail, NULL); } #ifdef DEBUGBUILD infof(data, "Expire cleared (transfer %p)\n", data); #endif nowp->tv_sec = 0; nowp->tv_usec = 0; } } CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s, void *hashp) { struct Curl_sh_entry *there = NULL; if(multi->in_callback) return <API key>; there = sh_getentry(&multi->sockhash, s); if(!there) return CURLM_BAD_SOCKET; there->socketp = hashp; return CURLM_OK; } size_t <API key>(struct Curl_multi *multi) { return multi ? multi-><API key> : 0; } size_t <API key>(struct Curl_multi *multi) { return multi ? multi-><API key> : 0; } /* * When information about a connection has appeared, call this! */ void Curl_multiuse_state(struct connectdata *conn, int bundlestate) /* use BUNDLE_* defines */ { DEBUGASSERT(conn); DEBUGASSERT(conn->bundle); DEBUGASSERT(conn->data); DEBUGASSERT(conn->data->multi); conn->bundle->multiuse = bundlestate; <API key>(conn->data->multi); } static void <API key>(struct Curl_multi *multi) { struct curl_llist_element *e = multi->pending.head; if(e) { struct Curl_easy *data = e->ptr; DEBUGASSERT(data->mstate == <API key>); multistate(data, CURLM_STATE_CONNECT); /* Remove this node from the list */ Curl_llist_remove(&multi->pending, e, NULL); /* Make sure that the handle will be processed soonish. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* mark this as having been in the pending queue */ data->state.previouslypending = TRUE; } } void <API key>(struct Curl_easy *data, bool value) { /* might get called when there is no data pointer! */ if(data) { if(data->multi_easy) data->multi_easy->in_callback = value; else if(data->multi) data->multi->in_callback = value; } } bool Curl_is_in_callback(struct Curl_easy *easy) { return ((easy->multi && easy->multi->in_callback) || (easy->multi_easy && easy->multi_easy->in_callback)); } #ifdef DEBUGBUILD void Curl_multi_dump(struct Curl_multi *multi) { struct Curl_easy *data; int i; fprintf(stderr, "* Multi status: %d handles, %d alive\n", multi->num_easy, multi->num_alive); for(data = multi->easyp; data; data = data->next) { if(data->mstate < <API key>) { /* only display handles that are not completed */ fprintf(stderr, "handle %p, state %s, %d sockets\n", (void *)data, statename[data->mstate], data->numsocks); for(i = 0; i < data->numsocks; i++) { curl_socket_t s = data->sockets[i]; struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); fprintf(stderr, "%d ", (int)s); if(!entry) { fprintf(stderr, "INTERNAL CONFUSION\n"); continue; } fprintf(stderr, "[%s %s] ", (entry->action&CURL_POLL_IN)?"RECVING":"", (entry->action&CURL_POLL_OUT)?"SENDING":""); } if(data->numsocks) fprintf(stderr, "\n"); } } } #endif
\file #ifndef __ETL_POOL__ #define __ETL_POOL__ #include "alignment.h" #include "array.h" #include "bitset.h" #include "ipool.h" #include <iterator>
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. //= require jquery //= require jquery_ujs //= require_tree .
#include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcIdentifier.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcMember.h" #include "ifcpp/IFC4/include/IfcMemberTypeEnum.h" #include "ifcpp/IFC4/include/IfcObjectPlacement.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/IfcRelAggregates.h" #include "ifcpp/IFC4/include/IfcRelAssigns.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/IfcRelDefinesByType.h" #include "ifcpp/IFC4/include/IfcRelFillsElement.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/IfcRelNests.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/<API key>.h" #include "ifcpp/IFC4/include/IfcRelSpaceBoundary.h" #include "ifcpp/IFC4/include/IfcRelVoidsElement.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcMember IfcMember::IfcMember( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcMember::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcMember> copy_self( new IfcMember() ); if( m_GlobalId ) { if( options.<API key> ) { copy_self->m_GlobalId = make_shared<IfcGloballyUniqueId>( <API key>().data() ); } else { copy_self->m_GlobalId = <API key><IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.<API key> ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = <API key><IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = <API key><IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = <API key><IfcText>( m_Description->getDeepCopy(options) ); } if( m_ObjectType ) { copy_self->m_ObjectType = <API key><IfcLabel>( m_ObjectType->getDeepCopy(options) ); } if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = <API key><IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); } if( m_Representation ) { copy_self->m_Representation = <API key><<API key>>( m_Representation->getDeepCopy(options) ); } if( m_Tag ) { copy_self->m_Tag = <API key><IfcIdentifier>( m_Tag->getDeepCopy(options) ); } if( m_PredefinedType ) { copy_self->m_PredefinedType = <API key><IfcMemberTypeEnum>( m_PredefinedType->getDeepCopy(options) ); } return copy_self; } void IfcMember::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCMEMBER" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Representation ) { stream << "#" << m_Representation->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcMember::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcMember::toString() const { return L"IfcMember"; } void IfcMember::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcMember, expecting 9, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::<API key>( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::<API key>( args[2], map ); m_Description = IfcText::<API key>( args[3], map ); m_ObjectType = IfcLabel::<API key>( args[4], map ); readEntityReference( args[5], m_ObjectPlacement, map ); readEntityReference( args[6], m_Representation, map ); m_Tag = IfcIdentifier::<API key>( args[7], map ); m_PredefinedType = IfcMemberTypeEnum::<API key>( args[8], map ); } void IfcMember::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcBuildingElement::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) ); } void IfcMember::<API key>( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& <API key> ) const { IfcBuildingElement::<API key>( <API key> ); } void IfcMember::<API key>( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcBuildingElement::<API key>( ptr_self_entity ); } void IfcMember::<API key>() { IfcBuildingElement::<API key>(); }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="<API key>" content="no"> <meta name="viewport" content="width=1000"> <meta name="keywords" content="attrs.ui"> <meta name="author" content="joje.attrs@gmail.com"> <meta name="description" content="Examples"> <title>Style System Basic</title> <script type="text/javascript" src="../ui.debug.js"></script> <script type="text/javascript"> // define style var style = new Appbus.Style({ 'background': 'white', 'color': 'black', 'font-size': 10, '.hierachy': { 'color': 'grey', 'background': 'yellow', 'test': { 'font-size': 9 } } }); console.log('style', style); style.on('*', function(e) { console.log('[' + e.type + '] event occured'); console.log('src', e.src); console.log('values', e.values); console.log('\n\n'); }); // append style.set('..newcls', { 'background': 'lightorange', '.hierachy': { '': { 'color': 'red' } } }); // replace style.set('color', 'grey'); // remove style.remove('font-size'); // merge element style.merge('..cls', { 'display': 'box', 'background-image': 'url("http://localhost/image.png")', 'transition': 'aa', 'p': { 'color': 'blue' } }); // sub style replace style.get('..cls').set('color', 'grey'); // sub style remove style.get('..cls').remove('color'); </script> </head> <body> </body> </html>
/** * Version : 1.0 * User : pcseg306 * Function : Service for Super/client Admin Notification Functions */ gxMainApp.factory("<API key>", function($http,$rootScope,gxAPIServiceWrapper){ var _notificationArray = []; var _resultPromise; var <API key> = function() { _resultPromise = gxAPIServiceWrapper.get("models/superAdmin/<API key>.json"); console.log(_resultPromise); return _resultPromise; } return{ notificationArray: _notificationArray, <API key>: <API key>, resultPromise : _resultPromise }; });
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service from thumbor.loaders import http_loader from tornado.concurrent import return_future from urllib import unquote def _normalize_url(url): url = http_loader.quote_url(unquote(url)) if url.startswith('http:'): url = url.replace('http:', 'https:', 1) return url if url.startswith('https: def validate(context, url): if url.startswith('http: return False return http_loader.validate(context, url, normalize_url_func=_normalize_url) def return_contents(response, url, callback, context): return http_loader.return_contents(response, url, callback, context) @return_future def load(context, url, callback): return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url) def encode(string): return http_loader.encode(string)
<?php class device extends CI_Controller{ public function add_device(){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id'); //later stages will take users key $passcode = rand($key,$key+10000); $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key, 'passcode' => $passcode ); $this->device_model->add_device($data); $this->session->set_userdata('passcode', $passcode); redirect('user/device'); } public function edit_device($id){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id');; //later stages will take users key $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key ); $this->device_model->edit_device($id,$data); redirect('user/device'); } public function delete_device($id){ $this->load->model('device_model'); $this->device_model->delete_device($id); redirect('user/device'); } public function add_parameters($device_id){ $parameters = $this->input->post("parameter_name[]"); $this->load->model('device_model'); foreach ($parameters as $parameter_name) { $data = [ 'parameter_name' => $parameter_name, 'device_id' => $device_id ]; $this->device_model->add_parameter($data); } redirect("user/device"); } public function update_parameter(){ $this->load->model('device_model'); $parameter_names = $this->input->post('parameter_name[]'); $parameter_ids = $this->input->post('parameter_id[]'); $count = 0; foreach ($parameter_names as $parameter_name){ $id = $parameter_ids[$count]; $data = array('parameter_name' => $parameter_name); $this->device_model->edit_parameter($id,$data); $count = $count + 1; } redirect('user/device'); } } ?>
define(function(require) { var test = require('../../../test') var count = 0 require.async('./a', function(a) { test.assert(a.name === 'a', 'load CMD module file') done() }) require.async('./b.js', function() { test.assert(global.SPECS_MODULES_ASYNC === true, 'load normal script file') global.SPECS_MODULES_ASYNC = undefined done() }) require.async(['./c1', './c2'], function(c1, c2) { test.assert(c1.name === 'c1', c1.name) test.assert(c2.name === 'c2', c2.name) done() }) function done() { if (++count === 3) { test.next() } } });
namespace AbpKendoDemo.Migrations { using System; using System.Data.Entity.Migrations; public partial class <API key> : DbMigration { public override void Up() { CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 128), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 256), <API key> = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.<API key>", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 128), EntityTypeName = c.String(maxLength: 256), <API key> = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.<API key>", c => new { Id = c.Guid(nullable: false), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); } public override void Down() { DropIndex("dbo.<API key>", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.<API key>", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.<API key>"); DropTable("dbo.<API key>"); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpBackgroundJobs"); } } }
using System.Web; using System.Web.Optimization; namespace TwitterFeed { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css","~/Content/site.css")); bundles.Add(new ScriptBundle("~/Scripts/js").Include("~/Scripts/jquery-2.1.1.min.js", "~/Scripts/bootstrap.min.js", "~/Scripts/knockout-3.3.0.js", "~/Scripts/sammy-0.7.5.min.js", "~/Scripts/main.js")); } } }
package com.microsoft.azure.management.advisor.v2017_04_19; import com.microsoft.azure.arm.collection.SupportsCreating; import rx.Completable; import rx.Observable; import com.microsoft.azure.management.advisor.v2017_04_19.implementation.SuppressionsInner; import com.microsoft.azure.arm.model.HasInner; /** * Type representing Suppressions. */ public interface Suppressions extends SupportsCreating<SuppressionContract.DefinitionStages.Blank>, HasInner<SuppressionsInner> { /** * Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @throws <API key> thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> listAsync(); /** * Obtains the details of a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws <API key> thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> getAsync(String resourceUri, String recommendationId, String name); /** * Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws <API key> thrown if parameters fail the validation * @return the observable for the request */ Completable deleteAsync(String resourceUri, String recommendationId, String name); }
# NOTICE: THIS FILE IS AUTOGENERATED # MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY # PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/item/<API key>.iff" result.<API key> = -1 result.stfName("obj_n","unknown_object") return result
const fs = require('fs'); const path = require('path'); const cleanCss = require('../../index.js'); module.exports = { name : 'basic test', this : function () { const str = fs.readFileSync(path.resolve('test/styles/basic.dirty.scss'), 'utf8'); const clean = cleanCss({ css : str }); return clean; }, isEqual : function () { return fs.readFileSync(path.resolve('test/styles/basic.clean.scss'), 'utf8'); } };
<script src="/socket.io/socket.io.js"></script> <script src="bower_components/virtualjoystick.js/virtualjoystick.js"></script> <script src="../threex.cloudcontroller.js"></script> <script src="../threex.<API key>.js"></script> <script src="../threex.<API key>.js"></script> <body style='width:100%;margin: 0px; background-color: #bbbbbb; overflow: hidden;'> <!-- <img id='remoteImage' src=''/> --> <script> window.addEventListener('load', function(event){ // CloudController itself // var cloudController = new THREEx.CloudController() cloudController.socket.on('connect', function(){ console.log('connected to server') }) cloudController.socket.on('disconnect', function(){ console.warn('disconnected from server') }) // screenUpdater // var screenUpdater = new THREEx.<API key>(cloudController) document.body.appendChild(screenUpdater.domElement) screenUpdater.sendResolution() setTimeout(function(){ screenUpdater.sendResolution() }, 1000*0.5) // virtualjoystick // var <API key> = new THREEx.<API key>(cloudController) setInterval(function(){ <API key>.sendIfChanged() }, 1000*1/60) }) </script></body>
<a href="/<API key>.html" class="lgi">Learning Programming</a> <a href="/serverless.html" class="lgi">Serverless Architectures</a> <a href="/aws-lambda.html" class="lgi">AWS Lambda</a> <a href="/monitoring.html" class="lgi">Monitoring</a> <a href="/deployment.html" class="lgi">Deployment</a> <a href="/rollbar.html" class="lgi">Rollbar</a> <a href="https://rollbar.com" class="lgi">Rollbar homepage {% include "blog/external-link.html" %}</a> <a href="https://docs.rollbar.com/docs/python/#aws-lambda" class="lgi">Rollbar AWS Lambda docs {% include "blog/external-link.html" %}</a>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Sat May 13 03:02:10 PDT 2017 --> <title>ConsoleUI</title> <meta name="date" content="2017-05-13"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ConsoleUI"; } } catch(err) { } var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-all.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../ui/Environment.html" title="class in ui"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?ui/ConsoleUI.html" target="_top">Frames</a></li> <li><a href="ConsoleUI.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <div class="subTitle">ui</div> <h2 title="Class ConsoleUI" class="title">Class ConsoleUI</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>ui.ConsoleUI</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.util.Observer</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">ConsoleUI</span> extends java.lang.Object implements java.util.Observer</pre> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>0.1 A console logger</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../ui/ConsoleUI.html#ConsoleUI--">ConsoleUI</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method.summary"> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../ui/ConsoleUI.html#update-java.util.Observable-java.lang.Object-">update</a></span>(java.util.Observable&nbsp;o, java.lang.Object&nbsp;arg)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> </a> <h3>Constructor Detail</h3> <a name="ConsoleUI </a> <ul class="blockListLast"> <li class="blockList"> <h4>ConsoleUI</h4> <pre>public&nbsp;ConsoleUI()</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method.detail"> </a> <h3>Method Detail</h3> <a name="update-java.util.Observable-java.lang.Object-"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>update</h4> <pre>public&nbsp;void&nbsp;update(java.util.Observable&nbsp;o, java.lang.Object&nbsp;arg)</pre> <dl> <dt><span class="<API key>">Specified by:</span></dt> <dd><code>update</code>&nbsp;in interface&nbsp;<code>java.util.Observer</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-all.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../ui/Environment.html" title="class in ui"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?ui/ConsoleUI.html" target="_top">Frames</a></li> <li><a href="ConsoleUI.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
{% highlight json %} { "" "C-S-u", "" "C-i", } {% endhighlight %}
#!/usr/bin/env python # 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, # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # in all copies or substantial portions of the Software. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # 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. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test setting the $P4COMSTR variable. """ import os.path import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.subdir('Perforce', ['Perforce', 'sub'], 'sub') sub_Perforce = os.path.join('sub', 'Perforce') sub_SConscript = os.path.join('sub', 'SConscript') sub_all = os.path.join('sub', 'all') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub', 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') test.write('my-p4.py', """ import shutil import sys for f in sys.argv[1:]: shutil.copy('Perforce/'+f, f) """) test.write('SConstruct', """ def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(TOOLS = ['default', 'Perforce'], BUILDERS={'Cat':Builder(action=cat)}, P4COM='%(_python_)s my-p4.py $TARGET', P4COMSTR='Checking out $TARGET from our fake Perforce') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.Perforce()) SConscript('sub/SConscript', "env") """ % locals()) test.write(['Perforce', 'sub', 'SConscript'], """\ Import("env") env.Cat('ddd.out', 'ddd.in') env.Cat('eee.out', 'eee.in') env.Cat('fff.out', 'fff.in') env.Cat('all', ['ddd.out', 'eee.out', 'fff.out']) """) test.write(['Perforce', 'aaa.in'], "Perforce/aaa.in\n") test.write('bbb.in', "checked-out bbb.in\n") test.write(['Perforce', 'ccc.in'], "Perforce/ccc.in\n") test.write(['Perforce', 'sub', 'ddd.in'], "Perforce/sub/ddd.in\n") test.write(['sub', 'eee.in'], "checked-out sub/eee.in\n") test.write(['Perforce', 'sub', 'fff.in'], "Perforce/sub/fff.in\n") test.run(arguments = '.', stdout = test.wrap_stdout(read_str = """\ Checking out %(sub_SConscript)s from our fake Perforce """ % locals(), build_str = """\ Checking out aaa.in from our fake Perforce cat(["aaa.out"], ["aaa.in"]) cat(["bbb.out"], ["bbb.in"]) Checking out ccc.in from our fake Perforce cat(["ccc.out"], ["ccc.in"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) Checking out %(sub_ddd_in)s from our fake Perforce cat(["%(sub_ddd_out)s"], ["%(sub_ddd_in)s"]) cat(["%(sub_eee_out)s"], ["%(sub_eee_in)s"]) Checking out %(sub_fff_in)s from our fake Perforce cat(["%(sub_fff_out)s"], ["%(sub_fff_in)s"]) cat(["%(sub_all)s"], ["%(sub_ddd_out)s", "%(sub_eee_out)s", "%(sub_fff_out)s"]) """ % locals())) test.must_match('all', "Perforce/aaa.in\nchecked-out bbb.in\nPerforce/ccc.in\n") test.must_match(['sub', 'all'], "Perforce/sub/ddd.in\nchecked-out sub/eee.in\nPerforce/sub/fff.in\n") test.pass_test()
\file \brief SocketLayer class implementation This file is part of RakNet Copyright 2003 Kevin Jenkins. Usage of RakNet is subject to the appropriate license agreement. Creative Commons Licensees are subject to the license found at http: Single application licensees are subject to the license found at http: Custom license users are subject to the terms therein. GPL license users are subject to 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. #ifndef __SOCKET_LAYER_H #define __SOCKET_LAYER_H #include "RakMemoryOverride.h" #ifdef _XBOX360 #include "Console1Includes.h" #elif defined(_PS3) #include "Console2Includes.h" typedef int SOCKET; #elif defined(_WIN32) // IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib // winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly #include <winsock2.h> #include <ws2tcpip.h> //#include "RakMemoryOverride.h" #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> //#include "RakMemoryOverride.h" Unix/Linux uses ints for sockets typedef int SOCKET; #endif //#include "ClientContextStruct.h" class RakPeer; // A platform independent implementation of Berkeley sockets, with settings used by RakNet class SocketLayer : public RakNet::RakMemoryOverride { public: Default Constructor SocketLayer(); Destructor ~SocketLayer(); // Get the singleton instance of the Socket Layer. \return unique instance static inline SocketLayer* Instance() { return & I; } // Connect a socket to a remote host. \param[in] writeSocket The local socket. \param[in] binaryAddress The address of the remote host. \param[in] port the remote port. \return A new socket used for communication. SOCKET Connect( SOCKET writeSocket, unsigned int binaryAddress, unsigned short port ); Creates a bound socket to listen for incoming connections on the specified port \param[in] port the port number \param[in] blockingSocket \return A new socket used for accepting clients SOCKET CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress ); Returns if this specified port is in use, for UDP \param[in] port the port number \return If this port is already in use static bool IsPortInUse(unsigned short port); #if !defined(_XBOX360) const char* DomainNameToIP( const char *domainName ); #endif Start an asynchronous read using the specified socket. The callback will use the specified SystemAddress (associated with this socket) and call either the client or the server callback (one or the other should be 0) \note Was used for depreciated IO completion ports. bool <API key>( SOCKET readSocket, unsigned int binaryAddress, unsigned short port, RakPeer* rakPeer ); Write \a data of length \a length to \a writeSocket \param[in] writeSocket The socket to write to \param[in] data The data to write \param[in] length The length of \a data void Write( const SOCKET writeSocket, const char* data, const int length ); Read data from a socket \param[in] s the socket \param[in] rakPeer The instance of rakPeer containing the recvFrom C callback \param[in] errorCode An error code if an error occured . \param[in] <API key> Which of the sockets in RakPeer we are using \return Returns true if you successfully read data, false on error. int RecvFrom( const SOCKET s, RakPeer *rakPeer, int *errorCode, unsigned <API key> ); #if !defined(_XBOX360) Retrieve all local IP address in a string format. \param[in] s The socket whose port we are referring to \param[in] ipList An array of ip address in dotted notation. void GetMyIP( char ipList[ 10 ][ 16 ] ); #endif Call sendto (UDP obviously) \param[in] s the socket \param[in] data The byte buffer to send \param[in] length The length of the \a data in bytes \param[in] ip The address of the remote host in dotted notation. \param[in] port The port number to send to. \return 0 on success, nonzero on failure. int SendTo( SOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port ); Call sendto (UDP obviously) It won't reach the recipient, except on a LAN However, this is good for opening routers / firewalls \param[in] s the socket \param[in] data The byte buffer to send \param[in] length The length of the \a data in bytes \param[in] ip The address of the remote host in dotted notation. \param[in] port The port number to send to. \param[in] ttl Max hops of datagram \return 0 on success, nonzero on failure. int SendToTTL( SOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port, int ttl ); Call sendto (UDP obviously) \param[in] s the socket \param[in] data The byte buffer to send \param[in] length The length of the \a data in bytes \param[in] binaryAddress The address of the remote host in binary format. \param[in] port The port number to send to. \return 0 on success, nonzero on failure. int SendTo( SOCKET s, const char *data, int length, unsigned int binaryAddress, unsigned short port ); Returns the local port, useful when passing 0 as the startup port. \param[in] s The socket whose port we are referring to \return The local port unsigned short GetLocalPort ( SOCKET s ); private: static bool socketLayerStarted; #ifdef _WIN32 static WSADATA winsockInfo; #endif static SocketLayer I; }; #endif
{%= author.name %}
<div class="comment-view mb-6"> {% if not comment_list %} <div class="no-comment"> <p class="text-muted small">{{ _("No comments yet. ") }} <span class="hidden login-required"> <a href="/login?redirect-to={{ pathname }}">{{ _("Login to start a new discussion") }}</a> </span> <span class="hidden start-discussion">{{ _("Start a new discussion") }}</span> </p> </div> {% endif %} {% if not is_communication %} <div class="add-comment-section mb-5"> <div class="<API key>"> <div id="comment-form"> <form class="new-comment"> <fieldset class="new-comment-fields"> <div class="user-details row" style="margin-bottom: 15px; display:none;"> <div class="comment-by col-sm-6 pb-4"> <div class="form-label mb-1">{{ _("Your Name") }}</div> <input class="form-control comment_by" name="comment_by" type="text"> </div> <div class="col-sm-6"> <div class="form-label mb-1">{{ _("Email") }}</div> <input class="form-control comment_email" name="comment_email" type="email"> </div> </div> <div class="comment-text-area"> <div class="form-label mb-1">{{ _("Add a comment") }}</div> <textarea class="form-control" name="comment" rows=5 ></textarea> <div class="text-muted small mt-1 mb-4">{{ _("Ctrl+Enter to add comment") }}</div> </div> <button class="btn btn-sm small" id="submit-comment">{{ _("Comment") }}</button> </fieldset> </form> </div> </div> </div> {% endif %} <hr class="add-comment-hr my-5"> <div itemscope itemtype="http://schema.org/UserComments" id="comment-list"> <div class="add-comment mb-5"> <div class="timeline-dot"></div> <button class="btn btn-sm small add-comment-button">{{ _("Add a comment") }}</button> </div> <div class="comment-list"> {% for comment in comment_list %} {% include "templates/includes/comments/comment.html" %} {% endfor %} </div> </div> </div> <script> frappe.ready(function() { let guest_allowed = parseInt("{{ guest_allowed or 0}}"); let comment_count = "{{ comment_text }}"; let full_name = "" let user_id = ""; let <API key> = function(direction, size) { if (direction == 'top') { $('.blog-container')[0].style.setProperty('--<API key>', size); } else { let <API key> = $('.comment-list .comment-row:last-child').height() - 10; $('.blog-container')[0].style.setProperty('--<API key>', <API key> +'px'); } } let show_comment_box = function() { $('.<API key>').show(); <API key>('top', '-20px'); $('.add-comment-hr').hide(); $('.add-comment').hide(); } let hide_comment_box = function() { $('.<API key>').hide(); <API key>('top', '8px'); <API key>('bottom'); $('.add-comment-hr').show(); $('.add-comment').show(); } let $comment_count = $(` <div class="feedback-item"> <span class="comment-icon">${frappe.utils.icon('small-message', 'md')}</span> <span class="comment-count"></span> </div> `); $('form').keydown(function(event) { if (event.ctrlKey && event.keyCode === 13) { $(this).find('#submit-comment').trigger('click'); } }) if (!frappe.is_user_logged_in()) { $(".user-details").toggle('hide'); if (guest_allowed) { $('.start-discussion').removeClass('hidden'); } else { $(".login-required, .<API key>").toggleClass("hidden"); $('.add-comment-button').text('{{ _("Login to comment") }}'); $('.add-comment-button').click(() => { window.location.href = '/login?redirect-to={{ pathname }}'; }); } } else { $('input.comment_by').prop("disabled", true); $('input.comment_email').prop("disabled", true); full_name = frappe.get_cookie("full_name"); user_id = frappe.get_cookie("user_id"); if(user_id != "Guest") { $("[name='comment_email']").val(user_id); $("[name='comment_by']").val(full_name); } $('.start-discussion').removeClass('hidden'); } $('.blog-feedback').append($comment_count); $('.comment-count').text(comment_count); $("#comment-form textarea").val(""); <API key>('bottom'); let n_comments = $(".comment-row").length; n_comments ? $(".no_comment").toggle(false) : show_comment_box(); if(n_comments > 50) { $(".add-comment").toggle(false) .parent().append("<div class='text-muted'>Comments are closed.</div>") } $('.add-comment-button').click(() => { show_comment_box(); }); $("#submit-comment").click(function() { var args = { comment_by: $("[name='comment_by']").val(), comment_email: $("[name='comment_email']").val(), comment: $("[name='comment']").val(), reference_doctype: "{{ reference_doctype or doctype }}", reference_name: "{{ reference_name or name }}", comment_type: "Comment", route: "{{ pathname }}", } if(!args.comment_by || !args.comment_email || !args.comment) { frappe.msgprint('{{ _("All fields are necessary to submit the comment.") }}'); return false; } if (args.comment_email!=='Administrator' && !validate_email(args.comment_email)) { frappe.msgprint('{{ _("Please enter a valid email address.") }}'); return false; } if(!args.comment || !args.comment.trim()) { frappe.msgprint('{{ _("Please add a valid comment.") }}'); return false; } frappe.call({ btn: this, type: "POST", method: "frappe.templates.includes.comments.comments.add_comment", args: args, callback: function(r) { if(r.exc) { if(r._server_messages) frappe.msgprint(r._server_messages); } else { if (r.message) { $(r.message).prependTo(".comment-list"); comment_count = cint(comment_count) + 1; $('.comment-count').text(comment_count); } $(".no-comment").toggle(false); $("#comment-form textarea").val(""); hide_comment_box(); } } }) return false; }); }); </script>
// <API key>.h // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. #import <CoreData/CoreData.h> @import UIKit; @interface <API key> : <API key><<API key>, <API key>, UISearchBarDelegate> { <API key> *<API key>; } @property (nonatomic, strong) <API key> *<API key>; @property (nonatomic, strong) <API key> *searchController; @property (nonatomic, strong) NSString *searchString; @property (nonatomic, assign) BOOL massUpdate; @property (nonatomic, assign) BOOL enableSectionIndex; -(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; -(void)<API key>:(NSString *)placeholder; // -(void)removeSearchBar; -(void)resetMassUpdate; -(void)refreshVisibleCells; -(UITableView *)currentTableView; @end
// Use of this source code is governed by a MIT-style package gitutil import ( "html/template" "testing" dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" "github.com/gogs/git-module" ) func Test_diffsToHTML(t *testing.T) { tests := []struct { diffs []dmp.Diff lineType git.DiffLineType expHTML template.HTML }{ { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffInsert, Text: "bar"}, {Type: dmp.DiffDelete, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineAdd, expHTML: template.HTML(`+foo <span class="added-code">bar</span> biz`), }, { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffDelete, Text: "bar"}, {Type: dmp.DiffInsert, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineDelete, expHTML: template.HTML(`-foo <span class="removed-code">bar</span> biz`), }, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expHTML, diffsToHTML(test.diffs, test.lineType)) }) } }
#!/bin/sh set -e echo "mkdir -p ${<API key>}/${<API key>}" mkdir -p "${<API key>}/${<API key>}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${<API key>}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps <API key> "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" <API key> "${destination}/${lib}" done fi } # Signs a framework with the provided identity <API key>() { if [ -n "${<API key>}" -a "${<API key>}" != "NO" -a "${<API key>}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${<API key>}" local code_sign_cmd="/usr/bin/codesign --force --sign ${<API key>} ${<API key>} --preserve-metadata=identifier,entitlements '$1'" if [ "${<API key>}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/ReactiveObjC/ReactiveObjC.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/ReactiveObjC/ReactiveObjC.framework" fi if [ "${<API key>}" == "true" ]; then wait fi
<?php include 'Vehicle.php'; include 'Car.php'; $car = new Car(4, 'Red', 'Audi', 'A4', 2016); print_r($car); echo "<br>"; $car->setColor('Green'); print_r($car);
<script type="text/javascript"> var _d = DialogManager.get('config_dialog'); _d.setWidth(350); _d.setPosition('center'); $("select[ectype='bgcolor_selector']").change(function(){ $("input[ectype='bgcolor']").val(this.value); }); $("select[name='img_recom_id']").change(function(){ switchRecommend(this.value, 'img_cate_id'); }); $("select[name='txt_recom_id']").change(function(){ switchRecommend(this.value, 'txt_cate_id'); }); switchRecommend($("select[name='img_recom_id']").val(), 'img_cate_id'); switchRecommend($("select[name='txt_recom_id']").val(), 'txt_cate_id'); function switchRecommend(recomId, selectName) { if (recomId >= 0) { $("select[name='" + selectName + "']").hide(); } else { $("select[name='" + selectName + "']").show(); } } </script> <div class="field_item"> <label>:</label> <p><input type="text" name="module_name" value="{$options.module_name}" /></p> </div> <div class="field_item"> <label>:(<span>#332211</span>)</label> <p><input type="text" name="bgcolor" ectype="bgcolor" value="{$options.bgcolor}" /> <select ectype="bgcolor_selector" style="width:100px"> <option value="">...</option> <option value="#bbc5d6" style="background:#bbc5d6"></option> <option value="#a7d8c8" style="background:#a7d8c8"></option> <option value="#a3c9ee" style="background:#a3c9ee"></option> <option value="#9fd9dd" style="background:#9fd9dd"></option> <option value="#b9afd4" style="background:#b9afd4"></option> <option value="#dcad7f" style="background:#dcad7f"></option> <option value="#c4d568" style="background:#c4d568"></option> <option value="#dcc972" style="background:#dcc972"></option> <option value="#e8b5e5" style="background:#e8b5e5"></option> <option value="#ecb8bc" style="background:#ecb8bc"></option> </select></p> </div> <div class="field_item"> <label>:(<span></span>)</label> <p><input type="text" name="keyword_list" value="{$options.keyword_list}" /></p> </div> <div class="field_item"> <label>:(<span>210*280 gif|jpg|jpeg|png </span>)</label> <p><input type="file" name="ad_image_file" /><input type="hidden" name="ad_image_url" value="{$options.ad_image_url}" /></p> <!-- {if $options.ad_image_url} --><p><img src="{$options.ad_image_url}" height="20" /></p><!-- {/if} --> </div> <div class="field_item"> <label>:</label> <p><input type="text" name="ad_link_url" value="{$options.ad_link_url}" /></p> </div> <div class="field_item"> <label>:</label> <p><select name="img_recom_id"> <option value="0">...</option> <!-- {foreach from=$recommends key=recom_id item=recom_name} --> <option value="{$recom_id}"{if $options.img_recom_id eq $recom_id} selected="selected"{/if}>{$recom_name|escape}</option> <!-- {/foreach} --> </select> <select name="img_cate_id"> <option value="0">...</option> <!-- {html_options options=$gcategories selected=$options.img_cate_id} --> </select></p> </div> <div class="field_item"> <label>:</label> <p><select name="txt_recom_id"> <option value="0">...</option> <!-- {foreach from=$recommends key=recom_id item=recom_name} --> <option value="{$recom_id}"{if $options.txt_recom_id eq $recom_id} selected="selected"{/if}>{$recom_name|escape}</option> <!-- {/foreach} --> </select> <select name="txt_cate_id"> <option value="0">...</option> <!-- {html_options options=$gcategories selected=$options.txt_cate_id} --> </select></p> </div>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="sv"> <head> <!-- Generated by javadoc on Fri Mar 18 12:42:22 CET 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IV1201 1.0-SNAPSHOT API</title> <script type="text/javascript"> targetPage = "" + window.location.search; if (targetPage != "" && targetPage != "undefined") targetPage = targetPage.substring(1); if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage))) targetPage = "undefined"; function validURL(url) { try { url = decodeURIComponent(url); } catch (error) { return false; } var pos = url.indexOf(".html"); if (pos == -1 || pos != url.length - 5) return false; var allowNumber = false; var allowSep = false; var seenDot = false; for (var i = 0; i < url.length - 5; i++) { var ch = url.charAt(i); if ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '$' || ch == '_' || ch.charCodeAt(0) > 127) { allowNumber = true; allowSep = true; } else if ('0' <= ch && ch <= '9' || ch == '-') { if (!allowNumber) return false; } else if (ch == '/' || ch == '.') { if (!allowSep) return false; allowNumber = false; allowSep = false; if (ch == '.') seenDot = true; if (ch == '/' && seenDot) return false; } else { return false; } } return true; } function loadFrames() { if (targetPage != "" && targetPage != "undefined") top.classFrame.location = top.targetPage; } </script> </head> <frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()"> <frameset rows="30%,70%" title="Left frames" onload="top.loadFrames()"> <frame src="overview-frame.html" name="packageListFrame" title="All Packages"> <frame src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)"> </frameset> <frame src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes"> <noframes> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <h2>Frame Alert</h2> <p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="overview-summary.html">Non-frame version</a>.</p> </noframes> </frameset> </html>
package com.xeiam.xchange.anx.v2.account.polling; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import org.junit.Assert; import org.junit.Test; import com.fasterxml.jackson.databind.<API key>; import com.fasterxml.jackson.databind.ObjectMapper; import com.xeiam.xchange.anx.v2.dto.account.polling.<API key>; //import static org.fest.assertions.api.Assertions.assertThat; /** * Test ANXWalletHistory JSON parsing */ public class <API key> { @Test public void testUnmarshal() throws IOException { // Read in the JSON from the example resources InputStream is = <API key>.class.getResourceAsStream("/v2/account/<API key>.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); mapper.configure(<API key>.<API key>, false); <API key> <API key> = mapper.readValue(is, <API key>.class); Assert.assertTrue(<API key>.getANXWalletHistory() != null); Assert.assertTrue(<API key>.getANXWalletHistory().getRecords() == 104); Assert.assertTrue(<API key>.getANXWalletHistory().getCurrentPage() == 1); Assert.assertTrue(<API key>.getANXWalletHistory().getMaxPage() == 3); Assert.assertTrue(<API key>.getANXWalletHistory().getMaxResults() == 50); Assert.assertTrue(<API key>.getANXWalletHistory().<API key>().length == 50); Assert.assertEquals("BTC bought: [tid:<API key>] 10.00000000 BTC at 280.65500 HKD", <API key>.getANXWalletHistory().<API key>()[0] .getInfo()); Assert.assertEquals(104, <API key>.getANXWalletHistory().<API key>()[0].getIndex()); Assert.assertEquals("1394594770000", <API key>.getANXWalletHistory().<API key>()[0].getDate()); Assert.assertEquals("fee", <API key>.getANXWalletHistory().<API key>()[0].getType()); Assert.assertEquals("BTC", <API key>.getANXWalletHistory().<API key>()[0].getValue().getCurrency()); // Assert.assertEquals(new BigDecimal(0), // <API key>.getANXWalletHistory().<API key>()[0].getValue().getValue()); Assert.assertEquals(new BigDecimal("103168.75400000"), <API key>.getANXWalletHistory().<API key>()[0].getBalance().getValue()); Assert.assertEquals("<API key>", <API key>.getANXWalletHistory().<API key>()[0].getTrade().getOid()); Assert.assertEquals("<API key>", <API key>.getANXWalletHistory().<API key>()[0].getTrade().getTid()); Assert.assertEquals(new BigDecimal("10.00000000"), <API key>.getANXWalletHistory().<API key>()[0].getTrade().getAmount().getValue()); Assert.assertEquals("market", <API key>.getANXWalletHistory().<API key>()[0].getTrade().getProperties()); } }
#ifdef HAVE_WINRT #define ICustomStreamSink StreamSink #ifndef __cplusplus_winrt #define __is_winrt_array(type) (type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key> ||\ type == ABI::Windows::Foundation::PropertyType::<API key> || type == ABI::Windows::Foundation::PropertyType::<API key>) template<typename _Type, bool bUnknown = std::is_base_of<IUnknown, _Type>::value> struct winrt_type { }; template<typename _Type> struct winrt_type<_Type, true> { static IUnknown* create(_Type* _ObjInCtx) { return reinterpret_cast<IUnknown*>(_ObjInCtx); } static IID getuuid() { return __uuidof(_Type); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::<API key>; }; template <typename _Type> struct winrt_type<_Type, false> { static IUnknown* create(_Type* _ObjInCtx) { Microsoft::WRL::ComPtr<IInspectable> _PObj; Microsoft::WRL::ComPtr<IActivationFactory> objFactory; HRESULT hr = Windows::Foundation::<API key>(Microsoft::WRL::Wrappers::HStringReference(<API key>).Get(), objFactory.<API key>()); if (FAILED(hr)) return nullptr; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::<API key>> spPropVal; if (SUCCEEDED(hr)) hr = objFactory.As(&spPropVal); if (SUCCEEDED(hr)) { hr = winrt_type<_Type>::create(spPropVal.Get(), _ObjInCtx, _PObj.GetAddressOf()); if (SUCCEEDED(hr)) return reinterpret_cast<IUnknown*>(_PObj.Detach()); } return nullptr; } static IID getuuid() { return __uuidof(ABI::Windows::Foundation::IPropertyValue); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::<API key>; }; template<> struct winrt_type<void> { static HRESULT create(ABI::Windows::Foundation::<API key>* spPropVal, void* _ObjInCtx, IInspectable** ppInsp) { (void)_ObjInCtx; return spPropVal->CreateEmpty(ppInsp); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_Empty; }; #define MAKE_TYPE(Type, Name) template<>\ struct winrt_type<Type>\ {\ static HRESULT create(ABI::Windows::Foundation::<API key>* spPropVal, Type* _ObjInCtx, IInspectable** ppInsp) {\ return spPropVal->Create##Name(*_ObjInCtx, ppInsp);\ }\ static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name;\ }; template<typename _Type> struct winrt_array_type { static IUnknown* create(_Type* _ObjInCtx, size_t N) { Microsoft::WRL::ComPtr<IInspectable> _PObj; Microsoft::WRL::ComPtr<IActivationFactory> objFactory; HRESULT hr = Windows::Foundation::<API key>(Microsoft::WRL::Wrappers::HStringReference(<API key>).Get(), objFactory.<API key>()); if (FAILED(hr)) return nullptr; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::<API key>> spPropVal; if (SUCCEEDED(hr)) hr = objFactory.As(&spPropVal); if (SUCCEEDED(hr)) { hr = winrt_array_type<_Type>::create(spPropVal.Get(), N, _ObjInCtx, _PObj.GetAddressOf()); if (SUCCEEDED(hr)) return reinterpret_cast<IUnknown*>(_PObj.Detach()); } return nullptr; } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::<API key>; }; template<int> struct winrt_prop_type {}; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_Empty> { typedef void _Type; }; template <> struct winrt_prop_type<ABI::Windows::Foundation::<API key>> { typedef void _Type; }; template <> struct winrt_prop_type<ABI::Windows::Foundation::<API key>> { typedef void _Type; }; #define MAKE_PROP(Prop, Type) template <>\ struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_##Prop> {\ typedef Type _Type;\ }; #define MAKE_ARRAY_TYPE(Type, Name) MAKE_PROP(Name, Type)\ MAKE_PROP(Name##Array, Type*)\ MAKE_TYPE(Type, Name)\ template<>\ struct winrt_array_type<Type*>\ {\ static HRESULT create(ABI::Windows::Foundation::<API key>* spPropVal, UINT32 __valueSize, Type** _ObjInCtx, IInspectable** ppInsp) {\ return spPropVal->Create##Name##Array(__valueSize, *_ObjInCtx, ppInsp);\ }\ static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name##Array;\ static std::vector<Type> <API key>(ABI::Windows::Foundation::IPropertyValue* propValue)\ {\ UINT32 uLen = 0;\ Type* pArray = nullptr;\ propValue->Get##Name##Array(&uLen, &pArray);\ return std::vector<Type>(pArray, pArray + uLen);\ }\ }; MAKE_ARRAY_TYPE(BYTE, UInt8) MAKE_ARRAY_TYPE(INT16, Int16) MAKE_ARRAY_TYPE(UINT16, UInt16) MAKE_ARRAY_TYPE(INT32, Int32) MAKE_ARRAY_TYPE(UINT32, UInt32) MAKE_ARRAY_TYPE(INT64, Int64) MAKE_ARRAY_TYPE(UINT64, UInt64) MAKE_ARRAY_TYPE(FLOAT, Single) MAKE_ARRAY_TYPE(DOUBLE, Double) MAKE_ARRAY_TYPE(WCHAR, Char16) //MAKE_ARRAY_TYPE(boolean, Boolean) //conflict with identical type in C++ of BYTE/UInt8 MAKE_ARRAY_TYPE(HSTRING, String) MAKE_ARRAY_TYPE(IInspectable*, Inspectable) MAKE_ARRAY_TYPE(GUID, Guid) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::DateTime, DateTime) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::TimeSpan, TimeSpan) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Point, Point) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Size, Size) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Rect, Rect) template < typename T > struct DerefHelper { typedef T DerefType; }; template < typename T > struct DerefHelper<T*> { typedef T DerefType; }; #define <API key>(_Type) (std::is_void<_Type>::value || \ std::is_same<_Type, BYTE>::value || \ std::is_same<_Type, INT16>::value || \ std::is_same<_Type, UINT16>::value || \ std::is_same<_Type, INT32>::value || \ std::is_same<_Type, UINT32>::value || \ std::is_same<_Type, INT64>::value || \ std::is_same<_Type, UINT64>::value || \ std::is_same<_Type, FLOAT>::value || \ std::is_same<_Type, DOUBLE>::value || \ std::is_same<_Type, WCHAR>::value || \ std::is_same<_Type, boolean>::value || \ std::is_same<_Type, HSTRING>::value || \ std::is_same<_Type, IInspectable *>::value || \ std::is_base_of<Microsoft::WRL::Details::RuntimeClassBase, _Type>::value || \ std::is_base_of<IInspectable, typename DerefHelper<_Type>::DerefType>::value || \ std::is_same<_Type, GUID>::value || \ std::is_same<_Type, ABI::Windows::Foundation::DateTime>::value || \ std::is_same<_Type, ABI::Windows::Foundation::TimeSpan>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Point>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Size>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Rect>::value || \ std::is_same<_Type, BYTE*>::value || \ std::is_same<_Type, INT16*>::value || \ std::is_same<_Type, UINT16*>::value || \ std::is_same<_Type, INT32*>::value || \ std::is_same<_Type, UINT32*>::value || \ std::is_same<_Type, INT64*>::value || \ std::is_same<_Type, UINT64*>::value || \ std::is_same<_Type, FLOAT*>::value || \ std::is_same<_Type, DOUBLE*>::value || \ std::is_same<_Type, WCHAR*>::value || \ std::is_same<_Type, boolean*>::value || \ std::is_same<_Type, HSTRING*>::value || \ std::is_same<_Type, IInspectable **>::value || \ std::is_same<_Type, GUID*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::DateTime*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::TimeSpan*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Point*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Size*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Rect*>::value) #endif #else EXTERN_C const IID <API key>; class DECLSPEC_UUID("<API key>") DECLSPEC_NOVTABLE ICustomStreamSink : public IUnknown { public: virtual HRESULT Initialize() = 0; virtual HRESULT Shutdown() = 0; virtual HRESULT Start(MFTIME start) = 0; virtual HRESULT Pause() = 0; virtual HRESULT Restart() = 0; virtual HRESULT Stop() = 0; }; #endif #define <API key> L"<API key>" #define MF_PROP_VIDTYPE L"vidtype" #define MF_PROP_VIDENCPROPS L"videncprops" #include <initguid.h> // <API key>: {<API key>} // Type: IUnknown* DEFINE_GUID(<API key>, 0x26957aa7, 0xaff4, 0x464c, 0xbb, 0x8b, 0x7, 0xba, 0x65, 0xce, 0x11, 0xdf); // {<API key>} DEFINE_GUID(MF_STREAMSINK_ID, 0x4bd133cc, 0xeb9b, 0x496e, 0x88, 0x65, 0x8, 0x13, 0xbf, 0xbc, 0x6f, 0xaa); // {<API key>} DEFINE_GUID(<API key>, 0xc9e22a8c, 0x6a50, 0x4d78, 0x91, 0x83, 0x8, 0x34, 0xa0, 0x2a, 0x37, 0x80); // {<API key>} DEFINE_GUID(<API key>, 0xdabd13ab, 0x26b7, 0x47c2, 0x97, 0xc1, 0x4b, 0x4, 0xc1, 0x87, 0xb8, 0x38); #include <utility> #ifdef _UNICODE #define MAKE_MAP(e) std::map<e, std::wstring> #define MAKE_ENUM(e) std::pair<e, std::wstring> #define MAKE_ENUM_PAIR(e, str) std::pair<e, std::wstring>(str, L#str) #else #define MAKE_MAP(e) std::map<e, std::string> #define MAKE_ENUM(e) std::pair<e, std::string> #define MAKE_ENUM_PAIR(e, str) std::pair<e, std::string>(str, #str) #endif MAKE_ENUM(MediaEventType) MediaEventTypePairs[] = { MAKE_ENUM_PAIR(MediaEventType, MEUnknown), MAKE_ENUM_PAIR(MediaEventType, MEError), MAKE_ENUM_PAIR(MediaEventType, MEExtendedType), MAKE_ENUM_PAIR(MediaEventType, MENonFatalError), MAKE_ENUM_PAIR(MediaEventType, MEGenericV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESessionUnknown), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MESessionStarted), MAKE_ENUM_PAIR(MediaEventType, MESessionPaused), MAKE_ENUM_PAIR(MediaEventType, MESessionStopped), MAKE_ENUM_PAIR(MediaEventType, MESessionClosed), MAKE_ENUM_PAIR(MediaEventType, MESessionEnded), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MENewPresentation), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MEEnablerProgress), MAKE_ENUM_PAIR(MediaEventType, MEEnablerCompleted), MAKE_ENUM_PAIR(MediaEventType, MEPolicyError), MAKE_ENUM_PAIR(MediaEventType, MEPolicyReport), MAKE_ENUM_PAIR(MediaEventType, MEBufferingStarted), MAKE_ENUM_PAIR(MediaEventType, MEBufferingStopped), MAKE_ENUM_PAIR(MediaEventType, MEConnectStart), MAKE_ENUM_PAIR(MediaEventType, MEConnectEnd), MAKE_ENUM_PAIR(MediaEventType, MEReconnectStart), MAKE_ENUM_PAIR(MediaEventType, MEReconnectEnd), MAKE_ENUM_PAIR(MediaEventType, MERendererEvent), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MESessionV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESourceUnknown), MAKE_ENUM_PAIR(MediaEventType, MESourceStarted), MAKE_ENUM_PAIR(MediaEventType, MEStreamStarted), MAKE_ENUM_PAIR(MediaEventType, MESourceSeeked), MAKE_ENUM_PAIR(MediaEventType, MEStreamSeeked), MAKE_ENUM_PAIR(MediaEventType, MENewStream), MAKE_ENUM_PAIR(MediaEventType, MEUpdatedStream), MAKE_ENUM_PAIR(MediaEventType, MESourceStopped), MAKE_ENUM_PAIR(MediaEventType, MEStreamStopped), MAKE_ENUM_PAIR(MediaEventType, MESourcePaused), MAKE_ENUM_PAIR(MediaEventType, MEStreamPaused), MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentation), MAKE_ENUM_PAIR(MediaEventType, MEEndOfStream), MAKE_ENUM_PAIR(MediaEventType, MEMediaSample), MAKE_ENUM_PAIR(MediaEventType, MEStreamTick), MAKE_ENUM_PAIR(MediaEventType, MEStreamThinMode), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MESourceRateChanged), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MESourceV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESinkUnknown), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStarted), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStopped), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPaused), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkMarker), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MEQualityNotify), MAKE_ENUM_PAIR(MediaEventType, MESinkInvalidated), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MESinkV1Anchor), #if (WINVER >= 0x0602) // Available since Win 8 MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MESinkV2Anchor), #endif MAKE_ENUM_PAIR(MediaEventType, METrustUnknown), MAKE_ENUM_PAIR(MediaEventType, MEPolicyChanged), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MEPolicySet), MAKE_ENUM_PAIR(MediaEventType, METrustV1Anchor), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMV1Anchor), MAKE_ENUM_PAIR(MediaEventType, METransformUnknown), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, METransformMarker), #if (WINVER >= 0x0602) // Available since Win 8 MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), MAKE_ENUM_PAIR(MediaEventType, <API key>), #endif MAKE_ENUM_PAIR(MediaEventType, MEReservedMax) }; MAKE_MAP(MediaEventType) MediaEventTypeMap(MediaEventTypePairs, MediaEventTypePairs + sizeof(MediaEventTypePairs) / sizeof(MediaEventTypePairs[0])); MAKE_ENUM(<API key>) <API key>[] = { MAKE_ENUM_PAIR(<API key>, <API key>), MAKE_ENUM_PAIR(<API key>, <API key>), MAKE_ENUM_PAIR(<API key>, <API key>), MAKE_ENUM_PAIR(<API key>, <API key>) }; MAKE_MAP(<API key>) <API key>(<API key>, <API key> + sizeof(<API key>) / sizeof(<API key>[0])); #ifdef HAVE_WINRT #ifdef __cplusplus_winrt #define _ContextCallback Concurrency::details::_ContextCallback #define <API key>(hr, var, ...) hr = S_OK;\ var._CallInContext([__VA_ARGS__]() { #define END_CALL_IN_CONTEXT(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\ }); #define <API key> }); #else #define _ContextCallback Concurrency_winrt::details::_ContextCallback #define <API key>(hr, var, ...) hr = var._CallInContext([__VA_ARGS__]() -> HRESULT { #define END_CALL_IN_CONTEXT(hr) return hr;\ }); #define <API key> return S_OK;\ }); #endif #define GET_CURRENT_CONTEXT _ContextCallback::_CaptureCurrent() #define <API key>(var) _ContextCallback var = GET_CURRENT_CONTEXT #define COMMA , #ifdef __cplusplus_winrt #define _Object Platform::Object^ #define _ObjectObj Platform::Object^ #define _String Platform::String^ #define _StringObj Platform::String^ #define _StringReference ref new Platform::String #define _StringReferenceObj Platform::String^ #define <API key> Windows::Devices::Enumeration::<API key> #define _MediaCapture Windows::Media::Capture::MediaCapture #define <API key> Windows::Media::Capture::MediaCapture #define <API key> Windows::Media::Capture::<API key> #define <API key> Windows::Media::Devices::<API key> #define <API key> Windows::Media::Devices::<API key> #define <API key> Windows::Media::MediaProperties::<API key> #define <API key> Windows::Media::MediaProperties::<API key> #define _MediaStreamType Windows::Media::Capture::MediaStreamType #define _AsyncInfo Windows::Foundation::IAsyncInfo #define _AsyncAction Windows::Foundation::IAsyncAction #define _AsyncOperation Windows::Foundation::IAsyncOperation #define _DeviceClass Windows::Devices::Enumeration::DeviceClass #define _IDeviceInformation Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformation Windows::Devices::Enumeration::DeviceInformation #define <API key> Windows::Devices::Enumeration::DeviceInformation #define <API key> Windows::Media::MediaProperties::<API key> #define <API key> Windows::Media::Capture::<API key> #define _PropertySet Windows::Foundation::Collections::PropertySet #define _Map Windows::Foundation::Collections::PropertySet #define <API key> Windows::Foundation::PropertyValue #define _VectorView Windows::Foundation::Collections::IVectorView #define <API key> <API key> #define <API key> InitializeAsync #define <API key> FindAllAsync #define _MediaExtension Windows::Media::IMediaExtension #define BEGIN_CREATE_ASYNC(type, ...) (Concurrency::create_async([__VA_ARGS__]() { #define END_CREATE_ASYNC(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\ })) #define DEFINE_TASK Concurrency::task #define CREATE_TASK Concurrency::create_task #define <API key>(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); }); #define <API key>(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); }); #define DEFINE_RET_VAL(x) #define DEFINE_RET_TYPE(x) #define DEFINE_RET_FORMAL(x) x #define RET_VAL(x) return x; #define RET_VAL_BASE #define MAKE_STRING(str) str #define GET_STL_STRING(str) std::wstring(str->Data()) #define GET_STL_STRING_RAW(str) std::wstring(str->Data()) #define MAKE_WRL_OBJ(x) x^ #define MAKE_WRL_REF(x) x^ #define MAKE_OBJ_REF(x) x^ #define MAKE_WRL_AGILE_REF(x) Platform::Agile<x^> #define MAKE_WRL_AGILE_OBJ(x) Platform::Agile<x^> #define <API key>(Type, PropName) property Type PropName; #define MAKE_PROPERTY(Type, PropName, PropValue) #define <API key>(Type, PropName, PropValue) #define <API key>(Type, PropName, PropValue) property Type PropName\ {\ Type get() { return PropValue; }\ } #define THROW_INVALID_ARG throw ref new Platform::<API key>(); #define RELEASE_AGILE_WRL(x) x = nullptr; #define RELEASE_WRL(x) x = nullptr; #define <API key>(objtype, obj, orig, hr) objtype^ obj = orig;\ hr = S_OK; #define <API key>(objtype, obj, orig, hr) objtype^ obj = safe_cast<objtype^>(orig);\ hr = S_OK; #define WRL_ENUM_GET(obj, prefix, prop) obj::##prop #define WRL_PROP_GET(obj, prop, arg, hr) arg = obj->##prop;\ hr = S_OK; #define WRL_PROP_PUT(obj, prop, arg, hr) obj->##prop = arg;\ hr = S_OK; #define WRL_METHOD_BASE(obj, method, ret, hr) ret = obj->##method();\ hr = S_OK; #define WRL_METHOD(obj, method, ret, hr, ...) ret = obj->##method(__VA_ARGS__);\ hr = S_OK; #define <API key>(obj, method, hr) obj->##method();\ hr = S_OK; #define WRL_METHOD_NORET(obj, method, hr, ...) obj->##method(__VA_ARGS__);\ hr = S_OK; #define REF_WRL_OBJ(obj) &obj #define DEREF_WRL_OBJ(obj) obj #define <API key>(obj) obj.Get() #define DEREF_AGILE_WRL_OBJ(obj) obj.Get() #define <API key>(type, obj) reinterpret_cast<type*>(obj) #define <API key>(obj) obj #define <API key>(objtype) ref new objtype() #define ACTIVATE_LOCAL_OBJ(objtype, ...) ref new objtype(__VA_ARGS__) #define <API key>(objtype, ...) ref new objtype(__VA_ARGS__) #define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj = ref new objtype();\ hr = S_OK; #define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\ hr = S_OK; #else #define _Object IInspectable* #define _ObjectObj Microsoft::WRL::ComPtr<IInspectable> #define _String HSTRING #define _StringObj Microsoft::WRL::Wrappers::HString #define _StringReference Microsoft::WRL::Wrappers::HStringReference #define _StringReferenceObj Microsoft::WRL::Wrappers::HStringReference #define <API key> ABI::Windows::Devices::Enumeration::<API key> #define _MediaCapture ABI::Windows::Media::Capture::IMediaCapture #define <API key> ABI::Windows::Media::Capture::<API key> #define <API key> ABI::Windows::Media::Capture::<API key> #define <API key> ABI::Windows::Media::Devices::<API key> #define <API key> ABI::Windows::Media::Devices::<API key> #define <API key> ABI::Windows::Media::MediaProperties::<API key> #define <API key> ABI::Windows::Media::MediaProperties::<API key> #define _MediaStreamType ABI::Windows::Media::Capture::MediaStreamType #define _AsyncInfo ABI::Windows::Foundation::IAsyncInfo #define _AsyncAction ABI::Windows::Foundation::IAsyncAction #define _AsyncOperation ABI::Windows::Foundation::IAsyncOperation #define _DeviceClass ABI::Windows::Devices::Enumeration::DeviceClass #define _IDeviceInformation ABI::Windows::Devices::Enumeration::IDeviceInformation #define _DeviceInformation ABI::Windows::Devices::Enumeration::DeviceInformation #define <API key> ABI::Windows::Devices::Enumeration::<API key> #define <API key> ABI::Windows::Media::MediaProperties::<API key> #define <API key> ABI::Windows::Media::Capture::<API key> #define _PropertySet ABI::Windows::Foundation::Collections::IPropertySet #define _Map ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *> #define <API key> ABI::Windows::Foundation::<API key> #define _VectorView ABI::Windows::Foundation::Collections::IVectorView #define <API key> <API key> #define <API key> <API key> #define <API key> <API key> #define _MediaExtension ABI::Windows::Media::IMediaExtension #define BEGIN_CREATE_ASYNC(type, ...) Concurrency_winrt::create_async<type>([__VA_ARGS__]() -> HRESULT { #define END_CREATE_ASYNC(hr) return hr;\ }) #define DEFINE_TASK Concurrency_winrt::task #define CREATE_TASK Concurrency_winrt::create_task #define <API key>(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then(func); #define <API key>(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then([func](rettype, rettype* retVal) -> HRESULT { return func(retVal); }); #define DEFINE_RET_VAL(x) x* retVal #define DEFINE_RET_TYPE(x) <x> #define DEFINE_RET_FORMAL(x) HRESULT #define RET_VAL(x) *retVal = x;\ return S_OK; #define RET_VAL_BASE return S_OK; #define MAKE_STRING(str) Microsoft::WRL::Wrappers::HStringReference(L##str) #define GET_STL_STRING(str) std::wstring(str.GetRawBuffer(NULL)) #define GET_STL_STRING_RAW(str) <API key>(str, NULL) #define MAKE_WRL_OBJ(x) Microsoft::WRL::ComPtr<x> #define MAKE_WRL_REF(x) x* #define MAKE_OBJ_REF(x) x #define MAKE_WRL_AGILE_REF(x) x* #define MAKE_WRL_AGILE_OBJ(x) Microsoft::WRL::ComPtr<x> #define <API key>(Type, PropName) Type PropName; #define MAKE_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }\ STDMETHODIMP put_##PropName(Type Val) { PropValue = Val; return S_OK; } #define <API key>(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { return ::<API key>(PropValue.Get(), pVal); } else { return E_INVALIDARG; } }\ STDMETHODIMP put_##PropName(Type Val) { return PropValue.Set(Val); } #define <API key>(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; } #define THROW_INVALID_ARG RoOriginateError(E_INVALIDARG, nullptr); #define RELEASE_AGILE_WRL(x) if (x) { (x)->Release(); x = nullptr; } #define RELEASE_WRL(x) if (x) { (x)->Release(); x = nullptr; } #define <API key>(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\ hr = orig->QueryInterface(__uuidof(objtype), &obj); #define <API key>(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\ hr = orig.As(&obj); #define WRL_ENUM_GET(obj, prefix, prop) obj::prefix##_##prop #define WRL_PROP_GET(obj, prop, arg, hr) hr = obj->get_##prop(&arg); #define WRL_PROP_PUT(obj, prop, arg, hr) hr = obj->put_##prop(arg); #define WRL_METHOD_BASE(obj, method, ret, hr) hr = obj->##method(&ret); #define WRL_METHOD(obj, method, ret, hr, ...) hr = obj->##method(__VA_ARGS__, &ret); #define <API key>(obj, method, hr) hr = obj->##method(); #define REF_WRL_OBJ(obj) obj.GetAddressOf() #define DEREF_WRL_OBJ(obj) obj.Get() #define <API key>(obj) obj.Get() #define DEREF_AGILE_WRL_OBJ(obj) obj #define <API key>(type, obj) obj.Get() #define <API key>(obj) obj.Detach() #define <API key>(objtype) Microsoft::WRL::Make<objtype>() #define ACTIVATE_LOCAL_OBJ(objtype, ...) Microsoft::WRL::Make<objtype>(__VA_ARGS__) #define <API key>(objtype, ...) Microsoft::WRL::Callback<objtype>(__VA_ARGS__).Get() #define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj;\ {\ Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\ hr = Windows::Foundation::<API key>(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.<API key>());\ if (SUCCEEDED(hr)) {\ Microsoft::WRL::ComPtr<IInspectable> pInsp;\ hr = objFactory->ActivateInstance(pInsp.GetAddressOf());\ if (SUCCEEDED(hr)) hr = pInsp.As(&obj);\ }\ } #define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\ {\ Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\ hr = Windows::Foundation::<API key>(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.<API key>());\ if (SUCCEEDED(hr)) {\ if (SUCCEEDED(hr)) hr = objFactory.As(&obj);\ }\ } #endif #define _ComPtr Microsoft::WRL::ComPtr #else #define <API key>(T,var) T ## Ptr var template <class T> class ComPtr { public: ComPtr() throw() { } ComPtr(T* lp) throw() { p = lp; } ComPtr(_In_ const ComPtr<T>& lp) throw() { p = lp.p; } virtual ~ComPtr() { } T** operator&() throw() { assert(p == NULL); return p.operator&(); } T* operator->() const throw() { assert(p != NULL); return p.operator->(); } bool operator!() const throw() { return p.operator==(NULL); } bool operator==(_In_opt_ T* pT) const throw() { return p.operator==(pT); } bool operator!=(_In_opt_ T* pT) const throw() { return p.operator!=(pT); } operator bool() { return p.operator!=(NULL); } T* const* GetAddressOf() const throw() { return &p; } T** GetAddressOf() throw() { return &p; } T** <API key>() throw() { p.Release(); return &p; } T* Get() const throw() { return p; } // Attach to an existing interface (does not AddRef) void Attach(_In_opt_ T* p2) throw() { p.Attach(p2); } // Detach the interface (does not Release) T* Detach() throw() { return p.Detach(); } _Check_return_ HRESULT CopyTo(_Deref_out_opt_ T** ppT) throw() { assert(ppT != NULL); if (ppT == NULL) return E_POINTER; *ppT = p; if (p != NULL) p->AddRef(); return S_OK; } void Reset() { p.Release(); } // query for U interface template<typename U> HRESULT As(_Inout_ U** lp) const throw() { return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp)); } // query for U interface template<typename U> HRESULT As(_Out_ ComPtr<U>* lp) const throw() { return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp-><API key>())); } private: <API key>(T, __uuidof(T)); <API key>(T, p); }; #define _ComPtr ComPtr #endif template <class TBase=IMFAttributes> class CBaseAttributes : public TBase { protected: // This version of the constructor does not initialize the // attribute store. The derived class must call Initialize() in // its own constructor. CBaseAttributes() { } // This version of the constructor initializes the attribute // store, but the derived class must pass an HRESULT parameter // to the constructor. CBaseAttributes(HRESULT& hr, UINT32 cInitialSize = 0) { hr = Initialize(cInitialSize); } // The next version of the constructor uses a caller-provided // implementation of IMFAttributes. // (Sometimes you want to delegate IMFAttributes calls to some // other object that implements IMFAttributes, rather than using // MFCreateAttributes.) CBaseAttributes(HRESULT& hr, IUnknown *pUnk) { hr = Initialize(pUnk); } virtual ~CBaseAttributes() { } // Initializes the object by creating the standard Media Foundation attribute store. HRESULT Initialize(UINT32 cInitialSize = 0) { if (_spAttributes.Get() == nullptr) { return MFCreateAttributes(&_spAttributes, cInitialSize); } else { return S_OK; } } // Initializes this object from a caller-provided attribute store. // pUnk: Pointer to an object that exposes IMFAttributes. HRESULT Initialize(IUnknown *pUnk) { if (_spAttributes) { _spAttributes.Reset(); _spAttributes = nullptr; } return pUnk->QueryInterface(IID_PPV_ARGS(&_spAttributes)); } public: // IMFAttributes methods STDMETHODIMP GetItem(REFGUID guidKey, PROPVARIANT* pValue) { assert(_spAttributes); return _spAttributes->GetItem(guidKey, pValue); } STDMETHODIMP GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType) { assert(_spAttributes); return _spAttributes->GetItemType(guidKey, pType); } STDMETHODIMP CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult) { assert(_spAttributes); return _spAttributes->CompareItem(guidKey, Value, pbResult); } STDMETHODIMP Compare( IMFAttributes* pTheirs, <API key> MatchType, BOOL* pbResult ) { assert(_spAttributes); return _spAttributes->Compare(pTheirs, MatchType, pbResult); } STDMETHODIMP GetUINT32(REFGUID guidKey, UINT32* punValue) { assert(_spAttributes); return _spAttributes->GetUINT32(guidKey, punValue); } STDMETHODIMP GetUINT64(REFGUID guidKey, UINT64* punValue) { assert(_spAttributes); return _spAttributes->GetUINT64(guidKey, punValue); } STDMETHODIMP GetDouble(REFGUID guidKey, double* pfValue) { assert(_spAttributes); return _spAttributes->GetDouble(guidKey, pfValue); } STDMETHODIMP GetGUID(REFGUID guidKey, GUID* pguidValue) { assert(_spAttributes); return _spAttributes->GetGUID(guidKey, pguidValue); } STDMETHODIMP GetStringLength(REFGUID guidKey, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetStringLength(guidKey, pcchLength); } STDMETHODIMP GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetString(guidKey, pwszValue, cchBufSize, pcchLength); } STDMETHODIMP GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetAllocatedString(guidKey, ppwszValue, pcchLength); } STDMETHODIMP GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize) { assert(_spAttributes); return _spAttributes->GetBlobSize(guidKey, pcbBlobSize); } STDMETHODIMP GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize) { assert(_spAttributes); return _spAttributes->GetBlob(guidKey, pBuf, cbBufSize, pcbBlobSize); } STDMETHODIMP GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize) { assert(_spAttributes); return _spAttributes->GetAllocatedBlob(guidKey, ppBuf, pcbSize); } STDMETHODIMP GetUnknown(REFGUID guidKey, REFIID riid, LPVOID* ppv) { assert(_spAttributes); return _spAttributes->GetUnknown(guidKey, riid, ppv); } STDMETHODIMP SetItem(REFGUID guidKey, REFPROPVARIANT Value) { assert(_spAttributes); return _spAttributes->SetItem(guidKey, Value); } STDMETHODIMP DeleteItem(REFGUID guidKey) { assert(_spAttributes); return _spAttributes->DeleteItem(guidKey); } STDMETHODIMP DeleteAllItems() { assert(_spAttributes); return _spAttributes->DeleteAllItems(); } STDMETHODIMP SetUINT32(REFGUID guidKey, UINT32 unValue) { assert(_spAttributes); return _spAttributes->SetUINT32(guidKey, unValue); } STDMETHODIMP SetUINT64(REFGUID guidKey,UINT64 unValue) { assert(_spAttributes); return _spAttributes->SetUINT64(guidKey, unValue); } STDMETHODIMP SetDouble(REFGUID guidKey, double fValue) { assert(_spAttributes); return _spAttributes->SetDouble(guidKey, fValue); } STDMETHODIMP SetGUID(REFGUID guidKey, REFGUID guidValue) { assert(_spAttributes); return _spAttributes->SetGUID(guidKey, guidValue); } STDMETHODIMP SetString(REFGUID guidKey, LPCWSTR wszValue) { assert(_spAttributes); return _spAttributes->SetString(guidKey, wszValue); } STDMETHODIMP SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize) { assert(_spAttributes); return _spAttributes->SetBlob(guidKey, pBuf, cbBufSize); } STDMETHODIMP SetUnknown(REFGUID guidKey, IUnknown* pUnknown) { assert(_spAttributes); return _spAttributes->SetUnknown(guidKey, pUnknown); } STDMETHODIMP LockStore() { assert(_spAttributes); return _spAttributes->LockStore(); } STDMETHODIMP UnlockStore() { assert(_spAttributes); return _spAttributes->UnlockStore(); } STDMETHODIMP GetCount(UINT32* pcItems) { assert(_spAttributes); return _spAttributes->GetCount(pcItems); } STDMETHODIMP GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue) { assert(_spAttributes); return _spAttributes->GetItemByIndex(unIndex, pguidKey, pValue); } STDMETHODIMP CopyAllItems(IMFAttributes* pDest) { assert(_spAttributes); return _spAttributes->CopyAllItems(pDest); } // Helper functions HRESULT SerializeToStream(DWORD dwOptions, IStream* pStm) // dwOptions: Flags from <API key> { assert(_spAttributes); return <API key>(_spAttributes.Get(), dwOptions, pStm); } HRESULT <API key>(DWORD dwOptions, IStream* pStm) { assert(_spAttributes); return <API key>(_spAttributes.Get(), dwOptions, pStm); } // SerializeToBlob: Stores the attributes in a byte array. // ppBuf: Receives a pointer to the byte array. // pcbSize: Receives the size of the byte array. // The caller must free the array using CoTaskMemFree. HRESULT SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize) { assert(_spAttributes); if (ppBuffer == NULL) { return E_POINTER; } if (pcbSize == NULL) { return E_POINTER; } HRESULT hr = S_OK; UINT32 cbSize = 0; BYTE *pBuffer = NULL; CHECK_HR(hr = <API key>(_spAttributes.Get(), &cbSize)); pBuffer = (BYTE*)CoTaskMemAlloc(cbSize); if (pBuffer == NULL) { CHECK_HR(hr = E_OUTOFMEMORY); } CHECK_HR(hr = <API key>(_spAttributes.Get(), pBuffer, cbSize)); *ppBuffer = pBuffer; *pcbSize = cbSize; done: if (FAILED(hr)) { *ppBuffer = NULL; *pcbSize = 0; CoTaskMemFree(pBuffer); } return hr; } HRESULT DeserializeFromBlob(const UINT8* pBuffer, UINT cbSize) { assert(_spAttributes); return <API key>(_spAttributes.Get(), pBuffer, cbSize); } HRESULT GetRatio(REFGUID guidKey, UINT32* pnNumerator, UINT32* punDenominator) { assert(_spAttributes); return MFGetAttributeRatio(_spAttributes.Get(), guidKey, pnNumerator, punDenominator); } HRESULT SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator) { assert(_spAttributes); return MFSetAttributeRatio(_spAttributes.Get(), guidKey, unNumerator, unDenominator); } // Gets an attribute whose value represents the size of something (eg a video frame). HRESULT GetSize(REFGUID guidKey, UINT32* punWidth, UINT32* punHeight) { assert(_spAttributes); return MFGetAttributeSize(_spAttributes.Get(), guidKey, punWidth, punHeight); } // Sets an attribute whose value represents the size of something (eg a video frame). HRESULT SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight) { assert(_spAttributes); return MFSetAttributeSize (_spAttributes.Get(), guidKey, unWidth, unHeight); } protected: _ComPtr<IMFAttributes> _spAttributes; }; class StreamSink : #ifdef HAVE_WINRT public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::ClassicCom>, IMFStreamSink, <API key>, IMFMediaTypeHandler, CBaseAttributes<> > #else public IMFStreamSink, public IMFMediaTypeHandler, public CBaseAttributes<>, public ICustomStreamSink #endif { public: // IUnknown methods #if defined(_MSC_VER) && _MSC_VER >= 1700 // '<API key>' SAL is avaialable since VS 2012 STDMETHOD(QueryInterface)(REFIID riid, <API key> void **ppv) #else STDMETHOD(QueryInterface)(REFIID riid, void **ppv) #endif { if (ppv == nullptr) { return E_POINTER; } (*ppv) = nullptr; HRESULT hr = S_OK; if (riid == IID_IMarshal) { return MarshalQI(riid, ppv); } else { #ifdef HAVE_WINRT hr = RuntimeClassT::QueryInterface(riid, ppv); #else if (riid == IID_IUnknown || riid == IID_IMFStreamSink) { *ppv = static_cast<IMFStreamSink*>(this); AddRef(); } else if (riid == <API key>) { *ppv = static_cast<<API key>*>(this); AddRef(); } else if (riid == <API key>) { *ppv = static_cast<IMFMediaTypeHandler*>(this); AddRef(); } else if (riid == IID_IMFAttributes) { *ppv = static_cast<IMFAttributes*>(this); AddRef(); } else if (riid == <API key>) { *ppv = static_cast<ICustomStreamSink*>(this); AddRef(); } else hr = E_NOINTERFACE; #endif } return hr; } #ifdef HAVE_WINRT STDMETHOD(<API key>)() { return S_OK; } #else ULONG STDMETHODCALLTYPE AddRef() { return <API key>(&m_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG cRef = <API key>(&m_cRef); if (cRef == 0) { delete this; } return cRef; } #endif HRESULT MarshalQI(REFIID riid, LPVOID* ppv) { HRESULT hr = S_OK; if (m_spFTM == nullptr) { <API key>(&m_critSec); if (m_spFTM == nullptr) { hr = <API key>((IMFStreamSink*)this, &m_spFTM); } <API key>(&m_critSec); } if (SUCCEEDED(hr)) { if (m_spFTM == nullptr) { hr = E_UNEXPECTED; } else { hr = m_spFTM.Get()->QueryInterface(riid, ppv); } } return hr; } enum State { State_TypeNotSet = 0, // No media type is set State_Ready, // Media type is set, Start has never been called. State_Started, State_Stopped, State_Paused, State_Count // Number of states }; StreamSink() : m_IsShutdown(false), m_StartTime(0), <API key>(false), <API key>(false), m_state(State_TypeNotSet), m_pParent(nullptr), <API key>(0), <API key>(0) { #ifdef HAVE_WINRT m_token.value = 0; #else m_bConnected = false; #endif <API key>(&m_critSec, 3000, 0); ZeroMemory(&m_guiCurrentSubtype, sizeof(m_guiCurrentSubtype)); CBaseAttributes::Initialize(0U); DebugPrintOut(L"StreamSink::StreamSink\n"); } virtual ~StreamSink() { <API key>(&m_critSec); assert(m_IsShutdown); DebugPrintOut(L"StreamSink::~StreamSink\n"); } HRESULT Initialize() { HRESULT hr; // Create the event queue helper. hr = MFCreateEventQueue(&m_spEventQueue); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaSink> pMedSink; hr = CBaseAttributes<>::GetUnknown(<API key>, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf()); assert(pMedSink.Get() != NULL); if (SUCCEEDED(hr)) { hr = pMedSink.Get()->QueryInterface(IID_PPV_ARGS(&m_pParent)); } } return hr; } HRESULT CheckShutdown() const { if (m_IsShutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } // Called when the presentation clock starts. HRESULT Start(MFTIME start) { HRESULT hr = S_OK; <API key>(&m_critSec); if (m_state != State_TypeNotSet) { if (start != <API key>) { m_StartTime = start; // Cache the start time. <API key> = false; } else { <API key> = true; } m_state = State_Started; GUID guiMajorType; <API key> = SUCCEEDED(m_spCurrentType->GetMajorType(&guiMajorType)) && (guiMajorType == MFMediaType_Video); hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL); if (SUCCEEDED(hr)) { hr = QueueEvent(<API key>, GUID_NULL, hr, NULL); } } else hr = <API key>; <API key>(&m_critSec); return hr; } // Called when the presentation clock pauses. HRESULT Pause() { <API key>(&m_critSec); HRESULT hr = S_OK; if (m_state != State_Stopped && m_state != State_TypeNotSet) { m_state = State_Paused; hr = QueueEvent(MEStreamSinkPaused, GUID_NULL, hr, NULL); } else if (hr == State_TypeNotSet) hr = <API key>; else hr = MF_E_INVALIDREQUEST; <API key>(&m_critSec); return hr; } // Called when the presentation clock restarts. HRESULT Restart() { <API key>(&m_critSec); HRESULT hr = S_OK; if (m_state == State_Paused) { m_state = State_Started; hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL); if (SUCCEEDED(hr)) { hr = QueueEvent(<API key>, GUID_NULL, hr, NULL); } } else if (hr == State_TypeNotSet) hr = <API key>; else hr = MF_E_INVALIDREQUEST; <API key>(&m_critSec); return hr; } // Called when the presentation clock stops. HRESULT Stop() { <API key>(&m_critSec); HRESULT hr = S_OK; if (m_state != State_TypeNotSet) { m_state = State_Stopped; hr = QueueEvent(MEStreamSinkStopped, GUID_NULL, hr, NULL); } else hr = <API key>; <API key>(&m_critSec); return hr; } // Shuts down the stream sink. HRESULT Shutdown() { _ComPtr<<API key>> pSampleCallback; HRESULT hr = S_OK; assert(!m_IsShutdown); hr = m_pParent->GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) { hr = pSampleCallback->OnShutdown(); } if (m_spEventQueue) { hr = m_spEventQueue->Shutdown(); } if (m_pParent) m_pParent->Release(); m_spCurrentType.Reset(); m_IsShutdown = TRUE; return hr; } //IMFStreamSink HRESULT STDMETHODCALLTYPE GetMediaSink( /* [out] */ <API key> IMFMediaSink **ppMediaSink) { if (ppMediaSink == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaSink> pMedSink; hr = CBaseAttributes<>::GetUnknown(<API key>, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf()); if (SUCCEEDED(hr)) { *ppMediaSink = pMedSink.Detach(); } } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetIdentifier( /* [out] */ __RPC__out DWORD *pdwIdentifier) { if (pdwIdentifier == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = GetUINT32(MF_STREAMSINK_ID, (UINT32*)pdwIdentifier); } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::GetIdentifier: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetMediaTypeHandler( /* [out] */ <API key> IMFMediaTypeHandler **ppHandler) { if (ppHandler == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); // This stream object acts as its own type handler, so we QI ourselves. if (SUCCEEDED(hr)) { hr = QueryInterface(<API key>, (void**)ppHandler); } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeHandler: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE ProcessSample(IMFSample *pSample) { _ComPtr<IMFMediaBuffer> pInput; _ComPtr<<API key>> pSampleCallback; BYTE *pSrc = NULL; // Source buffer. // Stride if the buffer does not support IMF2DBuffer LONGLONG hnsTime = 0; LONGLONG hnsDuration = 0; DWORD cbMaxLength; DWORD cbCurrentLength = 0; GUID guidMajorType; if (pSample == NULL) { return E_INVALIDARG; } HRESULT hr = S_OK; <API key>(&m_critSec); if (m_state != State_Started && m_state != State_Paused) { if (m_state == State_TypeNotSet) hr = <API key>; else hr = MF_E_INVALIDREQUEST; } if (SUCCEEDED(hr)) hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = pSample-><API key>(&pInput); if (SUCCEEDED(hr)) { hr = pSample->GetSampleTime(&hnsTime); } if (SUCCEEDED(hr)) { hr = pSample->GetSampleDuration(&hnsDuration); } if (SUCCEEDED(hr)) { hr = GetMajorType(&guidMajorType); } if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); } if (SUCCEEDED(hr)) { hr = pInput->Lock(&pSrc, &cbMaxLength, &cbCurrentLength); } if (SUCCEEDED(hr)) { hr = pSampleCallback->OnProcessSample(guidMajorType, 0, hnsTime, hnsDuration, pSrc, cbCurrentLength); pInput->Unlock(); } if (SUCCEEDED(hr)) { hr = QueueEvent(<API key>, GUID_NULL, S_OK, NULL); } } <API key>(&m_critSec); return hr; } HRESULT STDMETHODCALLTYPE PlaceMarker( <API key> eMarkerType, __RPC__in const PROPVARIANT * , __RPC__in const PROPVARIANT * ) { eMarkerType; <API key>(&m_critSec); HRESULT hr = S_OK; if (m_state == State_TypeNotSet) hr = <API key>; if (SUCCEEDED(hr)) hr = CheckShutdown(); if (SUCCEEDED(hr)) { //at shutdown will receive <API key> hr = QueueEvent(<API key>, GUID_NULL, S_OK, NULL); } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::PlaceMarker: HRESULT=%i %s\n", hr, <API key>.at(eMarkerType).c_str()); return hr; } HRESULT STDMETHODCALLTYPE Flush(void) { <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::Flush: HRESULT=%i\n", hr); return hr; } //<API key> HRESULT STDMETHODCALLTYPE GetEvent( DWORD dwFlags, IMFMediaEvent **ppEvent) { // NOTE: // GetEvent can block indefinitely, so we don't hold the lock. // This requires some juggling with the event queue pointer. HRESULT hr = S_OK; _ComPtr<IMFMediaEventQueue> pQueue; { <API key>(&m_critSec); // Check shutdown hr = CheckShutdown(); // Get the pointer to the event queue. if (SUCCEEDED(hr)) { pQueue = m_spEventQueue.Get(); } <API key>(&m_critSec); } // Now get the event. if (SUCCEEDED(hr)) { hr = pQueue->GetEvent(dwFlags, ppEvent); } MediaEventType meType = MEUnknown; if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) { } HRESULT hrStatus = S_OK; if (SUCCEEDED(hr)) hr = (*ppEvent)->GetStatus(&hrStatus); if (SUCCEEDED(hr)) DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str()); else DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE BeginGetEvent( IMFAsyncCallback *pCallback, IUnknown *punkState) { HRESULT hr = S_OK; <API key>(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->BeginGetEvent(pCallback, punkState); } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::BeginGetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE EndGetEvent( IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) { HRESULT hr = S_OK; <API key>(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->EndGetEvent(pResult, ppEvent); } MediaEventType meType = MEUnknown; if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) { } <API key>(&m_critSec); HRESULT hrStatus = S_OK; if (SUCCEEDED(hr)) hr = (*ppEvent)->GetStatus(&hrStatus); if (SUCCEEDED(hr)) DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str()); else DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE QueueEvent( MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue) { HRESULT hr = S_OK; <API key>(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue); } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(met).c_str()); DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i\n", hr); return hr; } IMFMediaTypeHandler methods // Check if a media type is supported. STDMETHODIMP <API key>( IMFMediaType *pMediaType, /* [out] */ IMFMediaType **ppMediaType) { if (pMediaType == nullptr) { return E_INVALIDARG; } <API key>(&m_critSec); GUID majorType = GUID_NULL; HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType); } // First make sure it's video or audio type. if (SUCCEEDED(hr)) { if (majorType != MFMediaType_Video && majorType != MFMediaType_Audio) { hr = MF_E_INVALIDTYPE; } } if (SUCCEEDED(hr) && m_spCurrentType != nullptr) { GUID guiNewSubtype; if (FAILED(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)) || guiNewSubtype != m_guiCurrentSubtype) { hr = MF_E_INVALIDTYPE; } } // We don't return any "close match" types. if (ppMediaType) { *ppMediaType = nullptr; } if (ppMediaType && SUCCEEDED(hr)) { _ComPtr<IMFMediaType> pType; hr = MFCreateMediaType(ppMediaType); if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(<API key>, __uuidof(IMFMediaType), (LPVOID*)&pType); } if (SUCCEEDED(hr)) { hr = pType->LockStore(); } bool bLocked = false; if (SUCCEEDED(hr)) { bLocked = true; UINT32 uiCount; UINT32 uiTotal; hr = pType->GetCount(&uiTotal); for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) { GUID guid; PROPVARIANT propval; hr = pType->GetItemByIndex(uiCount, &guid, &propval); if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == <API key> || guid == <API key> || guid == <API key> || guid == MF_MT_SUBTYPE)) { hr = (*ppMediaType)->SetItem(guid, propval); PropVariantClear(&propval); } } } if (bLocked) { hr = pType->UnlockStore(); } } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::<API key>: HRESULT=%i\n", hr); return hr; } // Return the number of preferred media types. STDMETHODIMP GetMediaTypeCount(DWORD *pdwTypeCount) { if (pdwTypeCount == nullptr) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // We've got only one media type *pdwTypeCount = 1; } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeCount: HRESULT=%i\n", hr); return hr; } // Return a preferred media type by index. STDMETHODIMP GetMediaTypeByIndex( DWORD dwIndex, /* [out] */ IMFMediaType **ppType) { if (ppType == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (dwIndex > 0) { hr = MF_E_NO_MORE_TYPES; } else { //return preferred type based on media capture library 6 elements preferred preview type //hr = m_spCurrentType.CopyTo(ppType); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaType> pType; hr = MFCreateMediaType(ppType); if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(<API key>, __uuidof(IMFMediaType), (LPVOID*)&pType); } if (SUCCEEDED(hr)) { hr = pType->LockStore(); } bool bLocked = false; if (SUCCEEDED(hr)) { bLocked = true; UINT32 uiCount; UINT32 uiTotal; hr = pType->GetCount(&uiTotal); for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) { GUID guid; PROPVARIANT propval; hr = pType->GetItemByIndex(uiCount, &guid, &propval); if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == <API key> || guid == <API key> || guid == <API key> || guid == MF_MT_SUBTYPE)) { hr = (*ppType)->SetItem(guid, propval); PropVariantClear(&propval); } } } if (bLocked) { hr = pType->UnlockStore(); } } } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeByIndex: HRESULT=%i\n", hr); return hr; } // Set the current media type. STDMETHODIMP SetCurrentMediaType(IMFMediaType *pMediaType) { if (pMediaType == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = S_OK; if (m_state != State_TypeNotSet && m_state != State_Ready) hr = MF_E_INVALIDREQUEST; if (SUCCEEDED(hr)) hr = CheckShutdown(); // We don't allow format changes after streaming starts. // We set media type already if (m_state >= State_Ready) { if (SUCCEEDED(hr)) { hr = <API key>(pMediaType, NULL); } } if (SUCCEEDED(hr)) { hr = MFCreateMediaType(m_spCurrentType.<API key>()); if (SUCCEEDED(hr)) { hr = pMediaType->CopyAllItems(m_spCurrentType.Get()); } if (SUCCEEDED(hr)) { hr = m_spCurrentType->GetGUID(MF_MT_SUBTYPE, &m_guiCurrentSubtype); } GUID guid; if (SUCCEEDED(hr)) { hr = m_spCurrentType->GetMajorType(&guid); } if (SUCCEEDED(hr) && guid == MFMediaType_Video) { hr = MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &<API key>, &<API key>); } if (SUCCEEDED(hr)) { m_state = State_Ready; } } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::SetCurrentMediaType: HRESULT=%i\n", hr); return hr; } // Return the current media type, if any. STDMETHODIMP GetCurrentMediaType(IMFMediaType **ppMediaType) { if (ppMediaType == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { if (m_spCurrentType == nullptr) { hr = <API key>; } } if (SUCCEEDED(hr)) { hr = m_spCurrentType.CopyTo(ppMediaType); } <API key>(&m_critSec); DebugPrintOut(L"StreamSink::GetCurrentMediaType: HRESULT=%i\n", hr); return hr; } // Return the major type GUID. STDMETHODIMP GetMajorType(GUID *pguidMajorType) { HRESULT hr; if (pguidMajorType == nullptr) { return E_INVALIDARG; } _ComPtr<IMFMediaType> pType; hr = m_pParent->GetUnknown(<API key>, __uuidof(IMFMediaType), (LPVOID*)&pType); if (SUCCEEDED(hr)) { hr = pType->GetMajorType(pguidMajorType); } DebugPrintOut(L"StreamSink::GetMajorType: HRESULT=%i\n", hr); return hr; } private: #ifdef HAVE_WINRT <API key> m_token; #else bool m_bConnected; #endif bool m_IsShutdown; // Flag to indicate if Shutdown() method was called. CRITICAL_SECTION m_critSec; #ifndef HAVE_WINRT long m_cRef; #endif IMFAttributes* m_pParent; _ComPtr<IMFMediaType> m_spCurrentType; _ComPtr<IMFMediaEventQueue> m_spEventQueue; // Event queue _ComPtr<IUnknown> m_spFTM; State m_state; bool <API key>; bool <API key>; MFTIME m_StartTime; // Presentation time when the clock started. GUID m_guiCurrentSubtype; UINT32 <API key>; UINT32 <API key>; }; // Notes: // The List class template implements a simple double-linked list. // It uses STL's copy semantics. // There are two versions of the Clear() method: // Clear(void) clears the list w/out cleaning up the object. // Clear(FN fn) takes a functor object that releases the objects, if they need cleanup. // The List class supports enumeration. Example of usage: // List<T>::POSIITON pos = list.GetFrontPosition(); // while (pos != list.GetEndPosition()) // T item; // hr = list.GetItemPos(&item); // pos = list.Next(pos); // The ComPtrList class template derives from List<> and implements a list of COM pointers. template <class T> struct NoOp { void operator()(T& ) { } }; template <class T> class List { protected: // Nodes in the linked list struct Node { Node *prev; Node *next; T item; Node() : prev(nullptr), next(nullptr) { } Node(T item) : prev(nullptr), next(nullptr) { this->item = item; } T Item() const { return item; } }; public: // Object for enumerating the list. class POSITION { friend class List<T>; public: POSITION() : pNode(nullptr) { } bool operator==(const POSITION &p) const { return pNode == p.pNode; } bool operator!=(const POSITION &p) const { return pNode != p.pNode; } private: const Node *pNode; POSITION(Node *p) : pNode(p) { } }; protected: Node m_anchor; // Anchor node for the linked list. DWORD m_count; // Number of items in the list. Node* Front() const { return m_anchor.next; } Node* Back() const { return m_anchor.prev; } virtual HRESULT InsertAfter(T item, Node *pBefore) { if (pBefore == nullptr) { return E_POINTER; } Node *pNode = new Node(item); if (pNode == nullptr) { return E_OUTOFMEMORY; } Node *pAfter = pBefore->next; pBefore->next = pNode; pAfter->prev = pNode; pNode->prev = pBefore; pNode->next = pAfter; m_count++; return S_OK; } virtual HRESULT GetItem(const Node *pNode, T* ppItem) { if (pNode == nullptr || ppItem == nullptr) { return E_POINTER; } *ppItem = pNode->item; return S_OK; } // RemoveItem: // Removes a node and optionally returns the item. // ppItem can be nullptr. virtual HRESULT RemoveItem(Node *pNode, T *ppItem) { if (pNode == nullptr) { return E_POINTER; } assert(pNode != &m_anchor); // We should never try to remove the anchor node. if (pNode == &m_anchor) { return E_INVALIDARG; } T item; // The next node's previous is this node's previous. pNode->next->prev = pNode->prev; // The previous node's next is this node's next. pNode->prev->next = pNode->next; item = pNode->item; delete pNode; m_count if (ppItem) { *ppItem = item; } return S_OK; } public: List() { m_anchor.next = &m_anchor; m_anchor.prev = &m_anchor; m_count = 0; } virtual ~List() { Clear(); } // Insertion functions HRESULT InsertBack(T item) { return InsertAfter(item, m_anchor.prev); } HRESULT InsertFront(T item) { return InsertAfter(item, &m_anchor); } HRESULT InsertPos(POSITION pos, T item) { if (pos.pNode == nullptr) { return InsertBack(item); } return InsertAfter(item, pos.pNode->prev); } // RemoveBack: Removes the tail of the list and returns the value. // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.) HRESULT RemoveBack(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return RemoveItem(Back(), ppItem); } } // RemoveFront: Removes the head of the list and returns the value. // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.) HRESULT RemoveFront(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return RemoveItem(Front(), ppItem); } } // GetBack: Gets the tail item. HRESULT GetBack(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return GetItem(Back(), ppItem); } } // GetFront: Gets the front item. HRESULT GetFront(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return GetItem(Front(), ppItem); } } // GetCount: Returns the number of items in the list. DWORD GetCount() const { return m_count; } bool IsEmpty() const { return (GetCount() == 0); } // Clear: Takes a functor object whose operator() // frees the object on the list. template <class FN> void Clear(FN& clear_fn) { Node *n = m_anchor.next; // Delete the nodes while (n != &m_anchor) { clear_fn(n->item); Node *tmp = n->next; delete n; n = tmp; } // Reset the anchor to point at itself m_anchor.next = &m_anchor; m_anchor.prev = &m_anchor; m_count = 0; } // Clear: Clears the list. (Does not delete or release the list items.) virtual void Clear() { NoOp<T> clearOp; Clear<>(clearOp); } // Enumerator functions POSITION FrontPosition() { if (IsEmpty()) { return POSITION(nullptr); } else { return POSITION(Front()); } } POSITION EndPosition() const { return POSITION(); } HRESULT GetItemPos(POSITION pos, T *ppItem) { if (pos.pNode) { return GetItem(pos.pNode, ppItem); } else { return E_FAIL; } } POSITION Next(const POSITION pos) { if (pos.pNode && (pos.pNode->next != &m_anchor)) { return POSITION(pos.pNode->next); } else { return POSITION(nullptr); } } // Remove an item at a position. // The item is returns in ppItem, unless ppItem is nullptr. // NOTE: This method invalidates the POSITION object. HRESULT Remove(POSITION& pos, T *ppItem) { if (pos.pNode) { // Remove const-ness temporarily... Node *pNode = const_cast<Node*>(pos.pNode); pos = POSITION(); return RemoveItem(pNode, ppItem); } else { return E_INVALIDARG; } } }; // Typical functors for Clear method. // ComAutoRelease: Releases COM pointers. // MemDelete: Deletes pointers to new'd memory. class ComAutoRelease { public: void operator()(IUnknown *p) { if (p) { p->Release(); } } }; class MemDelete { public: void operator()(void *p) { if (p) { delete p; } } }; // ComPtrList class // Derived class that makes it safer to store COM pointers in the List<> class. // It automatically AddRef's the pointers that are inserted onto the list // (unless the insertion method fails). // T must be a COM interface type. // example: ComPtrList<IUnknown> // NULLABLE: If true, client can insert nullptr pointers. This means GetItem can // succeed but return a nullptr pointer. By default, the list does not allow nullptr // pointers. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4127) // constant expression #endif template <class T, bool NULLABLE = FALSE> class ComPtrList : public List<T*> { public: typedef T* Ptr; void Clear() { ComAutoRelease car; List<Ptr>::Clear(car); } ~ComPtrList() { Clear(); } protected: HRESULT InsertAfter(Ptr item, Node *pBefore) { // Do not allow nullptr item pointers unless NULLABLE is true. if (item == nullptr && !NULLABLE) { return E_POINTER; } if (item) { item->AddRef(); } HRESULT hr = List<Ptr>::InsertAfter(item, pBefore); if (FAILED(hr) && item != nullptr) { item->Release(); } return hr; } HRESULT GetItem(const Node *pNode, Ptr* ppItem) { Ptr pItem = nullptr; // The base class gives us the pointer without AddRef'ing it. // If we return the pointer to the caller, we must AddRef(). HRESULT hr = List<Ptr>::GetItem(pNode, &pItem); if (SUCCEEDED(hr)) { assert(pItem || NULLABLE); if (pItem) { *ppItem = pItem; (*ppItem)->AddRef(); } } return hr; } HRESULT RemoveItem(Node *pNode, Ptr *ppItem) { // ppItem can be nullptr, but we need to get the // item so that we can release it. // If ppItem is not nullptr, we will AddRef it on the way out. Ptr pItem = nullptr; HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem); if (SUCCEEDED(hr)) { assert(pItem || NULLABLE); if (ppItem && pItem) { *ppItem = pItem; (*ppItem)->AddRef(); } if (pItem) { pItem->Release(); pItem = nullptr; } } return hr; } }; #ifdef _MSC_VER #pragma warning(pop) #endif /* Be sure to declare webcam device capability in manifest For better media capture support, add the following snippet with correct module name to the project manifest (highgui needs DLL activation class factoryentry points): <Extensions> <Extension Category="windows.activatableClass.inProcessServer"> <InProcessServer> <Path>modulename</Path> <ActivatableClass ActivatableClassId="cv.MediaSink" ThreadingModel="both" /> </InProcessServer> </Extension> </Extensions>*/ extern const __declspec(selectany) WCHAR <API key>[] = L"cv.MediaSink"; class MediaSink : #ifdef HAVE_WINRT public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >, Microsoft::WRL::Implements<ABI::Windows::Media::IMediaExtension>, IMFMediaSink, IMFClockStateSink, Microsoft::WRL::FtmBase, CBaseAttributes<>> #else public IMFMediaSink, public IMFClockStateSink, public CBaseAttributes<> #endif { #ifdef HAVE_WINRT InspectableClass(<API key>, BaseTrust) public: #else public: ULONG STDMETHODCALLTYPE AddRef() { return <API key>(&m_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG cRef = <API key>(&m_cRef); if (cRef == 0) { delete this; } return cRef; } #if defined(_MSC_VER) && _MSC_VER >= 1700 // '<API key>' SAL is avaialable since VS 2012 STDMETHOD(QueryInterface)(REFIID riid, <API key> void **ppv) #else STDMETHOD(QueryInterface)(REFIID riid, void **ppv) #endif { if (ppv == nullptr) { return E_POINTER; } (*ppv) = nullptr; HRESULT hr = S_OK; if (riid == IID_IUnknown || riid == IID_IMFMediaSink) { (*ppv) = static_cast<IMFMediaSink*>(this); AddRef(); } else if (riid == <API key>) { (*ppv) = static_cast<IMFClockStateSink*>(this); AddRef(); } else if (riid == IID_IMFAttributes) { (*ppv) = static_cast<IMFAttributes*>(this); AddRef(); } else { hr = E_NOINTERFACE; } return hr; } #endif MediaSink() : m_IsShutdown(false), m_llStartTime(0) { CBaseAttributes<>::Initialize(0U); <API key>(&m_critSec, 3000, 0); DebugPrintOut(L"MediaSink::MediaSink\n"); } virtual ~MediaSink() { DebugPrintOut(L"MediaSink::~MediaSink\n"); <API key>(&m_critSec); assert(m_IsShutdown); } HRESULT CheckShutdown() const { if (m_IsShutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } #ifdef HAVE_WINRT STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) { HRESULT hr = S_OK; if (pConfiguration) { Microsoft::WRL::ComPtr<IInspectable> spInsp; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>> spSetting; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropVal; Microsoft::WRL::ComPtr<ABI::Windows::Media::MediaProperties::<API key>> pMedEncProps; UINT32 uiType = ABI::Windows::Media::Capture::<API key>; hr = pConfiguration->QueryInterface(IID_PPV_ARGS(&spSetting)); if (FAILED(hr)) { hr = E_FAIL; } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(<API key>).Get(), spInsp.<API key>()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { hr = SetUnknown(<API key>, spInsp.Get()); } } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDTYPE).Get(), spInsp.<API key>()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { if (SUCCEEDED(hr = spInsp.As(&spPropVal))) { hr = spPropVal->GetUInt32(&uiType); } } } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDENCPROPS).Get(), spInsp.<API key>()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { hr = spInsp.As(&pMedEncProps); } } if (SUCCEEDED(hr)) { hr = <API key>((ABI::Windows::Media::Capture::MediaStreamType)uiType, pMedEncProps.Get()); } } return hr; } static DWORD GetStreamId(ABI::Windows::Media::Capture::MediaStreamType mediaStreamType) { return 3 - mediaStreamType; } static HRESULT AddAttribute(_In_ GUID guidKey, _In_ ABI::Windows::Foundation::IPropertyValue *pValue, _In_ IMFAttributes* pAttr) { HRESULT hr = S_OK; PROPVARIANT var; ABI::Windows::Foundation::PropertyType type; hr = pValue->get_Type(&type); ZeroMemory(&var, sizeof(var)); if (SUCCEEDED(hr)) { switch (type) { case ABI::Windows::Foundation::<API key>: { UINT32 cbBlob; BYTE *pbBlog = nullptr; hr = pValue->GetUInt8Array(&cbBlob, &pbBlog); if (SUCCEEDED(hr)) { if (pbBlog == nullptr) { hr = E_INVALIDARG; } else { hr = pAttr->SetBlob(guidKey, pbBlog, cbBlob); } } CoTaskMemFree(pbBlog); } break; case ABI::Windows::Foundation::PropertyType_Double: { DOUBLE value; hr = pValue->GetDouble(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetDouble(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_Guid: { GUID value; hr = pValue->GetGuid(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetGUID(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_String: { Microsoft::WRL::Wrappers::HString value; hr = pValue->GetString(value.GetAddressOf()); if (SUCCEEDED(hr)) { UINT32 len = 0; LPCWSTR szValue = <API key>(value.Get(), &len); hr = pAttr->SetString(guidKey, szValue); } } break; case ABI::Windows::Foundation::PropertyType_UInt32: { UINT32 value; hr = pValue->GetUInt32(&value); if (SUCCEEDED(hr)) { pAttr->SetUINT32(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_UInt64: { UINT64 value; hr = pValue->GetUInt64(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetUINT64(guidKey, value); } } break; case ABI::Windows::Foundation::<API key>: { Microsoft::WRL::ComPtr<IInspectable> value; hr = TYPE_E_TYPEMISMATCH; if (SUCCEEDED(hr)) { pAttr->SetUnknown(guidKey, value.Get()); } } break; // ignore unknown values } } return hr; } static HRESULT <API key>(_In_ ABI::Windows::Media::MediaProperties::<API key> *pMEP, _Outptr_ IMFMediaType **ppMT) { HRESULT hr = S_OK; _ComPtr<IMFMediaType> spMT; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<GUID, IInspectable*>> spMap; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterable; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterator; if (pMEP == nullptr || ppMT == nullptr) { return E_INVALIDARG; } *ppMT = nullptr; hr = pMEP->get_Properties(spMap.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spMap.As(&spIterable); } if (SUCCEEDED(hr)) { hr = spIterable->First(&spIterator); } if (SUCCEEDED(hr)) { MFCreateMediaType(spMT.<API key>()); } boolean hasCurrent = false; if (SUCCEEDED(hr)) { hr = spIterator->get_HasCurrent(&hasCurrent); } while (hasCurrent) { Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*> > spKeyValuePair; Microsoft::WRL::ComPtr<IInspectable> spValue; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue; GUID guidKey; hr = spIterator->get_Current(&spKeyValuePair); if (FAILED(hr)) { break; } hr = spKeyValuePair->get_Key(&guidKey); if (FAILED(hr)) { break; } hr = spKeyValuePair->get_Value(&spValue); if (FAILED(hr)) { break; } hr = spValue.As(&spPropValue); if (FAILED(hr)) { break; } hr = AddAttribute(guidKey, spPropValue.Get(), spMT.Get()); if (FAILED(hr)) { break; } hr = spIterator->MoveNext(&hasCurrent); if (FAILED(hr)) { break; } } if (SUCCEEDED(hr)) { Microsoft::WRL::ComPtr<IInspectable> spValue; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue; GUID guiMajorType; hr = spMap->Lookup(MF_MT_MAJOR_TYPE, spValue.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spValue.As(&spPropValue); } if (SUCCEEDED(hr)) { hr = spPropValue->GetGuid(&guiMajorType); } if (SUCCEEDED(hr)) { if (guiMajorType != MFMediaType_Video && guiMajorType != MFMediaType_Audio) { hr = E_UNEXPECTED; } } } if (SUCCEEDED(hr)) { *ppMT = spMT.Detach(); } return hr; } //this should be passed through SetProperties! HRESULT <API key>(ABI::Windows::Media::Capture::MediaStreamType MediaStreamType, _In_opt_ ABI::Windows::Media::MediaProperties::<API key> *<API key>) { HRESULT hr = S_OK; _ComPtr<IMFMediaType> spMediaType; if (MediaStreamType != ABI::Windows::Media::Capture::<API key> && MediaStreamType != ABI::Windows::Media::Capture::<API key> && MediaStreamType != ABI::Windows::Media::Capture::<API key>) { return E_INVALIDARG; } RemoveStreamSink(GetStreamId(MediaStreamType)); if (<API key> != nullptr) { _ComPtr<IMFStreamSink> spStreamSink; hr = <API key>(<API key>, &spMediaType); if (SUCCEEDED(hr)) { hr = AddStreamSink(GetStreamId(MediaStreamType), nullptr, spStreamSink.GetAddressOf()); } if (SUCCEEDED(hr)) { hr = SetUnknown(<API key>, spMediaType.Detach()); } } return hr; } #endif //IMFMediaSink HRESULT STDMETHODCALLTYPE GetCharacteristics( /* [out] */ __RPC__out DWORD *pdwCharacteristics) { HRESULT hr; if (pdwCharacteristics == NULL) return E_INVALIDARG; <API key>(&m_critSec); if (SUCCEEDED(hr = CheckShutdown())) { //if had an activation object for the sink, shut down would be managed and <API key> appears to be setable to TRUE *pdwCharacteristics = <API key>;// | <API key>; } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::GetCharacteristics: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE AddStreamSink( DWORD <API key>, IMFMediaType * /*pMediaType*/, IMFStreamSink **ppStreamSink) { _ComPtr<IMFStreamSink> spMFStream; _ComPtr<ICustomStreamSink> pStream; <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = GetStreamSinkById(<API key>, &spMFStream); } if (SUCCEEDED(hr)) { hr = <API key>; } else { hr = S_OK; } if (SUCCEEDED(hr)) { #ifdef HAVE_WINRT pStream = Microsoft::WRL::Make<StreamSink>(); if (pStream == nullptr) { hr = E_OUTOFMEMORY; } if (SUCCEEDED(hr)) hr = pStream.As<IMFStreamSink>(&spMFStream); #else StreamSink* pSink = new StreamSink(); if (pSink) { hr = pSink->QueryInterface(IID_IMFStreamSink, (void**)spMFStream.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spMFStream.As(&pStream); } if (FAILED(hr)) delete pSink; } #endif } // Initialize the stream. _ComPtr<IMFAttributes> pAttr; if (SUCCEEDED(hr)) { hr = pStream.As(&pAttr); } if (SUCCEEDED(hr)) { hr = pAttr->SetUINT32(MF_STREAMSINK_ID, <API key>); if (SUCCEEDED(hr)) { hr = pAttr->SetUnknown(<API key>, (IMFMediaSink*)this); } } if (SUCCEEDED(hr)) { hr = pStream->Initialize(); } if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION posEnd = m_streams.EndPosition(); // Insert in proper position for (; pos != posEnd; pos = m_streams.Next(pos)) { DWORD dwCurrId; _ComPtr<IMFStreamSink> spCurr; hr = m_streams.GetItemPos(pos, &spCurr); if (FAILED(hr)) { break; } hr = spCurr->GetIdentifier(&dwCurrId); if (FAILED(hr)) { break; } if (dwCurrId > <API key>) { break; } } if (SUCCEEDED(hr)) { hr = m_streams.InsertPos(pos, spMFStream.Get()); } } if (SUCCEEDED(hr)) { *ppStreamSink = spMFStream.Detach(); } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::AddStreamSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE RemoveStreamSink(DWORD <API key>) { <API key>(&m_critSec); HRESULT hr = CheckShutdown(); ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); _ComPtr<IMFStreamSink> spStream; if (SUCCEEDED(hr)) { for (; pos != endPos; pos = m_streams.Next(pos)) { hr = m_streams.GetItemPos(pos, &spStream); DWORD dwId; if (FAILED(hr)) { break; } hr = spStream->GetIdentifier(&dwId); if (FAILED(hr) || dwId == <API key>) { break; } } if (pos == endPos) { hr = <API key>; } } if (SUCCEEDED(hr)) { hr = m_streams.Remove(pos, nullptr); _ComPtr<ICustomStreamSink> spCustomSink; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(spStream.Get()); hr = S_OK; #else hr = spStream.As(&spCustomSink); #endif if (SUCCEEDED(hr)) hr = spCustomSink->Shutdown(); } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::RemoveStreamSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkCount(DWORD *pStreamSinkCount) { if (pStreamSinkCount == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { *pStreamSinkCount = m_streams.GetCount(); } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkCount: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE <API key>( DWORD dwIndex, IMFStreamSink **ppStreamSink) { if (ppStreamSink == NULL) { return E_INVALIDARG; } _ComPtr<IMFStreamSink> spStream; <API key>(&m_critSec); DWORD cStreams = m_streams.GetCount(); if (dwIndex >= cStreams) { return MF_E_INVALIDINDEX; } HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); DWORD dwCurrent = 0; for (; pos != endPos && dwCurrent < dwIndex; pos = m_streams.Next(pos), ++dwCurrent) { // Just move to proper position } if (pos == endPos) { hr = MF_E_UNEXPECTED; } else { hr = m_streams.GetItemPos(pos, &spStream); } } if (SUCCEEDED(hr)) { *ppStreamSink = spStream.Detach(); } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::<API key>: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkById( DWORD <API key>, IMFStreamSink **ppStreamSink) { if (ppStreamSink == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); _ComPtr<IMFStreamSink> spResult; if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); for (; pos != endPos; pos = m_streams.Next(pos)) { _ComPtr<IMFStreamSink> spStream; hr = m_streams.GetItemPos(pos, &spStream); DWORD dwId; if (FAILED(hr)) { break; } hr = spStream->GetIdentifier(&dwId); if (FAILED(hr)) { break; } else if (dwId == <API key>) { spResult = spStream; break; } } if (pos == endPos) { hr = <API key>; } } if (SUCCEEDED(hr)) { assert(spResult); *ppStreamSink = spResult.Detach(); } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkById: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE <API key>( <API key> *pPresentationClock) { <API key>(&m_critSec); HRESULT hr = CheckShutdown(); // If we already have a clock, remove ourselves from that clock's // state notifications. if (SUCCEEDED(hr)) { if (m_spClock) { hr = m_spClock-><API key>(this); } } // Register ourselves to get state notifications from the new clock. if (SUCCEEDED(hr)) { if (pPresentationClock) { hr = pPresentationClock->AddClockStateSink(this); } } _ComPtr<<API key>> pSampleCallback; if (SUCCEEDED(hr)) { // Release the pointer to the old clock. // Store the pointer to the new clock. m_spClock = pPresentationClock; hr = GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); } <API key>(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback-><API key>(pPresentationClock); DebugPrintOut(L"MediaSink::<API key>: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE <API key>( <API key> **ppPresentationClock) { if (ppPresentationClock == NULL) { return E_INVALIDARG; } <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { if (!m_spClock) { hr = MF_E_NO_CLOCK; // There is no presentation clock. } else { // Return the pointer to the caller. hr = m_spClock.CopyTo(ppPresentationClock); } } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::<API key>: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE Shutdown(void) { <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { ForEach(m_streams, ShutdownFunc()); m_streams.Clear(); m_spClock.<API key>(); _ComPtr<IMFMediaType> pType; hr = CBaseAttributes<>::GetUnknown(<API key>, __uuidof(IMFMediaType), (LPVOID*)pType.GetAddressOf()); if (SUCCEEDED(hr)) { hr = DeleteItem(<API key>); } m_IsShutdown = true; } <API key>(&m_critSec); DebugPrintOut(L"MediaSink::Shutdown: HRESULT=%i\n", hr); return hr; } class ShutdownFunc { public: HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Shutdown(); return hr; } }; class StartFunc { public: StartFunc(LONGLONG llStartTime) : _llStartTime(llStartTime) { } HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Start(_llStartTime); return hr; } LONGLONG _llStartTime; }; class StopFunc { public: HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Stop(); return hr; } }; template <class T, class TFunc> HRESULT ForEach(ComPtrList<T> &col, TFunc fn) { ComPtrList<T>::POSITION pos = col.FrontPosition(); ComPtrList<T>::POSITION endPos = col.EndPosition(); HRESULT hr = S_OK; for (; pos != endPos; pos = col.Next(pos)) { _ComPtr<T> spStream; hr = col.GetItemPos(pos, &spStream); if (FAILED(hr)) { break; } hr = fn(spStream.Get()); } return hr; } //IMFClockStateSink HRESULT STDMETHODCALLTYPE OnClockStart( MFTIME hnsSystemTime, LONGLONG llClockStartOffset) { <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // Start each stream. m_llStartTime = llClockStartOffset; hr = ForEach(m_streams, StartFunc(llClockStartOffset)); } _ComPtr<<API key>> pSampleCallback; if (SUCCEEDED(hr)) hr = GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); <API key>(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockStart(hnsSystemTime, llClockStartOffset); DebugPrintOut(L"MediaSink::OnClockStart: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockStop( MFTIME hnsSystemTime) { <API key>(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // Stop each stream hr = ForEach(m_streams, StopFunc()); } _ComPtr<<API key>> pSampleCallback; if (SUCCEEDED(hr)) hr = GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); <API key>(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockStop(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockStop: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockPause( MFTIME hnsSystemTime) { HRESULT hr; _ComPtr<<API key>> pSampleCallback; hr = GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockPause(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockPause: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockRestart( MFTIME hnsSystemTime) { HRESULT hr; _ComPtr<<API key>> pSampleCallback; hr = GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockRestart(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockRestart: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockSetRate( MFTIME hnsSystemTime, float flRate) { HRESULT hr; _ComPtr<<API key>> pSampleCallback; hr = GetUnknown(<API key>, <API key>, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockSetRate(hnsSystemTime, flRate); DebugPrintOut(L"MediaSink::OnClockSetRate: HRESULT=%i\n", hr); return hr; } private: #ifndef HAVE_WINRT long m_cRef; #endif CRITICAL_SECTION m_critSec; bool m_IsShutdown; ComPtrList<IMFStreamSink> m_streams; _ComPtr<<API key>> m_spClock; LONGLONG m_llStartTime; }; #ifdef HAVE_WINRT ActivatableClass(MediaSink); #endif
#money Node.js module to perform precise common money calculations. This library is a partial javascript implementation of the [Money Pattern](http://martinfowler.com/eaaCatalog/money.html) as described by Martin Fowler in his book *Patterns of Enterprise Application Architecture*. ## Using the library javascript var money = require('path/to/lib/money.js'); // Show me those monies var inheritance = money.dollar(1234567.89); // Subtract taxes var TAXMAN = 0.69; var netSum = inheritance.mult(TAXMAN); console.log(netSum.toNumber()); // 851851.84 // Hand out loot to heirs. // The oldest will receive 40% of the money, the next one 30% etc. var heirs = netSum.allocate([4,3,2,1]); heirs.forEach(function(heir) { console.log(heir.toNumber()); }); // 340740.74 // 255555.56 // 170370.36 // 85185.18 var addBack = heirs[0].add(heirs[1]).add(heirs[2]).add(heirs[3]); assert.deepEqual(addBack, netSum); // undefined (wow so money much precise) ## Running the tests (*nix only) 1. Clone and install [node-jscoverage](https://github.com/visionmedia/node-jscoverage) in your system 2. Enter the money repository and run `jscoverage lib/ lib-cov/` to instrument the library 3. Install [Mocha](http://mochajs.org/) as a command via npm `sudo npm install -g mocha` * a. To run the tests execute the following command: `mocha --ui tdd test/test.js` * b. To view a coverage report use the `html-cov` reporter: `mocha --ui tdd -R html-cov test/test.js > report.html` and open the HTML file with your browser of choice.
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('PetIndexCtrl', function($scope, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pets = PetService.all(); }) // A simple controller that shows a tapped item's data .controller('PetDetailCtrl', function($scope, $stateParams, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pet = PetService.get($stateParams.petId); }) // getting fake favor data .controller('FavorIndexCtrl', function($scope, FavorService) { $scope.favors = FavorService.all(); }) // A simple controller that shows a tapped item's data .controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) { // "Pets" is a service returning mock data (services.js) $scope.favor = FavorService.get($stateParams.favorId); });
<html lang="en"> <head> <title>Native - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Configurations.html#Configurations" title="Configurations"> <link rel="next" href="Embedded-OS.html#Embedded-OS" title="Embedded OS"> <link href="http: <! Copyright (C) 1988-2014 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 the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' <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="Native"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Embedded-OS.html#Embedded-OS">Embedded OS</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Configurations.html#Configurations">Configurations</a> <hr> </div> <h3 class="section">21.1 Native</h3> <p>This section describes details specific to particular native configurations. <ul class="menu"> <li><a accesskey="1" href="HP_002dUX.html#HP_002dUX">HP-UX</a>: HP-UX <li><a accesskey="2" href="<API key>.html#<API key>">BSD libkvm Interface</a>: Debugging BSD kernel memory images <li><a accesskey="3" href="<API key>.html#<API key>">SVR4 Process Information</a>: SVR4 process information <li><a accesskey="4" href="DJGPP-Native.html#DJGPP-Native">DJGPP Native</a>: Features specific to the DJGPP port <li><a accesskey="5" href="Cygwin-Native.html#Cygwin-Native">Cygwin Native</a>: Features specific to the Cygwin port <li><a accesskey="6" href="Hurd-Native.html#Hurd-Native">Hurd Native</a>: Features specific to <span class="sc">gnu</span> Hurd <li><a accesskey="7" href="Darwin.html#Darwin">Darwin</a>: Features specific to Darwin </ul> </body></html>
// FXCachePlist.h // FancyMall #import <Foundation/Foundation.h> @interface FXCachePlist : NSObject +(instancetype)sharedPlist; -(NSString *)needRemoveFileName; -(void)<API key>:(NSString *)url withMark:(NSString *)mark; -(void)<API key>; -(NSMutableArray *)readArrayFramePlist; //-(void)<API key>; //-(void)dataToPlist:(NSMutableArray *)mutArray; -(void)removeFileByLabel:(NSString *)label; @end
// modification, are permitted provided that the following conditions are // met: // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. var <API key> = 11; function WaveTable(name, context) { this.name = name; this.context = context; this.sampleRate = context.sampleRate; this.url = "wave-tables/" + this.name; this.waveTableSize = 4096; // hard-coded for now this.buffer = 0; this.<API key> = <API key>; } WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) { var nyquist = 0.5 * this.sampleRate; var lowestNumPartials = this.<API key>(0); var lowestFundamental = nyquist / lowestNumPartials; // Find out pitch range var ratio = pitchFrequency / lowestFundamental; var pitchRange = ratio == 0.0 ? 0 : Math.floor(Math.log(ratio) / Math.LN2); if (pitchRange < 0) pitchRange = 0; // Too bad, we'll alias if pitch is greater than around 5KHz :) if (pitchRange >= this.<API key>) pitchRange = this.<API key> - 1; return this.buffers[pitchRange]; } WaveTable.prototype.<API key> = function(j) { // goes from 1024 -> 4 @ 44.1KHz (and do same for 48KHz) // goes from 2048 -> 8 @ 96KHz var npartials = Math.pow(2, 1 + this.<API key> - j); if (this.getSampleRate() > 48000.0) npartials *= 2; // high sample rate allows more harmonics at given fundamental return npartials; } WaveTable.prototype.getWaveTableSize = function() { return this.waveTableSize; } WaveTable.prototype.getSampleRate = function() { return this.sampleRate; } WaveTable.prototype.getRateScale = function() { return this.getWaveTableSize() / this.getSampleRate(); } WaveTable.prototype.<API key> = function() { this.<API key>; } WaveTable.prototype.getName = function() { return this.name; } WaveTable.prototype.load = function(callback) { var request = new XMLHttpRequest(); request.open("GET", this.url, true); var wave = this; request.onload = function() { // Get the frequency-domain waveform data. var f = eval('(' + request.responseText + ')'); // Copy into more efficient Float32Arrays. var n = f.real.length; frequencyData = { "real": new Float32Array(n), "imag": new Float32Array(n) }; wave.frequencyData = frequencyData; for (var i = 0; i < n; ++i) { frequencyData.real[i] = f.real[i]; frequencyData.imag[i] = f.imag[i]; } wave.createBuffers(); if (callback) callback(wave); }; request.onerror = function() { alert("error loading: " + wave.url); }; request.send(); } WaveTable.prototype.print = function() { var f = this.frequencyData; var info = document.getElementById("info"); var s = ""; for (var i = 0; i < 2048; ++i) { s += "{" + f.real[i] + ", " + f.imag[i] + "}, <br>"; } info.innerHTML = s; } WaveTable.prototype.printBuffer = function(buffer) { var info = document.getElementById("info"); var s = ""; for (var i = 0; i < 4096; ++i) { s += buffer[i] + "<br>"; } info.innerHTML = s; } // WaveTable.prototype.createBuffers = function() { // var f = this.frequencyData; // var n = 4096; // var fft = new FFT(n, 44100); // // Copy from loaded frequency data and scale. // for (var i = 0; i < n / 2; ++i) { // fft.real[i] = 4096 * f.real[i]; // fft.imag[i] = 4096 * f.imag[i]; // // Now do inverse FFT // this.data = fft.inverse(); // var data = this.data; // this.buffer = context.createBuffer(1, data.length, 44100); // // Copy data to the buffer. // var p = this.buffer.getChannelData(0); // for (var i = 0; i < data.length; ++i) { // p[i] = data[i]; // Convert into time-domain wave tables. // We actually create several of them for non-aliasing playback at different playback rates. WaveTable.prototype.createBuffers = function() { // resample ranges // let's divide up versions of our waves based on the maximum fundamental frequency we're // resampling at. Let's use fundamental frequencies based on dividing Nyquist by powers of two. // For example for 44.1KHz sample-rate we have: // ranges // 21Hz, 43Hz, 86Hz, 172Hz, 344Hz, 689Hz, 1378Hz, 2756Hz, 5512Hz, 11025Hz, 22050Hz <-- 44.1KHz // 23Hz, 47Hz, 94Hz, 187Hz, 375Hz, 750Hz, 1500Hz, 3000Hz, 6000Hz, 12000Hz, 24000Hz, 48000Hz <-- 96KHz // and number of partials: // 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 // 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 // But it's probably OK if we skip the very highest fundamental frequencies and only // go up to 5512Hz, so we have a total of 9 resample ranges // 0 1 2 3 4 5 6 7 8 // The FFT size needs to be at least 2048 @ 44.1KHz and 4096 @ 96KHz // So let's try to use FFT size of 4096 all the time and pull out the harmonics we want this.buffers = new Array(); var finalScale = 1.0; for (var j = 0; j < this.<API key>; ++j) { var n = this.waveTableSize; var frame = new FFT(n, this.sampleRate); // Copy from loaded frequency data and scale. var f = this.frequencyData; var scale = n; for (var i = 0; i < n / 2; ++i) { frame.real[i] = scale * f.real[i]; frame.imag[i] = scale * f.imag[i]; } var realP = frame.real; var imagP = frame.imag; // Find the starting bin where we should start clearing out // (we need to clear out the highest frequencies to band-limit the waveform) var fftSize = n; var halfSize = fftSize / 2; var npartials = this.<API key>(j); // Now, go through and cull out the aliasing harmonics... for (var i = npartials + 1; i < halfSize; i++) { realP[i] = 0.0; imagP[i] = 0.0; } // Clear packed-nyquist if necessary if (npartials < halfSize) imagP[0] = 0.0; // Clear any DC-offset realP[0] = 0.0; // For the first resample range, find power and compute scale. if (j == 0) { var power = 0; for (var i = 1; i < halfSize; ++i) { x = realP[i]; y = imagP[i]; power += x * x + y * y; } power = Math.sqrt(power) / fftSize; finalScale = 0.5 / power; // window.console.log("power = " + power); } // Great, now do inverse FFT into our wavetable... var data = frame.inverse(); // Create mono AudioBuffer. var buffer = this.context.createBuffer(1, data.length, this.sampleRate); // Copy data to the buffer. var p = buffer.getChannelData(0); for (var i = 0; i < data.length; ++i) { p[i] = finalScale * data[i]; } this.buffers[j] = buffer; } } WaveTable.prototype.displayWaveData = function() { var data = this.data; var n = data.length; var s = ""; for (var i = 0; i < n; ++i) { s += data[i].toFixed(3) + "<br> "; } var info = document.getElementById("info"); info.innerHTML = s; }
Java.perform(function() { var cn = "android.telephony.SubscriptionManager"; var target = Java.use(cn); if (target) { target.<API key>.overloads[0].implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "<API key>"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.<API key>.overloads[0].apply(this, arguments); }; // target.<API key>.overloads[1].implementation = function(dest) { // var myArray=new Array() // myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE // myArray[1] = cn + "." + "<API key>"; // myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); // send(myArray); // return this.<API key>.overloads[1].apply(this, arguments); target.<API key>.overloads[0].implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "<API key>"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.<API key>.overloads[0].apply(this, arguments); }; // target.<API key>.overloads[1].implementation = function(dest) { // var myArray=new Array() // myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE // myArray[1] = cn + "." + "<API key>"; // myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); // send(myArray); // return this.<API key>.overloads[1].apply(this, arguments); target.<API key>.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "<API key>"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.<API key>.apply(this, arguments); }; target.<API key>.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "<API key>"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.<API key>.apply(this, arguments); }; target.<API key>.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "<API key>"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.<API key>.apply(this, arguments); }; } });
#!/bin/bash FN="<API key>.db_3.2.3.tar.gz" URLS=( "https://bioconductor.org/packages/3.11/data/annotation/src/contrib/<API key>.db_3.2.3.tar.gz" "https://bioarchive.galaxyproject.org/<API key>.db_3.2.3.tar.gz" "https://depot.galaxyproject.org/software/<API key>.db/<API key>.db_3.2.3_src_all.tar.gz" "https://depot.galaxyproject.org/software/<API key>.db/<API key>.db_3.2.3_src_all.tar.gz" ) MD5="<API key>" # Use a staging area in the conda dir rather than temp dirs, both to avoid # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
#import <UIKit/UIKit.h> #import "OLCVideoPlayer.h" FOUNDATION_EXPORT double <API key>; FOUNDATION_EXPORT const unsigned char <API key>[];
"use strict"; const chalk = require("chalk"); const readline = require("readline"); /** * Fill screen with blank lines, move to "0" afterwards and clear screen afterwards. * Note that it is still possible to "scroll back" afterwards. * * Function performs nothing in case the stdout is NOT a TTY. */ exports.cls = function() { if (process.stdout.isTTY) { const blank = "\n".repeat(process.stdout.rows); console.log(blank); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } }; /** * A less soft version of `cls` above which completely clears out the screen, * without leaving the option to scroll up again. * * Function performs nothing in case the stdout is NOT a TTY. */ exports.hardCls = function() { if (process.stdout.isTTY) { process.stdout.write( process.platform === "win32" ? "\x1Bc" : "\x1B[2J\x1B[3J\x1B[H" ); } }; exports.<API key> = function(text) { return chalk.bgWhite.black(text); };
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt--> <title>Method AssetAnimation.convertVectorArray</title> <link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/> <link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/> <script type="text/javascript" src="../../scripts/jquery.js"></script> <script type="text/javascript" src="../../prettify/prettify.js"></script> <script type="text/javascript" src="../../scripts/ddox.js"></script> </head> <body onload="prettyPrint(); setupDdox();"> <nav id="main-nav"><!-- using block navigation in layout.dt--> <ul class="tree-view"> <li class=" tree-view"> <a href="#" class="package">components</a> <ul class="tree-view"> <li> <a href="../../components/animation.html" class="selected module">animation</a> </li> <li> <a href="../../components/assets.html" class=" module">assets</a> </li> <li> <a href="../../components/behavior.html" class=" module">behavior</a> </li> <li> <a href="../../components/camera.html" class=" module">camera</a> </li> <li> <a href="../../components/icomponent.html" class=" module">icomponent</a> </li> <li> <a href="../../components/lights.html" class=" module">lights</a> </li> <li> <a href="../../components/material.html" class=" module">material</a> </li> <li> <a href="../../components/mesh.html" class=" module">mesh</a> </li> <li> <a href="../../components/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">core</a> <ul class="tree-view"> <li> <a href="../../core/dgame.html" class=" module">dgame</a> </li> <li> <a href="../../core/gameobject.html" class=" module">gameobject</a> </li> <li> <a href="../../core/prefabs.html" class=" module">prefabs</a> </li> <li> <a href="../../core/properties.html" class=" module">properties</a> </li> <li> <a href="../../core/reflection.html" class=" module">reflection</a> </li> <li> <a href="../../core/scene.html" class=" module">scene</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">graphics</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">adapters</a> <ul class="tree-view"> <li> <a href="../../graphics/adapters/adapter.html" class=" module">adapter</a> </li> <li> <a href="../../graphics/adapters/linux.html" class=" module">linux</a> </li> <li> <a href="../../graphics/adapters/mac.html" class=" module">mac</a> </li> <li> <a href="../../graphics/adapters/win32.html" class=" module">win32</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">shaders</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">glsl</a> <ul class="tree-view"> <li> <a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a> </li> <li> <a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a> </li> <li> <a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a> </li> <li> <a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a> </li> <li> <a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a> </li> <li> <a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li> <a href="../../graphics/shaders/glsl.html" class=" module">glsl</a> </li> <li> <a href="../../graphics/shaders/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li> <a href="../../graphics/adapters.html" class=" module">adapters</a> </li> <li> <a href="../../graphics/graphics.html" class=" module">graphics</a> </li> <li> <a href="../../graphics/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">utility</a> <ul class="tree-view"> <li> <a href="../../utility/array.html" class=" module">array</a> </li> <li> <a href="../../utility/awesomium.html" class=" module">awesomium</a> </li> <li> <a href="../../utility/concurrency.html" class=" module">concurrency</a> </li> <li> <a href="../../utility/config.html" class=" module">config</a> </li> <li> <a href="../../utility/filepath.html" class=" module">filepath</a> </li> <li> <a href="../../utility/input.html" class=" module">input</a> </li> <li> <a href="../../utility/output.html" class=" module">output</a> </li> <li> <a href="../../utility/string.html" class=" module">string</a> </li> <li> <a href="../../utility/tasks.html" class=" module">tasks</a> </li> <li> <a href="../../utility/time.html" class=" module">time</a> </li> </ul> </li> <li> <a href="../../components.html" class=" module">components</a> </li> <li> <a href="../../core.html" class=" module">core</a> </li> <li> <a href="../../graphics.html" class=" module">graphics</a> </li> <li> <a href="../../utility.html" class=" module">utility</a> </li> </ul> <noscript> <p style="color: red">The search functionality needs JavaScript enabled</p> </noscript> <div id="symbolSearchPane" style="display: none"> <p> <input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/> </p> <ul id="symbolSearchResults" style="display: none"></ul> <script type="application/javascript" src="../../symbols.js"></script> <script type="application/javascript"> //<![CDATA[ var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show(); </script> </div> </nav> <div id="main-contents"> <h1>Method AssetAnimation.convertVectorArray</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt--> <p> Converts a aiVectorKey[] to vec3[]. </p> <section></section> <section> <h2>Prototype</h2> <pre class="code prettyprint lang-d prototype"> shared(gl3n.linalg.Vector!(float,3)[]) convertVectorArray( &nbsp;&nbsp;const(derelict.assimp3.types.aiVectorKey*) vectors, &nbsp;&nbsp;int numKeys ) shared;</pre> </section> <section><h2>Parameters</h2> <table><col class="caption"><tr><th>Name</th><th>Description</th></tr> <tr><td id="quaternions">quaternions</td><td> aiVectorKey[] to be converted</td></tr> <tr><td id="numKeys">numKeys</td><td> Number of keys in vector array</td></tr> </table> </section> <section><h2>Returns</h2> <p>The <a href="../../components/animation/AssetAnimation.convertVectorArray.html#vectors"><code class="prettyprint lang-d">vectors</code></a> in vector[] format </p> </section> <section> <h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt--> </section> <section> <h2>Copyright</h2> </section> <section> <h2>License</h2> </section> </div> </body> </html>
module Locomotive class SitePolicy < ApplicationPolicy class Scope < Scope def resolve if membership.account.super_admin? scope.all else membership.account.sites end end end def index? true end def show? true end def create? true end def update? super_admin? || site_staff? end def destroy? super_admin? || site_admin? end def point? super_admin? || site_admin? end def update_advanced? super_admin? || site_admin? end def <API key>? super_admin? || site_admin? end def <API key> plain = [:name, :handle, :picture, :remove_picture, :seo_title, :meta_keywords, :meta_description, :timezone_name, :robots_txt] hash = { domains: [], locales: [] } unless update_advanced? plain -= [:timezone_name, :robots_txt] hash.delete(:locales) end unless point? plain -= [:handle] hash.delete(:domains) end plain << hash end end end
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) line += " " busses.status_bus["latest_messages"][msg.chat_id] = msg msg_type = helper.get_message_type(msg) if msg_type == "text" and msg.text.startswith("/"): msg_type = "command" appendix = "ERROR" if msg_type == "text": appendix = msg.text elif msg_type == "command": appendix = msg.text[1:] elif msg_type == "location": location_data = msg.location.to_dict() appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°" elif msg_type == "contact": appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name elif msg_type == "new_user": appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name) elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]: appendix = "" msg_type = msg_type.rjust(10, str(" ")) appendix = appendix.replace("\n", "\\n").rjust(40, str(" ")) line += msg_type + " " + appendix + " " line += str(msg.chat_id) + "," + str(msg.message_id) line += "\n" with open(config.msg_log_file_path, "a") as log_file: log_file.write(line.encode("utf-8")) def complete_log(update): with open(config.<API key>, "a") as log_file: data = update.to_dict() data.update({"time": time.time()}) json_data = json.dumps(data) log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
<div layout="vertical"> <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')"> <md-toolbar> <h1>Characters</h1> </md-toolbar> <char-list></char-list> </md-sidenav> </div>
public class LeetCode0363 { public int maxSumSubmatrix(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length, ans = Integer.MIN_VALUE; long[] sum = new long[m + 1]; for (int i = 0; i < n; ++i) { long[] sumInRow = new long[m]; for (int j = i; j < n; ++j) { for (int p = 0; p < m; ++p) { sumInRow[p] += matrix[p][j]; sum[p + 1] = sum[p] + sumInRow[p]; } ans = Math.max(ans, mergeSort(sum, 0, m + 1, k)); if (ans == k) return k; } } return ans; } int mergeSort(long[] sum, int start, int end, int k) { if (end == start + 1) return Integer.MIN_VALUE; int mid = start + (end - start) / 2, cnt = 0; int ans = mergeSort(sum, start, mid, k); if (ans == k) return k; ans = Math.max(ans, mergeSort(sum, mid, end, k)); if (ans == k) return k; long[] cache = new long[end - start]; for (int i = start, j = mid, p = mid; i < mid; ++i) { while (j < end && sum[j] - sum[i] <= k){ ++j; } if (j - 1 >= mid) { ans = Math.max(ans, (int) (sum[j - 1] - sum[i])); if (ans == k){ return k; } } while (p < end && sum[p] < sum[i]){ cache[cnt++] = sum[p++]; } cache[cnt++] = sum[i]; } System.arraycopy(cache, 0, sum, start, cnt); return ans; } }
<?php namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class <API key> extends AbstractTag { protected $Id = '2130,0030'; protected $Name = '<API key>'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Film Box Content Sequence'; }
<?php namespace Cascade\Mapper\Map; use Cascade\Mapper\Mapping\MappingInterface; class Map implements MapInterface { /** * @var MappingInterface[] */ private $mappings = []; /** * @param MappingInterface[] $mappings */ public function __construct($mappings) { foreach ($mappings as $mapping) { $this->addMapping($mapping); } } public function getMappings() { return $this->mappings; } /** * @param MappingInterface $mapping */ private function addMapping(MappingInterface $mapping) { $this->mappings[] = $mapping; } }
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, name='spectrum') driver = Spectrum(client) laser = Laser(client) laser.start() current = 30 laser.set_current(current) # driver.reset_acquisition() wfm_size = 4096 decimation_factor = 1 index_low = 0 index_high = wfm_size / 2 signal = driver.get_decimated_data(decimation_factor, index_low, index_high) print('Signal') print(signal) mhz = 1e6 sampling_rate = 125e6 freq_min = 0 freq_max = sampling_rate / mhz / 2 # Plot parameters fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(freq_min, freq_max, (wfm_size / 2)) print('X') print(len(x)) y = 10*np.log10(signal) print('Y') print(len(y)) li, = ax.plot(x, y) fig.canvas.draw() ax.set_xlim((x[0],x[-1])) ax.set_ylim((0,200)) ax.set_xlabel('Frequency (MHz)') ax.set_ylabel('Power spectral density (dB)') while True: try: signal = driver.get_decimated_data(decimation_factor, index_low, index_high) li.set_ydata(10*np.log10(signal)) fig.canvas.draw() plt.pause(0.001) except KeyboardInterrupt: # Save last spectrum in a csv file np.savetxt("psd.csv", signal, delimiter=",") laser.stop() driver.close() break
const assert = require('assert') const crypto = require('crypto') const { createRequest } = require("../util/util") describe('', () => { it(' name ', done => { const keywords = "" const type = 1 const limit = 30 const data = 's=' + keywords + '&limit=' + limit + '&type=' + type + '&offset=0' createRequest('/api/search/pc/', 'POST', data) .then(result => { console.log(JSON.parse(result).result.songs[0].mp3Url) assert(JSON.parse(result).result.songs[0].name === '') done() }) .catch(err => { done(err) }) }) })
<footer class="site-footer"> <div class="container"> <small class="pull-right">Made with <a href="http://jekyllrb.com/" target="_blank">Jekyll</a></small> </div> </footer>
<!DOCTYPE html> <html> {% include head.html %} <body> {%include banner.html%} {%include middle.html%} <!-- <script src="{{ site.baseurl }}/js/index.js"></script> --> </body> <footer></footer> </html>
export default function <API key>() { return (root) => { root.walkRules((node) => { let seen = new Map() let droppable = new Set([]) node.walkDecls((decl) => { // This could happen if we have nested selectors. In that case the // parent will loop over all its declarations but also the declarations // of nested rules. With this we ensure that we are shallowly checking // declarations. if (decl.parent !== node) { return } if (seen.has(decl.prop)) { droppable.add(seen.get(decl.prop)) } seen.set(decl.prop, decl) }) for (let decl of droppable) { decl.remove() } }) } }
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true, "jasmine" : true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "<API key>": [2, "smart-tabs"], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
import * as debug from 'debug'; import Resolver from '../../resolver'; import { IRemoteUser } from '../../../../models/user'; import acceptFollow from './follow'; import { IAccept, IFollow } from '../../type'; const log = debug('misskey:activitypub'); export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => { const uri = activity.id || activity; log(`Accept: ${uri}`); const resolver = new Resolver(); let object; try { object = await resolver.resolve(activity.object); } catch (e) { log(`Resolution failed: ${e}`); throw e; } switch (object.type) { case 'Follow': acceptFollow(actor, object as IFollow); break; default: console.warn(`Unknown accept type: ${object.type}`); break; } };
/** \brief A timer module with only a single compare value. Can be used to replace the "bsp_timer" and "radiotimer" modules with the help of abstimer. \author Xavi Vilajosana <xvilajosana@eecs.berkeley.edu>, May 2012. \author Thomas Watteyne <watteyne@eecs.berkeley.edu>, May 2012. */ #include "sctimer.h" #include "msp430x26x.h" typedef struct { uint8_t running; uint16_t taiv; } sctimers_vars_t; sctimers_vars_t sctimers_vars; void sctimer_setup(); void sctimer_start(); void sctimer_init() { sctimer_setup(); } void sctimer_stop() { sctimer_setup(); } void sctimer_schedule(uint16_t val) { if (sctimers_vars.running==0) { sctimers_vars.running=1; sctimer_start(); } // load when to fire TACCR1 = val; // enable interrupt TACCTL1 = CCIE; } uint16_t sctimer_getValue() { return TAR; } void sctimer_setCb(sctimer_cbt cb){ // does nothing as it is done by IAR -- look at board.c } void sctimer_clearISR() { sctimers_vars.taiv = TAIV;//read taiv to clear the flags. } void sctimer_setup() { // clear local variables memset(&sctimers_vars,0,sizeof(sctimers_vars_t)); // ACLK sources from external 32kHz BCSCTL3 |= LFXT1S_0; // disable all compares TACCTL0 = 0; TACCR0 = 0; // CCR1 in compare mode (disabled for now) TACCTL1 = 0; TACCR1 = 0; // CCR2 in capture mode TACCTL2 = 0; TACCR2 = 0; // reset couter TAR = 0; } void sctimer_start() { // start counting TACTL = MC_2+TASSEL_1; // continuous mode, clocked from ACLK }
$(document).ready(function(){ var Previewer = { preview: function(content, output) { $.ajax({ type: 'POST', url: "/govspeak", data: { govspeak: content.val() }, dataType: 'json' }).success(function(data){ output.html(data['govspeak']); }); } }; $("[data-preview]").each(function(){ var source_field = $($(this).data('preview-for')); var render_area = $(this); source_field.keyup(function() { Previewer.preview(source_field, render_area); }) }); $('textarea').autosize(); });
/** * @namespace Phaser.Structs */ module.exports = { List: require('./List'), Map: require('./Map'), ProcessQueue: require('./ProcessQueue'), RTree: require('./RTree'), Set: require('./Set'), Size: require('./Size') };
#! /usr/bin/env python """Show file statistics by extension.""" import os import sys class Stats: def __init__(self): self.stats = {} def statargs(self, args): for arg in args: if os.path.isdir(arg): self.statdir(arg) elif os.path.isfile(arg): self.statfile(arg) else: sys.stderr.write("Can't find %s\n" % file) self.addstats("<???>", "unknown", 1) def statdir(self, dir): self.addstats("<dir>", "dirs", 1) try: names = os.listdir(dir) except os.error, err: sys.stderr.write("Can't list %s: %s\n" % (file, err)) self.addstats(ext, "unlistable", 1) return names.sort() for name in names: if name.startswith(". continue # Skip CVS temp files if name.endswith("~"): continue# Skip Emacs backup files full = os.path.join(dir, name) if os.path.islink(full): self.addstats("<lnk>", "links", 1) elif os.path.isdir(full): self.statdir(full) else: self.statfile(full) def statfile(self, file): head, ext = os.path.splitext(file) head, base = os.path.split(file) if ext == base: ext = "" # E.g. .cvsignore is deemed not to have an extension ext = os.path.normcase(ext) if not ext: ext = "<none>" self.addstats(ext, "files", 1) try: f = open(file, "rb") except IOError, err: sys.stderr.write("Can't open %s: %s\n" % (file, err)) self.addstats(ext, "unopenable", 1) return data = f.read() f.close() self.addstats(ext, "bytes", len(data)) if '\0' in data: self.addstats(ext, "binary", 1) return if not data: self.addstats(ext, "empty", 1) #self.addstats(ext, "chars", len(data)) lines = data.splitlines() self.addstats(ext, "lines", len(lines)) del lines words = data.split() self.addstats(ext, "words", len(words)) def addstats(self, ext, key, n): d = self.stats.setdefault(ext, {}) d[key] = d.get(key, 0) + n def report(self): exts = self.stats.keys() exts.sort() # Get the column keys columns = {} for ext in exts: columns.update(self.stats[ext]) cols = columns.keys() cols.sort() colwidth = {} colwidth["ext"] = max([len(ext) for ext in exts]) minwidth = 6 self.stats["TOTAL"] = {} for col in cols: total = 0 cw = max(minwidth, len(col)) for ext in exts: value = self.stats[ext].get(col) if value is None: w = 0 else: w = len("%d" % value) total += value cw = max(cw, w) cw = max(cw, len(str(total))) colwidth[col] = cw self.stats["TOTAL"][col] = total exts.append("TOTAL") for ext in exts: self.stats[ext]["ext"] = ext cols.insert(0, "ext") def printheader(): for col in cols: print "%*s" % (colwidth[col], col), print printheader() for ext in exts: for col in cols: value = self.stats[ext].get(col, "") print "%*s" % (colwidth[col], value), print printheader() # Another header at the bottom def main(): args = sys.argv[1:] if not args: args = [os.curdir] s = Stats() s.statargs(args) s.report() if __name__ == "__main__": main()
# Contributing ## Mailing list The main communication tool in use is the Yocto Project mailing list: * <yocto@yoctoproject.org> * <https://lists.yoctoproject.org/listinfo/yocto> Feel free to ask any kind of questions but please always prepend your email subject with `[meta-raspberrypi]` as this is the global *Yocto* mailing list and not a dedicated *meta-raspberrypi* mailing list. ## Formatting patches First and foremost, all of the contributions to the layer must be compliant with the standard openembedded patch guidelines: * <http: In summary, your commit log messages should be formatted as follows: <layer-component>: <short log/statement of what needed to be changed> (Optional pointers to external resources, such as defect tracking) The intent of your change. (Optional: if it's not clear from above, how your change resolves the issues in the first part) Signed-off-by: Your Name <yourname@youremail.com> The `<layer-component>` is the layer component name that your changes affect. It is important that you choose it correctly. A simple guide for selecting a a good component name is the following: * For changes that affect *layer recipes*, please just use the **base names** of the affected recipes, separated by commas (`,`), as the component name. For example: use `omxplayer` instead of `omxplayer_git.bb`. If you are adding new recipe(s), just use the new recipe(s) base name(s). An example for changes to multiple recipes would be `userland,vc-graphics,wayland`. * For changes that affect the *layer documentation*, please just use `docs` as the component name. * For changes that affect *other files*, i.e. under the `conf` directory, please use the full path as the component name, e.g. `conf/layer.conf`. * For changes that affect the *layer itself* and do not fall into any of the above cases, please use `meta-raspberrypi` as the component name. A full example of a suitable commit log message is below: foobar: Adjusted the foo setting in bar When using foobar on systems with less than a gigabyte of RAM common usage patterns often result in an Out-of-memory condition causing slowdowns and unexpected application termination. Low-memory systems should continue to function without running into memory-starvation conditions with minimal cost to systems with more available memory. High-memory systems will be less able to use the full extent of the system, a dynamically tunable option may be best, long-term. The foo setting in bar was decreased from X to X-50% in order to ensure we don't exhaust all system memory with foobar threads. Signed-off-by: Joe Developer <joe.developer@example.com> A common issue during patch reviewing is commit log formatting, please review the above formatting guidelines carefully before sending your patches. ## Sending patches The preferred method to contribute to this project is to send pull requests to the GitHub mirror of the layer: * <https://github.com/agherzan/meta-raspberrypi> **In addition**, you may send patches for review to the above specified mailing list. In this case, when creating patches using `git` please make sure to use the following formatting for the message subject: git format-patch -s --subject-prefix='meta-raspberrypi][PATCH' origin Then, for sending patches to the mailing list, you may use this command: git send-email --to yocto@yoctoproject.org <generated patch> ## GitHub issues In order to manage and track the layer issues more efficiently, the GitHub issues facility is used by this project: * <https://github.com/agherzan/meta-raspberrypi/issues> If you submit patches that have a GitHub issue associated, please make sure to use standard GitHub keywords, e.g. `closes`, `resolves` or `fixes`, before the "Signed-off-by" tag to close the relevant issues automatically: foobar: Adjusted the foo setting in bar Fixes: #324 Signed-off-by: Joe Developer <joe.developer@example.com> More information on the available GitHub close keywords can be found here: * <https://help.github.com/articles/<API key>>
<!doctype html> <html> <head> <title>Network | Hierarchical layout</title> <style type="text/css"> body { font: 10pt sans; } #mynetwork { width: 600px; height: 600px; border: 1px solid lightgray; } </style> <script type="text/javascript" src="../../../dist/vis.js"></script> <link href="../../../dist/vis-network.min.css" rel="stylesheet" type="text/css"/> <script type="text/javascript"> var network = null; function p(data) { var container = document.getElementById('mynetwork'); var options = { layout: { hierarchical: {}, }, }; console.log("starting layout"); network = new vis.Network(container, data, options); console.log("layout complete"); } </script> </head> <body> <h2>Hierarchical Layout</h2> <div id="mynetwork"></div> <script type="text/javascript" src="./demo.jsonp"></script> </body> </html>
<?php namespace WiderFunnel\OptimizelyX\Items; /** * Class Experiment * @package WiderFunnel\Items; */ class Experiment extends ItemAbstract { }
var jsbin = { 'root': '{{root}}', 'shareRoot': '{{shareRoot}}', 'runner': '{{runner}}', 'static': '{{static}}', 'version': '{{version}}', user: {{{user}}}, }; (function () { if (jsbin.user && jsbin.user.name) { $('.loggedout').hide(); var menu = $('.loggedin').show(); var html = $('#profile-template').text(); var $html = $(html.replace(/({.*?})/g, function (all, match) { var key = match.slice(1, -1).trim(); // ditch the wrappers return jsbin.user[key] || ''; })); if (jsbin.user.pro) { document.documentElement.className += ' pro'; $html.find('.gopro').remove(); } else { $html.find('.pro').remove(); } menu.append($html); } else { $('.loggedout').show(); } })();
.profile__login { position: relative; display: inline-block; z-index: 50; padding-bottom: .5rem; } .<API key> { width: 2.5rem; margin-bottom: -0.7rem; } .<API key> { opacity: 0; position: absolute; right: 3rem; padding: 1rem; margin-top: 1rem; border-radius: .5rem; white-space: nowrap; background: var(--color-secondary); transition: all .2s ease-in-out; } .<API key>::before { content: ""; position: absolute; top: -0.5rem; right: 0.8rem; border-left: 0.625rem solid transparent; border-right: 0.625rem solid transparent; border-bottom: 0.625rem solid var(--color-secondary); transition-duration: 0.2s; transition-property: transform; } .<API key> { font-family: var(--ff-sans); text-decoration: none; color: white; transition: color .2s ease-in-out; } .<API key>:hover { color: var(--ultra-dark); } .profile__login:hover .<API key> { opacity: 1; transform: translate(3rem); transition: all 0.5s cubic-bezier(0.75, -0.02, 0.2, 0.97); }
using System.Text; namespace GuruComponents.Netrix.Events { <summary> SaveEventArgs provides information about the current save process. </summary> public class SaveEventArgs : LoadEventArgs { <summary> Constructor. It's build by Save event handler and not intendet to being called from user's code. </summary> <param name="encoding"></param> <param name="url"></param> public SaveEventArgs(Encoding encoding, string url) : base(encoding, url) { } <summary> Set another encoding temporarily, if used within the <see cref="IHtmlEditor.Saving">Saving</see> event. </summary> <param name="encoding"></param> public void SetEncoding(Encoding encoding) { _encoding = encoding; } } }
YUI.add("yuidoc-meta", function(Y) { Y.YUIDoc = { meta: { "classes": [ "Audio" ], "modules": [ "gallery-audio" ], "allModules": [ { "displayName": "gallery-audio", "name": "gallery-audio" } ] } }; });
// angular import { HttpClient } from '@angular/common/http'; import { Routes } from '@angular/router'; // libs import * as _ from 'lodash'; import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core'; export class <API key> implements I18NRouterLoader { private _translations: any; get routes(): Routes { return _.map(this.providedSettings.routes, _.cloneDeep); } get translations(): any { return this._translations; } constructor(private readonly http: HttpClient, private readonly path: string = '/routes.json', private readonly providedSettings: I18NRouterSettings = {}) { } loadTranslations(): any { return new Promise((resolve, reject) => { this.http.get(this.path) .subscribe(res => { this._translations = res; return resolve(res); }, () => reject('Endpoint unreachable!')); }); } }
'use strict'; var fs = require('fs'), util = require('util'), Duplexify = require('duplexify'), _ = require('lodash'), su = require('bindings')('serialutil.node'), fsu = require('./fsutil'), pins = require('./pins'), Dto = require('./dto'), dto = new Dto(__dirname + '/../templates/uart.dts'); var DEFAULT_OPTIONS; function onopen(uart, options) { if (uart._rxfd !== -1 && uart._txfd !== -1) { su.setRawMode(uart._rxfd); uart.baudRate(options.baudRate); uart.characterSize(options.characterSize); uart.parity(options.parity); uart.stopBits(options.stopBits); setImmediate(function () { uart.emit('open'); uart.emit('ready'); }); } } function onclose(uart) { if (uart._rxfd === -1 && uart._txfd === -1) { setImmediate(function () { uart.emit('close'); }); } } function createStreams(uart, options) { uart._rxfd = -1; uart._txfd = -1; uart._rxstream = fs.createReadStream(uart.devPath, { highWaterMark: options.highWaterMark, encoding: options.encoding }); uart._txstream = fs.createWriteStream(uart.devPath, { highWaterMark: options.highWaterMark, encoding: options.encoding, flags: 'r+' }); uart._rxstream.once('open', function (rxfd) { uart._rxfd = rxfd; onopen(uart, options); }); uart._txstream.once('open', function (txfd) { uart._txfd = txfd; onopen(uart, options); }); uart._rxstream.once('close', function () { uart._rxfd = -1; onclose(uart); }); uart._txstream.once('close', function () { uart._txfd = -1; onclose(uart); }); // TODO - test error handling uart.setReadable(uart._rxstream); uart.setWritable(uart._txstream); } function waitForUart(uart, options) { fsu.waitForFile(uart.devPath, function (err, devPath) { if (err) { return uart.emit('error', err); } createStreams(uart, options); }); } function Uart(uartDef, options) { var badPin, config; if (!(this instanceof Uart)) { return new Uart(uartDef); } options = options ? _.defaults(options, DEFAULT_OPTIONS) : DEFAULT_OPTIONS; // Consider calling Duplexify with the allowHalfOpen option set to false. // It's super-class (Duplex) will then ensure that this.end is called when // the read stream fires the 'end' event. (see: Duplexify.call(this, null, null); if (typeof uartDef === 'string') { this.uartDef = null; this.devPath = uartDef; this.name = null; waitForUart(this, options); } else { if (uartDef.txPin.uart === undefined) { badPin = new Error(uartDef.txPin + ' doesn\'t support uarts'); } else if (uartDef.rxPin.uart === undefined) { badPin = new Error(uartDef.rxPin + ' doesn\'t support uarts'); } if (badPin) { setImmediate(function () { this.emit('error', badPin); }.bind(this)); return; } this.uartDef = uartDef; this.devPath = '/dev/ttyO' + uartDef.id; this.name = 'bot_uart' + uartDef.id; config = { txHeader: this.uartDef.txPin.name.toUpperCase().replace('_', '.'), rxHeader: this.uartDef.rxPin.name.toUpperCase().replace('_', '.'), hardwareIp: 'uart' + this.uartDef.id, name: this.name, rxMuxOffset: '0x' + this.uartDef.rxPin.muxOffset.toString(16), rxMuxValue: '0x' + this.uartDef.rxPin.uart.muxValue.toString(16), txMuxOffset: '0x' + this.uartDef.txPin.muxOffset.toString(16), txMuxValue: '0x' + this.uartDef.txPin.uart.muxValue.toString(16), targetUart: 'uart' + (this.uartDef.id + 1), partNumber: this.name }; dto.install(config, function (err) { if (err) { return this.emit('error', err); } waitForUart(this, options); }.bind(this)); } } module.exports = Uart; util.inherits(Uart, Duplexify); Uart.B0 = su.B0; Uart.B50 = su.B50; Uart.B75 = su.B75; Uart.B110 = su.B110; Uart.B134 = su.B134; Uart.B150 = su.B150; Uart.B200 = su.B200; Uart.B300 = su.B300; Uart.B600 = su.B600; Uart.B1200 = su.B1200; Uart.B1800 = su.B1800; Uart.B2400 = su.B2400; Uart.B4800 = su.B4800; Uart.B9600 = su.B9600; Uart.B19200 = su.B19200; Uart.B38400 = su.B38400; Uart.B57600 = su.B57600; Uart.B115200 = su.B115200; Uart.B230400 = su.B230400; Uart.B460800 = su.B460800; Uart.B500000 = su.B500000; Uart.B576000 = su.B576000; Uart.B921600 = su.B921600; Uart.B1000000 = su.B1000000; Uart.B1152000 = su.B1152000; Uart.B1500000 = su.B1500000; Uart.B2000000 = su.B2000000; Uart.B2500000 = su.B2500000; Uart.B3000000 = su.B3000000; Uart.B3500000 = su.B3500000; Uart.B4000000 = su.B4000000; Uart.PARITY_NONE = su.PARITY_NONE; Uart.PARITY_ODD = su.PARITY_ODD; Uart.PARITY_EVEN = su.PARITY_EVEN; Uart.UART1 = { id: 1, txPin: pins.p9_24, rxPin: pins.p9_26 }; Uart.UART2 = { id: 2, txPin: pins.p9_21, rxPin: pins.p9_22 }; Uart.UART4 = { id: 4, txPin: pins.p9_13, rxPin: pins.p9_11 }; DEFAULT_OPTIONS = { baudRate: Uart.B38400, characterSize: 8, parity: Uart.PARITY_NONE, stopBits: 1, highWaterMark: 512, encoding: null }; Object.freeze(DEFAULT_OPTIONS); Uart.prototype.baudRate = function (rate) { if (rate === undefined) { return su.getBaudRate(this._rxfd); } su.setBaudRate(this._rxfd, rate); }; Uart.prototype.characterSize = function (size) { if (size === undefined) { return su.getCharacterSize(this._rxfd); } su.setCharacterSize(this._rxfd, size); }; Uart.prototype.parity = function (type) { if (type === undefined) { return su.getParity(this._rxfd); } su.setParity(this._rxfd, type); }; Uart.prototype.stopBits = function (count) { if (count === undefined) { return su.getStopBits(this._rxfd); } su.setStopBits(this._rxfd, count); }; Uart.prototype.close = function () { this.removeAllListeners('data'); // Is this a good idea? Should the user be doing this? // TODO: the following is a bit of a hack. // Here \n EOF is faked for this._rxfd inorder to close the read stream. // It's faked three times as the uart may receive a character between // \n and EOF and the stream will not be closed. Faking three times // increases the chances of it working! su.setCanonical(this._rxfd, true); su.fakeInput(this._rxfd, '\n'.charCodeAt(0)); su.fakeInput(this._rxfd, 4); // fake eof su.fakeInput(this._rxfd, '\n'.charCodeAt(0)); su.fakeInput(this._rxfd, 4); // fake eof su.fakeInput(this._rxfd, '\n'.charCodeAt(0)); su.fakeInput(this._rxfd, 4); // fake eof };
package de.andreasgiemza.mangadownloader.gui.chapter; import de.andreasgiemza.mangadownloader.MangaDownloader; import de.andreasgiemza.mangadownloader.helpers.RegexHelper; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.TableRowSorter; /** * * @author Andreas Giemza <andreas@giemza.net> */ public class <API key> implements DocumentListener { private final MangaDownloader mangaDownloader; private final JTextField <API key>; private final TableRowSorter<ChapterTableModel> <API key>; @SuppressWarnings("unchecked") public <API key>(MangaDownloader mangaDownloader, JTextField <API key>, JTable chapterListTable) { this.mangaDownloader = mangaDownloader; this.<API key> = <API key>; <API key> = (TableRowSorter<ChapterTableModel>) chapterListTable .getRowSorter(); } @Override public void insertUpdate(DocumentEvent e) { changed(); } @Override public void removeUpdate(DocumentEvent e) { changed(); } @Override public void changedUpdate(DocumentEvent e) { changed(); } private void changed() { mangaDownloader.<API key>(); final String searchText = <API key>.getText(); if (searchText.length() == 0) { <API key>.setRowFilter(null); } else if (searchText.length() > 0) { <API key>.setRowFilter(RowFilter .regexFilter(RegexHelper.build(searchText))); } } }
package nxt.http; import nxt.Account; import nxt.Attachment; import nxt.Constants; import nxt.NxtException; import nxt.util.Convert; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; import static nxt.http.JSONResponses.INCORRECT_ASSET; import static nxt.http.JSONResponses.INCORRECT_PRICE; import static nxt.http.JSONResponses.INCORRECT_QUANTITY; import static nxt.http.JSONResponses.MISSING_ASSET; import static nxt.http.JSONResponses.MISSING_PRICE; import static nxt.http.JSONResponses.MISSING_QUANTITY; import static nxt.http.JSONResponses.NOT_ENOUGH_ASSETS; import static nxt.http.JSONResponses.UNKNOWN_ACCOUNT; public final class PlaceAskOrder extends CreateTransaction { static final PlaceAskOrder instance = new PlaceAskOrder(); private PlaceAskOrder() { super("asset", "quantity", "price"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException { String assetValue = req.getParameter("asset"); String quantityValue = req.getParameter("quantity"); String priceValue = req.getParameter("price"); if (assetValue == null) { return MISSING_ASSET; } else if (quantityValue == null) { return MISSING_QUANTITY; } else if (priceValue == null) { return MISSING_PRICE; } long price; try { price = Long.parseLong(priceValue); if (price <= 0 || price > Constants.MAX_BALANCE * 100L) { return INCORRECT_PRICE; } } catch (<API key> e) { return INCORRECT_PRICE; } Long asset; try { asset = Convert.parseUnsignedLong(assetValue); } catch (RuntimeException e) { return INCORRECT_ASSET; } int quantity; try { quantity = Integer.parseInt(quantityValue); if (quantity <= 0 || quantity > Constants.MAX_ASSET_QUANTITY) { return INCORRECT_QUANTITY; } } catch (<API key> e) { return INCORRECT_QUANTITY; } Account account = getAccount(req); if (account == null) { return UNKNOWN_ACCOUNT; } Integer assetBalance = account.<API key>(asset); if (assetBalance == null || quantity > assetBalance) { return NOT_ENOUGH_ASSETS; } Attachment attachment = new Attachment.<API key>(asset, quantity, price); return createTransaction(req, account, attachment); } }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = <API key>(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = <API key>(_reactIconBase); function <API key>(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FaHouzz = function FaHouzz(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm19.9 26.6l11.5-6.6v13.2l-11.5 6.6v-13.2z m-11.4-6.6v13.2l11.4-6.6z m11.4-19.8v13.2l-11.4 6.6v-13.2z m0 13.2l11.5-6.6v13.2z' }) ) ); }; exports.default = FaHouzz; module.exports = exports['default'];
// The LLVM Compiler Infrastructure // This file is distributed under the University of Illinois Open Source // This file implements the JumpScopeChecker class, which is used to diagnose // jumps that enter a protected scope in an invalid way. #include "clang/Sema/SemaInternal.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "llvm/ADT/BitVector.h" using namespace clang; namespace { JumpScopeChecker - This object is used by Sema to diagnose invalid jumps into VLA and other protected scopes. For example, this rejects: goto L; int a[n]; L: class JumpScopeChecker { Sema &S; Permissive - True when recovering from errors, in which case precautions are taken to handle incomplete scope information. const bool Permissive; GotoScope - This is a record that we use to keep track of all of the scopes that are introduced by VLAs and other things that scope jumps like gotos. This scope tree has nothing to do with the source scope tree, because you can have multiple VLA scopes per compound statement, and most compound statements don't introduce any scopes. struct GotoScope { ParentScope - The index in ScopeMap of the parent scope. This is 0 for the parent scope is the function body. unsigned ParentScope; InDiag - The note to emit if there is a jump into this scope. unsigned InDiag; OutDiag - The note to emit if there is an indirect jump out of this scope. Direct jumps always clean up their current scope in an orderly way. unsigned OutDiag; Loc - Location to emit the diagnostic. SourceLocation Loc; GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag, SourceLocation L) : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {} }; SmallVector<GotoScope, 48> Scopes; llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes; SmallVector<Stmt*, 16> Jumps; SmallVector<IndirectGotoStmt*, 4> IndirectJumps; SmallVector<LabelDecl*, 4> IndirectJumpTargets; public: JumpScopeChecker(Stmt *Body, Sema &S); private: void <API key>(Decl *D, unsigned &ParentScope); void <API key>(VarDecl *D, const BlockDecl *BDecl, unsigned &ParentScope); void <API key>(Stmt *S, unsigned &origParentScope); void VerifyJumps(); void VerifyIndirectJumps(); void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes); void <API key>(IndirectGotoStmt *IG, unsigned IGScope, LabelDecl *Target, unsigned TargetScope); void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, unsigned JumpDiag, unsigned JumpDiagWarning, unsigned JumpDiagCXX98Compat); void CheckGotoStmt(GotoStmt *GS); unsigned <API key>(unsigned A, unsigned B); }; } // end anonymous namespace #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x))) JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s), Permissive(s.<API key>()) { // Add a scope entry for function scope. Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation())); // Build information for the top level compound statement, so that we have a // defined scope record for every "goto" and label. unsigned BodyParentScope = 0; <API key>(Body, BodyParentScope); // Check that all jumps we saw are kosher. VerifyJumps(); VerifyIndirectJumps(); } <API key> - Finds the innermost scope enclosing the two scopes. unsigned JumpScopeChecker::<API key>(unsigned A, unsigned B) { while (A != B) { // Inner scopes are created after outer scopes and therefore have // higher indices. if (A < B) { assert(Scopes[B].ParentScope < B); B = Scopes[B].ParentScope; } else { assert(Scopes[A].ParentScope < A); A = Scopes[A].ParentScope; } } return A; } typedef std::pair<unsigned,unsigned> ScopePair; <API key> - If this decl induces a new goto scope, return a diagnostic that should be emitted if control goes over it. If not, return 0. static ScopePair <API key>(Sema &S, const Decl *D) { if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { unsigned InDiag = 0; unsigned OutDiag = 0; if (VD->getType()-><API key>()) InDiag = diag::<API key>; if (VD->hasAttr<BlocksAttr>()) return ScopePair(diag::<API key>, diag::note_exits___block); if (VD->hasAttr<CleanupAttr>()) return ScopePair(diag::<API key>, diag::note_exits_cleanup); if (VD->hasLocalStorage()) { switch (VD->getType().isDestructedType()) { case QualType::<API key>: return ScopePair(diag::<API key>, diag::<API key>); case QualType::<API key>: return ScopePair(diag::<API key>, diag::<API key>); case QualType::DK_cxx_destructor: OutDiag = diag::note_exits_dtor; break; case QualType::DK_none: break; } } const Expr *Init = VD->getInit(); if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) { // C++11 [stmt.dcl]p3: // A program that jumps from a point where a variable with automatic // storage duration is not in scope to a point where it is in scope // is ill-formed unless the variable has scalar type, class type with // a trivial default constructor and a trivial destructor, a // cv-qualified version of one of these types, or an array of one of // the preceding types and is declared without an initializer. // C++03 [stmt.dcl.p3: // A program that jumps from a point where a local variable // with automatic storage duration is not in scope to a point // where it is in scope is ill-formed unless the variable has // POD type and is declared without an initializer. InDiag = diag::<API key>; // For a variable of (array of) class type declared without an // initializer, we will have call-style initialization and the initializer // will be the CXXConstructExpr with no intervening nodes. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { const CXXConstructorDecl *Ctor = CCE->getConstructor(); if (Ctor->isTrivial() && Ctor-><API key>() && VD->getInitStyle() == VarDecl::CallInit) { if (OutDiag) InDiag = diag::<API key>; else if (!Ctor->getParent()->isPOD()) InDiag = diag::<API key>; else InDiag = 0; } } } return ScopePair(InDiag, OutDiag); } if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { if (TD->getUnderlyingType()-><API key>()) return ScopePair(isa<TypedefDecl>(TD) ? diag::<API key> : diag::<API key>, 0); } return ScopePair(0U, 0U); } \brief Build scope information for a declaration that is part of a DeclStmt. void JumpScopeChecker::<API key>(Decl *D, unsigned &ParentScope) { // If this decl causes a new scope, push and switch to it. std::pair<unsigned,unsigned> Diags = <API key>(S, D); if (Diags.first || Diags.second) { Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second, D->getLocation())); ParentScope = Scopes.size()-1; } // If the decl has an initializer, walk it with the potentially new // scope we just installed. if (VarDecl *VD = dyn_cast<VarDecl>(D)) if (Expr *Init = VD->getInit()) <API key>(Init, ParentScope); } \brief Build scope information for a captured block literal variables. void JumpScopeChecker::<API key>(VarDecl *D, const BlockDecl *BDecl, unsigned &ParentScope) { // exclude captured __block variables; there's no destructor // associated with the block literal for them. if (D->hasAttr<BlocksAttr>()) return; QualType T = D->getType(); QualType::DestructionKind destructKind = T.isDestructedType(); if (destructKind != QualType::DK_none) { std::pair<unsigned,unsigned> Diags; switch (destructKind) { case QualType::DK_cxx_destructor: Diags = ScopePair(diag::<API key>, diag::<API key>); break; case QualType::<API key>: Diags = ScopePair(diag::<API key>, diag::<API key>); break; case QualType::<API key>: Diags = ScopePair(diag::<API key>, diag::<API key>); break; case QualType::DK_none: llvm_unreachable("non-lifetime captured variable"); } SourceLocation Loc = D->getLocation(); if (Loc.isInvalid()) Loc = BDecl->getLocation(); Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second, Loc)); ParentScope = Scopes.size()-1; } } <API key> - The statements from CI to CE are known to form a coherent VLA scope with a specified parent node. Walk through the statements, adding any labels or gotos to LabelAndGotoScopes and recursively walking the AST as needed. void JumpScopeChecker::<API key>(Stmt *S, unsigned &origParentScope) { // If this is a statement, rather than an expression, scopes within it don't // propagate out into the enclosing scope. Otherwise we have to worry // about block literals, which have the lifetime of their enclosing statement. unsigned <API key> = origParentScope; unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S)) ? origParentScope : <API key>); unsigned StmtsToSkip = 0u; // If we found a label, remember that it is in ParentScope scope. switch (S->getStmtClass()) { case Stmt::AddrLabelExprClass: IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel()); break; case Stmt::<API key>: // "goto *&&lbl;" is a special case which we treat as equivalent // to a normal goto. In addition, we don't calculate scope in the // operand (to avoid recording the address-of-label use), which // works only because of the restricted set of expressions which // we detect as constant targets. if (cast<IndirectGotoStmt>(S)->getConstantTarget()) { LabelAndGotoScopes[S] = ParentScope; Jumps.push_back(S); return; } LabelAndGotoScopes[S] = ParentScope; IndirectJumps.push_back(cast<IndirectGotoStmt>(S)); break; case Stmt::SwitchStmtClass: // Evaluate the C++17 init stmt and condition variable // before entering the scope of the switch statement. if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) { <API key>(Init, ParentScope); ++StmtsToSkip; } if (VarDecl *Var = cast<SwitchStmt>(S)-><API key>()) { <API key>(Var, ParentScope); ++StmtsToSkip; } // Fall through case Stmt::GotoStmtClass: // Remember both what scope a goto is in as well as the fact that we have // it. This makes the second scan not have to walk the AST again. LabelAndGotoScopes[S] = ParentScope; Jumps.push_back(S); break; case Stmt::IfStmtClass: { IfStmt *IS = cast<IfStmt>(S); if (!(IS->isConstexpr() || IS-><API key>())) break; unsigned Diag = IS->isConstexpr() ? diag::<API key> : diag::<API key>; if (VarDecl *Var = IS-><API key>()) <API key>(Var, ParentScope); // Cannot jump into the middle of the condition. unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart())); <API key>(IS->getCond(), NewParentScope); // Jumps into either arm of an 'if constexpr' are not allowed. NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart())); <API key>(IS->getThen(), NewParentScope); if (Stmt *Else = IS->getElse()) { NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart())); <API key>(Else, NewParentScope); } return; } case Stmt::CXXTryStmtClass: { CXXTryStmt *TS = cast<CXXTryStmt>(S); { unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::note_exits_cxx_try, TS->getSourceRange().getBegin())); if (Stmt *TryBlock = TS->getTryBlock()) <API key>(TryBlock, NewParentScope); } // Jump from the catch into the try is not allowed either. for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) { CXXCatchStmt *CS = TS->getHandler(I); unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, CS->getSourceRange().getBegin())); <API key>(CS->getHandlerBlock(), NewParentScope); } return; } case Stmt::SEHTryStmtClass: { SEHTryStmt *TS = cast<SEHTryStmt>(S); { unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::note_exits_seh_try, TS->getSourceRange().getBegin())); if (Stmt *TryBlock = TS->getTryBlock()) <API key>(TryBlock, NewParentScope); } // Jump from __except or __finally into the __try are not allowed either. if (SEHExceptStmt *Except = TS->getExceptHandler()) { unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, Except->getSourceRange().getBegin())); <API key>(Except->getBlock(), NewParentScope); } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) { unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, Finally->getSourceRange().getBegin())); <API key>(Finally->getBlock(), NewParentScope); } return; } case Stmt::DeclStmtClass: { // If this is a declstmt with a VLA definition, it defines a scope from here // to the end of the containing context. DeclStmt *DS = cast<DeclStmt>(S); // The decl statement creates a scope if any of the decls in it are VLAs // or have the cleanup attribute. for (auto *I : DS->decls()) <API key>(I, origParentScope); return; } case Stmt::ObjCAtTryStmtClass: { // Disallow jumps into any part of an @try statement by pushing a scope and // walking all sub-stmts in that scope. ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S); // Recursively walk the AST for the @try part. { unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::note_exits_objc_try, AT->getAtTryLoc())); if (Stmt *TryPart = AT->getTryBody()) <API key>(TryPart, NewParentScope); } // Jump from the catch to the finally or try is not valid. for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) { ObjCAtCatchStmt *AC = AT->getCatchStmt(I); unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, AC->getAtCatchLoc())); // @catches are nested and it isn't <API key>(AC->getCatchBody(), NewParentScope); } // Jump from the finally to the try or catch is not valid. if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) { unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, AF->getAtFinallyLoc())); <API key>(AF, NewParentScope); } return; } case Stmt::<API key>: { // Disallow jumps into the protected statement of an @synchronized, but // allow jumps into the object expression it protects. <API key> *AS = cast<<API key>>(S); // Recursively walk the AST for the @synchronized object expr, it is // evaluated in the normal scope. <API key>(AS->getSynchExpr(), ParentScope); // Recursively walk the AST for the @synchronized part, protected by a new // scope. unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, AS-><API key>())); <API key>(AS->getSynchBody(), NewParentScope); return; } case Stmt::<API key>: { // Disallow jumps into the protected statement of an @autoreleasepool. <API key> *AS = cast<<API key>>(S); // Recursively walk the AST for the @autoreleasepool part, protected by a // new scope. unsigned NewParentScope = Scopes.size(); Scopes.push_back(GotoScope(ParentScope, diag::<API key>, diag::<API key>, AS->getAtLoc())); <API key>(AS->getSubStmt(), NewParentScope); return; } case Stmt::<API key>: { // Disallow jumps past full-expressions that use blocks with // non-trivial cleanups of their captures. This is theoretically // implementable but a lot of work which we haven't felt up to doing. ExprWithCleanups *EWC = cast<ExprWithCleanups>(S); for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) { const BlockDecl *BDecl = EWC->getObject(i); for (const auto &CI : BDecl->captures()) { VarDecl *variable = CI.getVariable(); <API key>(variable, BDecl, origParentScope); } } break; } case Stmt::<API key>: { // Disallow jumps out of scopes containing temporaries lifetime-extended to // automatic storage duration. <API key> *MTE = cast<<API key>>(S); if (MTE->getStorageDuration() == SD_Automatic) { SmallVector<const Expr *, 4> CommaLHS; SmallVector<SubobjectAdjustment, 4> Adjustments; const Expr *ExtendedObject = MTE->GetTemporaryExpr()-><API key>( CommaLHS, Adjustments); if (ExtendedObject->getType().isDestructedType()) { Scopes.push_back(GotoScope(ParentScope, 0, diag::<API key>, ExtendedObject->getExprLoc())); origParentScope = Scopes.size()-1; } } break; } case Stmt::CaseStmtClass: case Stmt::DefaultStmtClass: case Stmt::LabelStmtClass: LabelAndGotoScopes[S] = ParentScope; break; default: break; } for (Stmt *SubStmt : S->children()) { if (!SubStmt) continue; if (StmtsToSkip) { --StmtsToSkip; continue; } // Cases, labels, and defaults aren't "scope parents". It's also // important to handle these iteratively instead of recursively in // order to avoid blowing out the stack. while (true) { Stmt *Next; if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt)) Next = SC->getSubStmt(); else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt)) Next = LS->getSubStmt(); else break; LabelAndGotoScopes[SubStmt] = ParentScope; SubStmt = Next; } // Recursively walk the AST. <API key>(SubStmt, ParentScope); } } VerifyJumps - Verify each element of the Jumps array to see if they are valid, emitting diagnostics if not. void JumpScopeChecker::VerifyJumps() { while (!Jumps.empty()) { Stmt *Jump = Jumps.pop_back_val(); // With a goto, if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) { // The label may not have a statement if it's coming from inline MS ASM. if (GS->getLabel()->getStmt()) { CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(), diag::<API key>, diag::<API key>, diag::<API key>); } CheckGotoStmt(GS); continue; } // We only get indirect gotos here when they have a constant target. if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) { LabelDecl *Target = IGS->getConstantTarget(); CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(), diag::<API key>, diag::<API key>, diag::<API key>); continue; } SwitchStmt *SS = cast<SwitchStmt>(Jump); for (SwitchCase *SC = SS->getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC))) continue; SourceLocation Loc; if (CaseStmt *CS = dyn_cast<CaseStmt>(SC)) Loc = CS->getLocStart(); else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) Loc = DS->getLocStart(); else Loc = SC->getLocStart(); CheckJump(SS, SC, Loc, diag::<API key>, 0, diag::<API key>); } } } VerifyIndirectJumps - Verify whether any possible indirect jump might cross a protection boundary. Unlike direct jumps, indirect jumps count cleanups as protection boundaries: since there's no way to know where the jump is going, we can't implicitly run the right cleanups the way we can with direct jumps. Thus, an indirect jump is "trivial" if it bypasses no initializations and no teardowns. More formally, an indirect jump from A to B is trivial if the path out from A to DCA(A,B) is trivial and the path in from DCA(A,B) to B is trivial, where DCA(A,B) is the deepest common ancestor of A and B. Jump-triviality is transitive but asymmetric. A path in is trivial if none of the entered scopes have an InDiag. A path out is trivial is none of the exited scopes have an OutDiag. Under these definitions, this function checks that the indirect jump between A and B is trivial for every indirect goto statement A and every label B whose address was taken in the function. void JumpScopeChecker::VerifyIndirectJumps() { if (IndirectJumps.empty()) return; // If there aren't any address-of-label expressions in this function, // complain about the first indirect goto. if (IndirectJumpTargets.empty()) { S.Diag(IndirectJumps[0]->getGotoLoc(), diag::<API key>); return; } // Collect a single representative of every scope containing an // indirect goto. For most code bases, this substantially cuts // down on the number of jump sites we'll have to consider later. typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope; SmallVector<JumpScope, 32> JumpScopes; { llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap; for (SmallVectorImpl<IndirectGotoStmt*>::iterator I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) { IndirectGotoStmt *IG = *I; if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG))) continue; unsigned IGScope = LabelAndGotoScopes[IG]; IndirectGotoStmt *&Entry = JumpScopesMap[IGScope]; if (!Entry) Entry = IG; } JumpScopes.reserve(JumpScopesMap.size()); for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I) JumpScopes.push_back(*I); } // Collect a single representative of every scope containing a // label whose address was taken somewhere in the function. // For most code bases, there will be only one such scope. llvm::DenseMap<unsigned, LabelDecl*> TargetScopes; for (SmallVectorImpl<LabelDecl*>::iterator I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end(); I != E; ++I) { LabelDecl *TheLabel = *I; if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt()))) continue; unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()]; LabelDecl *&Target = TargetScopes[LabelScope]; if (!Target) Target = TheLabel; } // For each target scope, make sure it's trivially reachable from // every scope containing a jump site. // A path between scopes always consists of exitting zero or more // scopes, then entering zero or more scopes. We build a set of // of scopes S from which the target scope can be trivially // entered, then verify that every jump scope can be trivially // exitted to reach a scope in S. llvm::BitVector Reachable(Scopes.size(), false); for (llvm::DenseMap<unsigned,LabelDecl*>::iterator TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) { unsigned TargetScope = TI->first; LabelDecl *TargetLabel = TI->second; Reachable.reset(); // Mark all the enclosing scopes from which you can safely jump // into the target scope. 'Min' will end up being the index of // the shallowest such scope. unsigned Min = TargetScope; while (true) { Reachable.set(Min); // Don't go beyond the outermost scope. if (Min == 0) break; // Stop if we can't trivially enter the current scope. if (Scopes[Min].InDiag) break; Min = Scopes[Min].ParentScope; } // Walk through all the jump sites, checking that they can trivially // reach this label scope. for (SmallVectorImpl<JumpScope>::iterator I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) { unsigned Scope = I->first; // Walk out the "scope chain" for this scope, looking for a scope // we've marked reachable. For well-formed code this amortizes // to O(JumpScopes.size() / Scopes.size()): we only iterate // when we see something unmarked, and in well-formed code we // mark everything we iterate past. bool IsReachable = false; while (true) { if (Reachable.test(Scope)) { // If we find something reachable, mark all the scopes we just // walked through as reachable. for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope) Reachable.set(S); IsReachable = true; break; } // Don't walk out if we've reached the top-level scope or we've // gotten shallower than the shallowest reachable scope. if (Scope == 0 || Scope < Min) break; // Don't walk out through an out-diagnostic. if (Scopes[Scope].OutDiag) break; Scope = Scopes[Scope].ParentScope; } // Only diagnose if we didn't find something. if (IsReachable) continue; <API key>(I->second, I->first, TargetLabel, TargetScope); } } } Return true if a particular error+note combination must be downgraded to a warning in Microsoft mode. static bool <API key>(unsigned JumpDiag, unsigned InDiagNote) { return (JumpDiag == diag::<API key> && (InDiagNote == diag::<API key> || InDiagNote == diag::<API key>)); } Return true if a particular note should be downgraded to a compatibility warning in C++11 mode. static bool <API key>(Sema &S, unsigned InDiagNote) { return S.getLangOpts().CPlusPlus11 && InDiagNote == diag::<API key>; } Produce primary diagnostic for an indirect jump statement. static void <API key>(Sema &S, IndirectGotoStmt *Jump, LabelDecl *Target, bool &Diagnosed) { if (Diagnosed) return; S.Diag(Jump->getGotoLoc(), diag::<API key>); S.Diag(Target->getStmt()->getIdentLoc(), diag::<API key>); Diagnosed = true; } Produce note diagnostics for a jump into a protected scope. void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) { if (CHECK_PERMISSIVE(ToScopes.empty())) return; for (unsigned I = 0, E = ToScopes.size(); I != E; ++I) if (Scopes[ToScopes[I]].InDiag) S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag); } Diagnose an indirect jump which is known to cross scopes. void JumpScopeChecker::<API key>(IndirectGotoStmt *Jump, unsigned JumpScope, LabelDecl *Target, unsigned TargetScope) { if (CHECK_PERMISSIVE(JumpScope == TargetScope)) return; unsigned Common = <API key>(JumpScope, TargetScope); bool Diagnosed = false; // Walk out the scope chain until we reach the common ancestor. for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope) if (Scopes[I].OutDiag) { <API key>(S, Jump, Target, Diagnosed); S.Diag(Scopes[I].Loc, Scopes[I].OutDiag); } SmallVector<unsigned, 10> ToScopesCXX98Compat; // Now walk into the scopes containing the label whose address was taken. for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope) if (<API key>(S, Scopes[I].InDiag)) ToScopesCXX98Compat.push_back(I); else if (Scopes[I].InDiag) { <API key>(S, Jump, Target, Diagnosed); S.Diag(Scopes[I].Loc, Scopes[I].InDiag); } // Diagnose this jump if it would be ill-formed in C++98. if (!Diagnosed && !ToScopesCXX98Compat.empty()) { S.Diag(Jump->getGotoLoc(), diag::<API key>); S.Diag(Target->getStmt()->getIdentLoc(), diag::<API key>); NoteJumpIntoScopes(ToScopesCXX98Compat); } } CheckJump - Validate that the specified jump statement is valid: that it is jumping within or out of its current scope, not into a deeper one. void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc, unsigned JumpDiagError, unsigned JumpDiagWarning, unsigned JumpDiagCXX98Compat) { if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From))) return; if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To))) return; unsigned FromScope = LabelAndGotoScopes[From]; unsigned ToScope = LabelAndGotoScopes[To]; // Common case: exactly the same scope, which is fine. if (FromScope == ToScope) return; // Warn on gotos out of __finally blocks. if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) { // If FromScope > ToScope, FromScope is more nested and the jump goes to a // less nested scope. Check if it crosses a __finally along the way. for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) { if (Scopes[I].InDiag == diag::<API key>) { S.Diag(From->getLocStart(), diag::<API key>); break; } } } unsigned CommonScope = <API key>(FromScope, ToScope); // It's okay to jump out from a nested scope. if (CommonScope == ToScope) return; // Pull out (and reverse) any scopes we might need to diagnose skipping. SmallVector<unsigned, 10> ToScopesCXX98Compat; SmallVector<unsigned, 10> ToScopesError; SmallVector<unsigned, 10> ToScopesWarning; for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) { if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 && <API key>(JumpDiagError, Scopes[I].InDiag)) ToScopesWarning.push_back(I); else if (<API key>(S, Scopes[I].InDiag)) ToScopesCXX98Compat.push_back(I); else if (Scopes[I].InDiag) ToScopesError.push_back(I); } // Handle warnings. if (!ToScopesWarning.empty()) { S.Diag(DiagLoc, JumpDiagWarning); NoteJumpIntoScopes(ToScopesWarning); } // Handle errors. if (!ToScopesError.empty()) { S.Diag(DiagLoc, JumpDiagError); NoteJumpIntoScopes(ToScopesError); } // Handle -Wc++98-compat warnings if the jump is well-formed. if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) { S.Diag(DiagLoc, JumpDiagCXX98Compat); NoteJumpIntoScopes(ToScopesCXX98Compat); } } void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) { if (GS->getLabel()->isMSAsmLabel()) { S.Diag(GS->getGotoLoc(), diag::<API key>) << GS->getLabel()->getIdentifier(); S.Diag(GS->getLabel()->getLocation(), diag::<API key>) << GS->getLabel()->getIdentifier(); } } void Sema::<API key>(Stmt *Body) { (void)JumpScopeChecker(Body, *this); }
// <API key>: Apache-2.0 #pragma once #include "trianglei.h" #include "<API key>.h" #include "<API key>.h" namespace embree { namespace isa { /*! Intersects M triangles with 1 ray */ template<int M, int Mx, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx> Precalculations; static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri) { return <API key><Primitive>::pointQuery(query, context, tri); } }; /*! Intersects M triangles with K rays */ template<int M, int Mx, int K, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx,K> Precalculations; static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const Primitive& tri) { const Scene* scene = context->scene; for (size_t i=0; i<Primitive::max_size(); i++) { if (!tri.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),RayHitK<K>::size()); const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene); const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene); const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene); pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i)); } } static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri) { vbool<K> valid0 = valid_i; const Scene* scene = context->scene; for (size_t i=0; i<Primitive::max_size(); i++) { if (!tri.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid_i),RayHitK<K>::size()); const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene); const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene); const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene); pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i)); if (none(valid0)) break; } return !valid0; } static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } }; /*! Intersects M triangles with 1 ray */ template<int M, int Mx, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx> Precalculations; static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri) { return <API key><Primitive>::pointQuery(query, context, tri); } }; /*! Intersects M triangles with K rays */ template<int M, int Mx, int K, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx,K> Precalculations; static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const Primitive& tri) { const Scene* scene = context->scene; for (size_t i=0; i<Primitive::max_size(); i++) { if (!tri.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),RayHitK<K>::size()); const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene); const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene); const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene); pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i)); } } static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri) { vbool<K> valid0 = valid_i; const Scene* scene = context->scene; for (size_t i=0; i<Primitive::max_size(); i++) { if (!tri.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid_i),RayHitK<K>::size()); const Vec3vf<K> v0 = tri.template getVertex<0>(i,scene); const Vec3vf<K> v1 = tri.template getVertex<1>(i,scene); const Vec3vf<K> v2 = tri.template getVertex<2>(i,scene); pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i)); if (none(valid0)) break; } return !valid0; } static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0, v1, v2; tri.gather(v0,v1,v2,context->scene); return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } }; /*! Intersects M motion blur triangles with 1 ray */ template<int M, int Mx, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx> Precalculations; /*! Intersect a ray with the M triangles and updates the hit. */ static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()); pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } /*! Test if the ray is occluded by one of M triangles. */ static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()); return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri) { return <API key><Primitive>::pointQuery(query, context, tri); } }; /*! Intersects M motion blur triangles with K rays. */ template<int M, int Mx, int K, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx,K> Precalculations; /*! Intersects K rays with M triangles. */ static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri) { for (size_t i=0; i<TriangleMi<M>::max_size(); i++) { if (!tri.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),K); Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time()); pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i)); } } /*! Test for K rays if they are occluded by any of the M triangles. */ static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri) { vbool<K> valid0 = valid_i; for (size_t i=0; i<TriangleMi<M>::max_size(); i++) { if (!tri.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid0),K); Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time()); pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i)); if (none(valid0)) break; } return !valid0; } /*! Intersect a ray with M triangles and updates the hit. */ static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]); pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } /*! Test if the ray is occluded by one of the M triangles. */ static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]); return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } }; /*! Intersects M motion blur triangles with 1 ray */ template<int M, int Mx, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx> Precalculations; /*! Intersect a ray with the M triangles and updates the hit. */ static __forceinline void intersect(const Precalculations& pre, RayHit& ray, IntersectContext* context, const Primitive& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()); pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } /*! Test if the ray is occluded by one of M triangles. */ static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()); return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomID(),tri.primID())); } static __forceinline bool pointQuery(PointQuery* query, PointQueryContext* context, const Primitive& tri) { return <API key><Primitive>::pointQuery(query, context, tri); } }; /*! Intersects M motion blur triangles with K rays. */ template<int M, int Mx, int K, bool filter> struct <API key> { typedef TriangleMi<M> Primitive; typedef <API key><Mx,K> Precalculations; /*! Intersects K rays with M triangles. */ static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayHitK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri) { for (size_t i=0; i<TriangleMi<M>::max_size(); i++) { if (!tri.valid(i)) break; STAT3(normal.trav_prims,1,popcnt(valid_i),K); Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time()); pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomID(),tri.primID(),i)); } } /*! Test for K rays if they are occluded by any of the M triangles. */ static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const TriangleMi<M>& tri) { vbool<K> valid0 = valid_i; for (size_t i=0; i<TriangleMi<M>::max_size(); i++) { if (!tri.valid(i)) break; STAT3(shadow.trav_prims,1,popcnt(valid0),K); Vec3vf<K> v0,v1,v2; tri.gather(valid_i,v0,v1,v2,i,context->scene,ray.time()); pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomID(),tri.primID(),i)); if (none(valid0)) break; } return !valid0; } /*! Intersect a ray with M triangles and updates the hit. */ static __forceinline void intersect(Precalculations& pre, RayHitK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri) { STAT3(normal.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]); pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } /*! Test if the ray is occluded by one of the M triangles. */ static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const TriangleMi<M>& tri) { STAT3(shadow.trav_prims,1,1,1); Vec3vf<M> v0,v1,v2; tri.gather(v0,v1,v2,context->scene,ray.time()[k]); return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomID(),tri.primID())); } }; } }
<div class="container-fluid landing"> <div id="almari"> <center> <h1 id="alm">Almari</h1> <h2 id="sub">Elegant clothing. Delivered.</h2> </center> </div> <div class="sec1"> <div class="row" id="toprow"> <div class="col-md-6" id="borrow"> <center> <img src="clothing285.png" class="icon"> <p> Prom, party or wedding, but nothing to wear? <br> Your virtual wardrobe has some exotic clothing...</p> <div class="col-md-4 col-centered btn" type="button"> <h3 class = "box" ng-click="borrow()">BORROW</h3> </div> </center> </div> <div class="col-md-6"> <center> <img src="pricetag.png" class="icon"> <p> Bought an expensive dress, but wore it only once? <br> Monetize your wardrobe </p> <div class="col-md-4 col-centered btn" type="button"> <h3 class="box" ng-click="lend()">LEND</h3> </div> </center> </div> </div> <br><br> </div> <div id="sec2"> <br> <br> </div> </div>
[![Docker Hub](http: [![Gratipay](http: # Trusted Docker Image for Rubinius Ruby ## Use the Trusted Image sudo docker run -i -t hopsoft/ruby-rbx:2.5.3 bash ruby -v ## Build the Image Manually # Dependencies * [Virtual Box](https: * [Vagrant](http: git clone https://github.com/hopsoft/docker-ruby-rbx.git cd docker-ruby-rbx vagrant up vagrant ssh sudo docker build -t hopsoft/ruby-rbx /vagrant Once the build finishes, you can [use the image](#<API key>).
<!DOCTYPE html PUBLIC "- <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.13"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="files_8.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Wczytywanie...</div> <div id="SRResults"></div> <script type="text/javascript"><! createResults(); --></script> <div class="SRStatus" id="Searching">Szukanie...</div> <div class="SRStatus" id="NoMatches">Brak dopasowań</div> <script type="text/javascript"><! document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
# modification, are permitted provided that the following conditions are met: # documentation and/or other materials provided with the distribution. # * Neither the name of the University of Freiburg nor the names of its # contributors may be used to endorse or promote products derived from # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # 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. # COMPILER SETTINGS (default: Release) # Use "-DCMAKE_BUILD_TYPE=Debug" in cmake for a Debug-build IF(NOT <API key> AND NOT CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE Release) ENDIF(NOT <API key> AND NOT CMAKE_BUILD_TYPE) MESSAGE ("\n") MESSAGE (STATUS "${PROJECT_NAME} building as ${CMAKE_BUILD_TYPE}") # COMPILER FLAGS IF (<API key>) SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-error") SET (<API key> "-O3 -fmessage-length=0 -fno-strict-aliasing -DNDEBUG") SET (CMAKE_C_FLAGS_DEBUG "-O0 -g3 -DTRACE=1") SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-error") SET (<API key> "-O3 -fmessage-length=0 -fno-strict-aliasing -DNDEBUG") SET (<API key> "-O0 -g3 -DTRACE=1") # Shared object compilation under 64bit (vtable) ADD_DEFINITIONS(-fPIC) ADD_DEFINITIONS(-<API key>=${<API key>}) ADD_DEFINITIONS(-<API key>=${<API key>}) ADD_DEFINITIONS(-<API key>=${<API key>}) ENDIF() # Use, i.e. don't skip the full RPATH for the build tree set(<API key> FALSE) # When building, don't use the install RPATH already (but later on # when installing) set(<API key> FALSE) # The RPATH to use when installing. Since it's empty the library must # be found in a path search by other means (e.g. LD_LIBRARY_PATH, default # library location, etc...) set(CMAKE_INSTALL_RPATH "") # Don't add teh automatically determined parts of the RPATH which point to # directories outside the build tree to the install RPATH. set(<API key> FALSE) # no prefix needed for Lua modules # set(<API key> "")
import * as React from "react"; import { CarbonIconProps } from "../../"; declare const Opacity24: React.<API key>< CarbonIconProps & React.RefAttributes<SVGSVGElement> >; export default Opacity24;
<?php namespace DSQ\Test\Compiler; use DSQ\Compiler\CompilerChain; use DSQ\Expression\BasicExpression; use DSQ\Expression\Expression; class CompilerChainTest extends \<API key> { /** * @param int $expectedcalls * @return Compiler */ public function getCompilerMock($expectedcalls = 1) { $mock = $this->getMock('DSQ\Compiler\Compiler'); $mock ->expects($this->exactly($expectedcalls)) ->method('compile') ->will($this->returnCallback(function(Expression $expr){ return new BasicExpression((int) $expr->getValue() + 1); })); return $mock; } public function testConstructor() { $chain = array($this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler')); $compiler = new CompilerChain($chain[0], $chain[1], $chain[2]); $this-><API key>($chain, 'chain', $compiler); } public function testAddCompiler() { $chain = array($this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler'), $this->getMock('DSQ\Compiler\Compiler')); $compiler = new CompilerChain; $compiler ->addCompiler($chain[0]) ->addCompiler($chain[1]) ->addCompiler($chain[2]); $this-><API key>($chain, 'chain', $compiler); } public function testCompile() { $expr = new BasicExpression(0); $chain = new CompilerChain($this->getCompilerMock(1), $this->getCompilerMock(1), $this->getCompilerMock(1)); $compiled = $chain->compile($expr); $this->assertEquals(3, $compiled->getValue()); } }
Copyright (c) 2016 Dropbox, Inc. All rights reserved. Auto-generated by Stone, do not modify. #import <Foundation/Foundation.h> #import "<API key>.h" @class <API key>; <API key> #pragma mark - API Object The `<API key>` union. Alert severity This class implements the `DBSerializable` protocol (serialize and deserialize instance methods), which is required for all Obj-C SDK API route objects. @interface <API key> : NSObject <DBSerializable, NSCopying> #pragma mark - Instance fields The `<API key>` enum type represents the possible tag states with which the `<API key>` union can exist. typedef NS_CLOSED_ENUM(NSInteger, <API key>){ (no description). <API key>, (no description). <API key>, (no description). <API key>, (no description). <API key>, (no description). <API key>, (no description). <API key>, }; Represents the union's current tag state. @property (nonatomic, readonly) <API key> tag; #pragma mark - Constructors Initializes union class with tag state of "high". @return An initialized instance. - (instancetype)initWithHigh; Initializes union class with tag state of "info". @return An initialized instance. - (instancetype)initWithInfo; Initializes union class with tag state of "low". @return An initialized instance. - (instancetype)initWithLow; Initializes union class with tag state of "medium". @return An initialized instance. - (instancetype)initWithMedium; Initializes union class with tag state of "na". @return An initialized instance. - (instancetype)initWithNa; Initializes union class with tag state of "other". @return An initialized instance. - (instancetype)initWithOther; - (instancetype)init NS_UNAVAILABLE; #pragma mark - Tag state methods Retrieves whether the union's current tag state has value "high". @return Whether the union's current tag state has value "high". - (BOOL)isHigh; Retrieves whether the union's current tag state has value "info". @return Whether the union's current tag state has value "info". - (BOOL)isInfo; Retrieves whether the union's current tag state has value "low". @return Whether the union's current tag state has value "low". - (BOOL)isLow; Retrieves whether the union's current tag state has value "medium". @return Whether the union's current tag state has value "medium". - (BOOL)isMedium; Retrieves whether the union's current tag state has value "na". @return Whether the union's current tag state has value "na". - (BOOL)isNa; Retrieves whether the union's current tag state has value "other". @return Whether the union's current tag state has value "other". - (BOOL)isOther; Retrieves string value of union's current tag state. @return A human-readable string representing the union's current tag state. - (NSString *)tagName; @end #pragma mark - Serializer Object The serialization class for the `<API key>` union. @interface <API key> : NSObject Serializes `<API key>` instances. @param instance An instance of the `<API key>` API object. @return A json-compatible dictionary representation of the `<API key>` API object. + (nullable NSDictionary<NSString *, id> *)serialize:(<API key> *)instance; Deserializes `<API key>` instances. @param dict A json-compatible dictionary representation of the `<API key>` API object. @return An instantiation of the `<API key>` object. + (<API key> *)deserialize:(NSDictionary<NSString *, id> *)dict; @end <API key>
import os import pygtk pygtk.require('2.0') import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader class Ui(object): """ The user interface. This dialog is the LaTeX input window and includes widgets to display compilation logs and a preview. It uses GTK2 which must be installed an importable. """ app_name = 'InkTeX' help_text = r"""You can set a preamble file and scale factor in the <b>settings</b> tab. The preamble should not include <b>\documentclass</b> and <b>\begin{document}</b>. The LaTeX code you write is only the stuff between <b>\begin{document}</b> and <b>\end{document}</b>. Compilation errors are reported in the <b>log</b> tab. The preamble file and scale factor are stored on a per-drawing basis, so in a new document, these information must be set again.""" about_text = r"""Written by <a href="mailto:janoliver@oelerich.org">Jan Oliver Oelerich &lt;janoliver@oelerich.org&gt;</a>""" def __init__(self, render_callback, src, settings): """Takes the following parameters: * render_callback: callback function to execute with "apply" button * src: source code that should be pre-inserted into the LaTeX input""" self.render_callback = render_callback self.src = src if src else "" self.settings = settings # init the syntax highlighting buffer lang = SyntaxLoader("latex") self.syntax_buffer = CodeBuffer(lang=lang) self.setup_ui() def render(self, widget, data=None): """Extracts the input LaTeX code and calls the render callback. If that returns true, we quit and are happy.""" buf = self.text.get_buffer() tex = buf.get_text(buf.get_start_iter(), buf.get_end_iter()) settings = dict() if self.preamble.get_filename(): settings['preamble'] = self.preamble.get_filename() settings['scale'] = self.scale.get_value() if self.render_callback(tex, settings): gtk.main_quit() return False def cancel(self, widget, data=None): """Close button pressed: Exit""" raise SystemExit(1) def destroy(self, widget, event, data=None): """Destroy hook for the GTK window. Quit and return False.""" gtk.main_quit() return False def setup_ui(self): """Creates the actual UI.""" # create a floating toplevel window and set some title and border self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_type_hint(gtk.gdk.<API key>) self.window.set_title(self.app_name) self.window.set_border_width(8) # connect delete and destroy events self.window.connect("destroy", self.destroy) self.window.connect("delete-event", self.destroy) # This is our main container, vertically ordered. self.box_container = gtk.VBox(False, 5) self.box_container.show() self.notebook = gtk.Notebook() self.page_latex = gtk.HBox(False, 5) self.page_latex.set_border_width(8) self.page_latex.show() self.page_log = gtk.HBox(False, 5) self.page_log.set_border_width(8) self.page_log.show() self.page_settings = gtk.HBox(False, 5) self.page_settings.set_border_width(8) self.page_settings.show() self.page_help = gtk.VBox(False, 5) self.page_help.set_border_width(8) self.page_help.show() self.notebook.append_page(self.page_latex, gtk.Label("LaTeX")) self.notebook.append_page(self.page_log, gtk.Label("Log")) self.notebook.append_page(self.page_settings, gtk.Label("Settings")) self.notebook.append_page(self.page_help, gtk.Label("Help")) self.notebook.show() # First component: The input text view for the LaTeX code. # It lives in a ScrolledWindow so we can get some scrollbars when the # text is too long. self.text = gtk.TextView(self.syntax_buffer) self.text.get_buffer().set_text(self.src) self.text.show() self.text_container = gtk.ScrolledWindow() self.text_container.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.text_container.set_shadow_type(gtk.SHADOW_IN) self.text_container.add(self.text) self.text_container.set_size_request(400, 200) self.text_container.show() self.page_latex.pack_start(self.text_container) # Second component: The log view self.log_view = gtk.TextView() self.log_view.show() self.log_container = gtk.ScrolledWindow() self.log_container.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.log_container.set_shadow_type(gtk.SHADOW_IN) self.log_container.add(self.log_view) self.log_container.set_size_request(400, 200) self.log_container.show() self.page_log.pack_start(self.log_container) # third component: settings self.settings_container = gtk.Table(2,2) self.settings_container.set_row_spacings(8) self.settings_container.show() self.label_preamble = gtk.Label("Preamble") self.label_preamble.set_alignment(0, 0.5) self.label_preamble.show() self.preamble = gtk.FileChooserButton("...") if 'preamble' in self.settings and os.path.exists(self.settings['preamble']): self.preamble.set_filename(self.settings['preamble']) self.preamble.set_action(gtk.<API key>) self.preamble.show() self.settings_container.attach(self.label_preamble, yoptions=gtk.SHRINK, left_attach=0, right_attach=1, top_attach=0, bottom_attach=1) self.settings_container.attach(self.preamble, yoptions=gtk.SHRINK, left_attach=1, right_attach=2, top_attach=0, bottom_attach=1) self.label_scale = gtk.Label("Scale") self.label_scale.set_alignment(0, 0.5) self.label_scale.show() self.scale_adjustment = gtk.Adjustment(value=1.0, lower=0, upper=100, step_incr=0.1) self.scale = gtk.SpinButton(adjustment=self.scale_adjustment, digits=1) if 'scale' in self.settings: self.scale.set_value(float(self.settings['scale'])) self.scale.show() self.settings_container.attach(self.label_scale, yoptions=gtk.SHRINK, left_attach=0, right_attach=1, top_attach=1, bottom_attach=2) self.settings_container.attach(self.scale, yoptions=gtk.SHRINK, left_attach=1, right_attach=2, top_attach=1, bottom_attach=2) self.page_settings.pack_start(self.settings_container) # help tab self.help_label = gtk.Label() self.help_label.set_markup(Ui.help_text) self.help_label.set_line_wrap(True) self.help_label.show() self.about_label = gtk.Label() self.about_label.set_markup(Ui.about_text) self.about_label.set_line_wrap(True) self.about_label.show() self.separator_help = gtk.HSeparator() self.separator_help.show() self.page_help.pack_start(self.help_label) self.page_help.pack_start(self.separator_help) self.page_help.pack_start(self.about_label) self.box_container.pack_start(self.notebook, True, True) # separator between buttonbar and notebook self.separator_buttons = gtk.HSeparator() self.separator_buttons.show() self.box_container.pack_start(self.separator_buttons, False, False) # the button bar self.box_buttons = gtk.HButtonBox() self.box_buttons.set_layout(gtk.BUTTONBOX_END) self.box_buttons.show() self.button_render = gtk.Button(stock=gtk.STOCK_APPLY) self.button_cancel = gtk.Button(stock=gtk.STOCK_CLOSE) self.button_render.set_flags(gtk.CAN_DEFAULT) self.button_render.connect("clicked", self.render, None) self.button_cancel.connect("clicked", self.cancel, None) self.button_render.show() self.button_cancel.show() self.box_buttons.pack_end(self.button_cancel) self.box_buttons.pack_end(self.button_render) self.box_container.pack_start(self.box_buttons, False, False) self.window.add(self.box_container) self.window.set_default(self.button_render) self.window.show() def log(self, msg): buffer = self.log_view.get_buffer() buffer.set_text(msg) self.notebook.set_current_page(1) def main(self): gtk.main()
'use strict'; var convert = require('./convert'), func = convert('findLastIndexFrom', require('../findLastIndex')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2ZpbmRMYXN0SW5kZXhGcm9tLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFkO0lBQ0ksT0FBTyxRQUFRLG1CQUFSLEVBQTZCLFFBQVEsa0JBQVIsQ0FBN0IsQ0FEWDs7QUFHQSxLQUFLLFdBQUwsR0FBbUIsUUFBUSxlQUFSLENBQW5CO0FBQ0EsT0FBTyxPQUFQLEdBQWlCLElBQWpCIiwiZmlsZSI6ImZpbmRMYXN0SW5kZXhGcm9tLmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGNvbnZlcnQgPSByZXF1aXJlKCcuL2NvbnZlcnQnKSxcbiAgICBmdW5jID0gY29udmVydCgnZmluZExhc3RJbmRleEZyb20nLCByZXF1aXJlKCcuLi9maW5kTGFzdEluZGV4JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
<?php /** * Functions related to starring private messages. * * @package BuddyPress * @subpackage MessagesStar * @since 2.3.0 */ // Exit if accessed directly. defined( 'ABSPATH' ) || exit; /** * Return the starred messages slug. Defaults to 'starred'. * * @since 2.3.0 * * @return string */ function <API key>() { /** * Filters the starred message slug. * * @since 2.3.0 * * @param string */ return sanitize_title( apply_filters( '<API key>', 'starred' ) ); } /** * Function to determine if a message ID is starred. * * @since 2.3.0 * * @param int $mid The message ID. Please note that this isn't the message thread ID. * @param int $user_id The user ID. * @return bool */ function <API key>( $mid = 0, $user_id = 0 ) { if ( empty( $user_id ) ) { $user_id = <API key>(); } if ( empty( $mid ) ) { return false; } $starred = array_flip( (array) <API key>( $mid, 'starred_by_user', false ) ); if ( isset( $starred[$user_id] ) ) { return true; } else { return false; } } /** * Output the link or raw URL for starring or unstarring a message. * * @since 2.3.0 * * @param array $args See <API key>() for full documentation. */ function <API key>( $args = array() ) { echo <API key>( $args ); } /** * Return the link or raw URL for starring or unstarring a message. * * @since 2.3.0 * * @param array $args { * Array of arguments. * @type int $user_id The user ID. Defaults to the logged-in user ID. * @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over * $message_id. * @type int $message_id The individual message ID. If on a single thread page, defaults to the * current message ID in the message loop. * @type bool $url_only Whether to return the URL only. If false, returns link with markup. * Default: false. * @type string $text_unstar Link text for the 'unstar' action. Only applicable if $url_only is false. * @type string $text_star Link text for the 'star' action. Only applicable if $url_only is false. * @type string $title_unstar Link title for the 'unstar' action. Only applicable if $url_only is false. * @type string $title_star Link title for the 'star' action. Only applicable if $url_only is false. * @type string $title_unstar_thread Link title for the 'unstar' action when displayed in a thread loop. * Only applicable if $message_id is set and if $url_only is false. * @type string $title_star_thread Link title for the 'star' action when displayed in a thread loop. * Only applicable if $message_id is set and if $url_only is false. * } * @return string */ function <API key>( $args = array() ) { // Default user ID. $user_id = <API key>() ? <API key>() : bp_loggedin_user_id(); $r = bp_parse_args( $args, array( 'user_id' => (int) $user_id, 'thread_id' => 0, 'message_id' => (int) <API key>(), 'url_only' => false, 'text_unstar' => __( 'Unstar', 'buddypress' ), 'text_star' => __( 'Star', 'buddypress' ), 'title_unstar' => __( 'Starred', 'buddypress' ), 'title_star' => __( 'Not starred', 'buddypress' ), 'title_unstar_thread' => __( 'Remove all starred messages in this thread', 'buddypress' ), 'title_star_thread' => __( 'Star the first message in this thread', 'buddypress' ), ), '<API key>' ); // Check user ID and determine base user URL. switch ( $r['user_id'] ) { // Current user. case bp_loggedin_user_id() : $user_domain = <API key>(); break; // Displayed user. case <API key>() : $user_domain = <API key>(); break; // Empty or other. default : $user_domain = <API key>( $r['user_id'] ); break; } // Bail if no user domain was calculated. if ( empty( $user_domain ) ) { return ''; } // Define local variables. $retval = $bulk_attr = ''; // Thread ID. if ( (int) $r['thread_id'] > 0 ) { // See if we're in the loop. if ( <API key>() == $r['thread_id'] ) { // Grab all message ids. $mids = wp_list_pluck( $GLOBALS['messages_template']->thread->messages, 'id' ); // Make sure order is ASC. // Order is DESC when used in the thread loop by default. $mids = array_reverse( $mids ); // Pull up the thread. } else { $thread = new BP_Messages_Thread( $r['thread_id'] ); $mids = wp_list_pluck( $thread->messages, 'id' ); } $is_starred = false; $message_id = 0; foreach ( $mids as $mid ) { // Try to find the first msg that is starred in a thread. if ( true === <API key>( $mid ) ) { $is_starred = true; $message_id = $mid; break; } } // No star, so default to first message in thread. if ( empty( $message_id ) ) { $message_id = $mids[0]; } $message_id = (int) $message_id; // Nonce. $nonce = wp_create_nonce( "bp-messages-star-{$message_id}" ); if ( true === $is_starred ) { $action = 'unstar'; $bulk_attr = ' data-star-bulk="1"'; $retval = $user_domain . <API key>() . '/unstar/' . $message_id . '/' . $nonce . '/all/'; } else { $action = 'star'; $retval = $user_domain . <API key>() . '/star/' . $message_id . '/' . $nonce . '/'; } $title = $r["title_{$action}_thread"]; // Message ID. } else { $message_id = (int) $r['message_id']; $is_starred = <API key>( $message_id ); $nonce = wp_create_nonce( "bp-messages-star-{$message_id}" ); if ( true === $is_starred ) { $action = 'unstar'; $retval = $user_domain . <API key>() . '/unstar/' . $message_id . '/' . $nonce . '/'; } else { $action = 'star'; $retval = $user_domain . <API key>() . '/star/' . $message_id . '/' . $nonce . '/'; } $title = $r["title_{$action}"]; } /** * Filters the star action URL for starring / unstarring a message. * * @since 2.3.0 * * @param string $retval URL for starring / unstarring a message. * @param array $r Parsed link arguments. See $args in <API key>(). */ $retval = esc_url( apply_filters( '<API key>', $retval, $r ) ); if ( true === (bool) $r['url_only'] ) { return $retval; } /** * Filters the star action link, including markup. * * @since 2.3.0 * * @param string $retval Link for starring / unstarring a message, including markup. * @param array $r Parsed link arguments. See $args in <API key>(). */ return apply_filters( '<API key>', '<a data-bp-tooltip="' . esc_attr( $title ) . '" class="bp-tooltip message-action-' . esc_attr( $action ) . '" data-star-status="' . esc_attr( $action ) .'" data-star-nonce="' . esc_attr( $nonce ) . '"' . $bulk_attr . ' data-message-id="' . esc_attr( (int) $message_id ) . '" href="' . $retval . '" role="button" aria-pressed="false"><span class="icon"></span> <span class="<API key>">' . $r['text_' . $action] . '</span></a>', $r ); } /** * Save or delete star message meta according to a message's star status. * * @since 2.3.0 * * @param array $args { * Array of arguments. * @type string $action The star action. Either 'star' or 'unstar'. Default: 'star'. * @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over * $message_id. * @type int $message_id The indivudal message ID to star or unstar. Default: 0. * @type int $user_id The user ID. Defaults to the logged-in user ID. * @type bool $bulk Whether to mark all messages in a thread as a certain action. Only relevant * when $action is 'unstar' at the moment. Default: false. * } * @return bool */ function <API key>( $args = array() ) { $r = wp_parse_args( $args, array( 'action' => 'star', 'thread_id' => 0, 'message_id' => 0, 'user_id' => <API key>(), 'bulk' => false ) ); // Set thread ID. if ( ! empty( $r['thread_id'] ) ) { $thread_id = (int) $r['thread_id']; } else { $thread_id = <API key>( $r['message_id'] ); } if ( empty( $thread_id ) ) { return false; } // Check if user has access to thread. if( ! <API key>( $thread_id, $r['user_id'] ) ) { return false; } $is_starred = <API key>( $r['message_id'], $r['user_id'] ); // Star. if ( 'star' == $r['action'] ) { if ( true === $is_starred ) { return true; } else { <API key>( $r['message_id'], 'starred_by_user', $r['user_id'] ); return true; } // Unstar. } else { // Unstar one message. if ( false === $r['bulk'] ) { if ( false === $is_starred ) { return true; } else { <API key>( $r['message_id'], 'starred_by_user', $r['user_id'] ); return true; } // Unstar all messages in a thread. } else { $thread = new BP_Messages_Thread( $thread_id ); $mids = wp_list_pluck( $thread->messages, 'id' ); foreach ( $mids as $mid ) { if ( true === <API key>( $mid, $r['user_id'] ) ) { <API key>( $mid, 'starred_by_user', $r['user_id'] ); } } return true; } } } /** * Screen handler to display a user's "Starred" private messages page. * * @since 2.3.0 */ function <API key>() { add_action( 'bp_template_content', '<API key>' ); /** * Fires right before the loading of the "Starred" messages box. * * @since 2.3.0 */ do_action( '<API key>' ); <API key>( 'members/single/plugins' ); } /** * Screen content callback to display a user's "Starred" messages page. * * @since 2.3.0 */ function <API key>() { // Add our message thread filter. add_filter( '<API key>', '<API key>' ); // Load the message loop template part. <API key>( 'members/single/messages/messages-loop' ); // Remove our filter. remove_filter( '<API key>', '<API key>' ); } /** * Filter message threads by those starred by the logged-in user. * * @since 2.3.0 * * @param array $r Current message thread arguments. * @return array $r Array of starred message threads. */ function <API key>( $r = array() ) { $r['box'] = 'starred'; $r['meta_query'] = array( array( 'key' => 'starred_by_user', 'value' => $r['user_id'] ) ); return $r; } /** * Action handler to set a message's star status for those not using JS. * * @since 2.3.0 */ function <API key>() { if ( ! bp_is_user_messages() ) { return; } if ( false === ( <API key>( 'unstar' ) || <API key>( 'star' ) ) ) { return; } if ( ! wp_verify_nonce( bp_action_variable( 1 ), 'bp-messages-star-' . bp_action_variable( 0 ) ) ) { wp_die( "Oops! That's a no-no!" ); } // Check capability. if ( ! is_user_logged_in() || ! <API key>() ) { return; } // Mark the star. <API key>( array( 'action' => bp_current_action(), 'message_id' => bp_action_variable(), 'bulk' => (bool) bp_action_variable( 2 ) ) ); // Redirect back to previous screen. $redirect = wp_get_referer() ? wp_get_referer() : <API key>() . <API key>(); bp_core_redirect( $redirect ); die(); } add_action( 'bp_actions', '<API key>' ); /** * Bulk manage handler to set the star status for multiple messages. * * @since 2.3.0 */ function <API key>() { if ( empty( $_POST['messages_bulk_nonce' ] ) ) { return; } // Check the nonce. if ( ! wp_verify_nonce( $_POST['messages_bulk_nonce'], 'messages_bulk_nonce' ) ) { return; } // Check capability. if ( ! is_user_logged_in() || ! <API key>() ) { return; } $action = ! empty( $_POST['<API key>'] ) ? $_POST['<API key>'] : ''; $threads = ! empty( $_POST['message_ids'] ) ? $_POST['message_ids'] : ''; $threads = wp_parse_id_list( $threads ); // Bail if action doesn't match our star actions or no IDs. if ( false === in_array( $action, array( 'star', 'unstar' ), true ) || empty( $threads ) ) { return; } // It's star time! switch ( $action ) { case 'star' : $count = count( $threads ); // If we're starring a thread, we only star the first message in the thread. foreach ( $threads as $thread ) { $thread = new BP_Messages_thread( $thread ); $mids = wp_list_pluck( $thread->messages, 'id' ); <API key>( array( 'action' => 'star', 'message_id' => $mids[0], ) ); } bp_core_add_message( sprintf( _n( '%s message was successfully starred', '%s messages were successfully starred', $count, 'buddypress' ), $count ) ); break; case 'unstar' : $count = count( $threads ); foreach ( $threads as $thread ) { <API key>( array( 'action' => 'unstar', 'thread_id' => $thread, 'bulk' => true ) ); } bp_core_add_message( sprintf( _n( '%s message was successfully unstarred', '%s messages were successfully unstarred', $count, 'buddypress' ), $count ) ); break; } // Redirect back to message box. bp_core_redirect( <API key>() . <API key>() . '/' . bp_current_action() . '/' ); die(); } add_action( 'bp_actions', '<API key>', 5 ); /** * Enqueues the dashicons font. * * The dashicons font is used for the star / unstar icon. * * @since 2.3.0 */ function <API key>() { if ( ! bp_is_user_messages() ) { return; } wp_enqueue_style( 'dashicons' ); } add_action( 'bp_enqueue_scripts', '<API key>' ); /** * Add the "Add star" and "Remove star" options to the bulk management list. * * @since 2.3.0 */ function <API key>() { ?> <option value="star"><?php _e( 'Add star', 'buddypress' ); ?></option> <option value="unstar"><?php _e( 'Remove star', 'buddypress' ); ?></option> <?php } add_action( '<API key>', '<API key>', 1 ); /** * Add CSS class for the current message depending on starred status. * * @since 2.3.0 * * @param array $retval Current CSS classes. * @return array */ function <API key>( $retval = array() ) { if ( true === <API key>( <API key>() ) ) { $status = 'starred'; } else { $status = 'not-starred'; } // Add css class based on star status for the current message. $retval[] = "message-{$status}"; return $retval; } add_filter( '<API key>', '<API key>' );
<!doctype html> <html> <head> <title>Radian to degree</title> <script src="/require.js"></script> <!-- ATTENTION: Remove in non-test code --> <script src="/requireconfig.js"></script> </head> <body> </body> </html>
<?php namespace Illuminate\Cache; use Closure; use Exception; use Carbon\Carbon; use Illuminate\Contracts\Cache\Store; use Illuminate\Database\ConnectionInterface; class DatabaseStore implements Store { use <API key>; /** * The database connection instance. * * @var \Illuminate\Database\ConnectionInterface */ protected $connection; /** * The name of the cache table. * * @var string */ protected $table; /** * A string that should be prepended to keys. * * @var string */ protected $prefix; /** * Create a new database store. * * @param \Illuminate\Database\ConnectionInterface $connection * @param string $table * @param string $prefix * @return void */ public function __construct(ConnectionInterface $connection, $table, $prefix = '') { $this->table = $table; $this->prefix = $prefix; $this->connection = $connection; } /** * Retrieve an item from the cache by key. * * @param string|array $key * @return mixed */ public function get($key) { $prefixed = $this->prefix.$key; $cache = $this->table()->where('key', '=', $prefixed)->first(); // If we have a cache record we will check the expiration time against current // time on the system and see if the record has expired. If it has, we will // remove the records from the database table so it isn't returned again. if (is_null($cache)) { return; } $cache = is_array($cache) ? (object) $cache : $cache; // If this cache expiration date is past the current time, we will remove this // item from the cache. Then we will return a null value since the cache is // expired. We will use "Carbon" to make this comparison with the column. if (Carbon::now()->getTimestamp() >= $cache->expiration) { $this->forget($key); return; } return unserialize($cache->value); } /** * Store an item in the cache for a given number of minutes. * * @param string $key * @param mixed $value * @param float|int $minutes * @return void */ public function put($key, $value, $minutes) { $key = $this->prefix.$key; $value = serialize($value); $expiration = $this->getTime() + (int) ($minutes * 60); try { $this->table()->insert(compact('key', 'value', 'expiration')); } catch (Exception $e) { $this->table()->where('key', $key)->update(compact('value', 'expiration')); } } /** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return int|bool */ public function increment($key, $value = 1) { return $this-><API key>($key, $value, function ($current, $value) { return $current + $value; }); } /** * Decrement the value of an item in the cache. * * @param string $key * @param mixed $value * @return int|bool */ public function decrement($key, $value = 1) { return $this-><API key>($key, $value, function ($current, $value) { return $current - $value; }); } /** * Increment or decrement an item in the cache. * * @param string $key * @param mixed $value * @param \Closure $callback * @return int|bool */ protected function <API key>($key, $value, Closure $callback) { return $this->connection->transaction(function () use ($key, $value, $callback) { $prefixed = $this->prefix.$key; $cache = $this->table()->where('key', $prefixed) ->lockForUpdate()->first(); // If there is no value in the cache, we will return false here. Otherwise the // value will be decrypted and we will proceed with this function to either // increment or decrement this value based on the given action callbacks. if (is_null($cache)) { return false; } $cache = is_array($cache) ? (object) $cache : $cache; $current = unserialize($cache->value); // Here we'll call this callback function that was given to the function which // is used to either increment or decrement the function. We use a callback // so we do not have to recreate all this logic in each of the functions. $new = $callback((int) $current, $value); if (! is_numeric($current)) { return false; } // Here we will update the values in the table. We will also encrypt the value // since database cache values are encrypted by default with secure storage // that can't be easily read. We will return the new value after storing. $this->table()->where('key', $prefixed)->update([ 'value' => serialize($new), ]); return $new; }); } /** * Get the current system time. * * @return int */ protected function getTime() { return Carbon::now()->getTimestamp(); } /** * Store an item in the cache indefinitely. * * @param string $key * @param mixed $value * @return void */ public function forever($key, $value) { $this->put($key, $value, 5256000); } /** * Remove an item from the cache. * * @param string $key * @return bool */ public function forget($key) { $this->table()->where('key', '=', $this->prefix.$key)->delete(); return true; } /** * Remove all items from the cache. * * @return bool */ public function flush() { return (bool) $this->table()->delete(); } /** * Get a query builder for the cache table. * * @return \Illuminate\Database\Query\Builder */ protected function table() { return $this->connection->table($this->table); } /** * Get the underlying database connection. * * @return \Illuminate\Database\ConnectionInterface */ public function getConnection() { return $this->connection; } /** * Get the cache key prefix. * * @return string */ public function getPrefix() { return $this->prefix; } }
'use strict'; /** * Person object. * */ class PersonResult { /** * Create a PersonResult. * @member {string} personId personId of the target face list. * @member {array} [persistedFaceIds] persistedFaceIds of registered faces in * the person. These persistedFaceIds are returned from Person - Add a Person * Face, and will not expire. * @member {string} [name] Person's display name. * @member {string} [userData] User-provided data attached to this person. */ constructor() { } /** * Defines the metadata of PersonResult * * @returns {object} metadata of PersonResult * */ mapper() { return { required: false, serializedName: 'PersonResult', type: { name: 'Composite', className: 'PersonResult', modelProperties: { personId: { required: true, serializedName: 'personId', type: { name: 'String' } }, persistedFaceIds: { required: false, serializedName: 'persistedFaceIds', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, userData: { required: false, serializedName: 'userData', type: { name: 'String' } } } } }; } } module.exports = PersonResult;
<?php namespace Symfony\Bundle\FrameworkBundle\Test; use Symfony\Bundle\FrameworkBundle\Client; use Symfony\Component\Finder\Finder; use Symfony\Component\HttpKernel\HttpKernelInterface; /** * WebTestCase is the base class for functional tests. * * @author Fabien Potencier <fabien@symfony.com> */ abstract class WebTestCase extends \<API key> { protected static $class; protected static $kernel; /** * Creates a Client. * * @param array $options An array of options to pass to the createKernel class * @param array $server An array of server parameters * * @return Client A Client instance */ protected static function createClient(array $options = array(), array $server = array()) { if (null !== static::$kernel) { static::$kernel->shutdown(); } static::$kernel = static::createKernel($options); static::$kernel->boot(); $client = static::$kernel->getContainer()->get('test.client'); $client->setServerParameters($server); return $client; } /** * Finds the directory where the phpunit.xml(.dist) is stored. * * If you run tests with the PHPUnit CLI tool, everything will work as expected. * If not, override this method in your test classes. * * @return string The directory where phpunit.xml(.dist) is stored */ protected static function getPhpUnitXmlDir() { if (!isset($_SERVER['argv']) || false === strpos($_SERVER['argv'][0], 'phpunit')) { throw new \RuntimeException('You must override the WebTestCase::createKernel() method.'); } $dir = static::<API key>(); if ($dir === null && (is_file(getcwd().DIRECTORY_SEPARATOR.'phpunit.xml') || is_file(getcwd().DIRECTORY_SEPARATOR.'phpunit.xml.dist'))) { $dir = getcwd(); } // Can't continue if ($dir === null) { throw new \RuntimeException('Unable to guess the Kernel directory.'); } if (!is_dir($dir)) { $dir = dirname($dir); } return $dir; } /** * Finds the value of configuration flag from cli * * PHPUnit will use the last configuration argument on the command line, so this only returns * the last configuration argument * * @return string The value of the phpunit cli configuration option */ private static function <API key>() { $dir = null; $reversedArgs = array_reverse($_SERVER['argv']); foreach ($reversedArgs as $argIndex => $testArg) { if ($testArg === '-c' || $testArg === '--configuration') { $dir = realpath($reversedArgs[$argIndex - 1]); break; } elseif (strpos($testArg, '--configuration=') === 0) { $argPath = substr($testArg, strlen('--configuration=')); $dir = realpath($argPath); break; } } return $dir; } /** * Attempts to guess the kernel location. * * When the Kernel is located, the file is required. * * @return string The Kernel class name */ protected static function getKernelClass() { $dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : static::getPhpUnitXmlDir(); $finder = new Finder(); $finder->name('*Kernel.php')->depth(0)->in($dir); $results = iterator_to_array($finder); if (!count($results)) { throw new \RuntimeException('Either set KERNEL_DIR in your phpunit.xml according to http://symfony.com/doc/current/book/testing.html#<API key> or override the WebTestCase::createKernel() method.'); } $file = current($results); $class = $file->getBasename('.php'); require_once $file; return $class; } /** * Creates a Kernel. * * Available options: * * * environment * * debug * * @param array $options An array of options * * @return HttpKernelInterface A HttpKernelInterface instance */ protected static function createKernel(array $options = array()) { if (null === static::$class) { static::$class = static::getKernelClass(); } return new static::$class( isset($options['environment']) ? $options['environment'] : 'test', isset($options['debug']) ? $options['debug'] : true ); } /** * Shuts the kernel down if it was used in the test. */ protected function tearDown() { if (null !== static::$kernel) { static::$kernel->shutdown(); } } }
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using Ical.Net.DataTypes; namespace Ical.Net.Serialization.DataTypes { public class <API key> : StringSerializer { public <API key>() { } public <API key>(<API key> ctx) : base(ctx) { } public override Type TargetType => typeof (RequestStatus); public override string SerializeToString(object obj) { try { var rs = obj as RequestStatus; if (rs == null) { return null; } // Push the object onto the serialization stack <API key>.Push(rs); try { var factory = GetService<ISerializerFactory>(); var serializer = factory?.Build(typeof (StatusCode), <API key>) as IStringSerializer; if (serializer == null) { return null; } var builder = new StringBuilder(); builder.Append(Escape(serializer.SerializeToString(rs.StatusCode))); builder.Append(";"); builder.Append(Escape(rs.Description)); if (!string.IsNullOrWhiteSpace(rs.ExtraData)) { builder.Append(";"); builder.Append(Escape(rs.ExtraData)); } return Encode(rs, builder.ToString()); } finally { // Pop the object off the serialization stack <API key>.Pop(); } } catch { return null; } } internal static readonly Regex NarrowRequestMatch = new Regex(@"(.*?[^\\]);(.*?[^\\]);(.+)", RegexOptions.Compiled); internal static readonly Regex BroadRequestMatch = new Regex(@"(.*?[^\\]);(.+)", RegexOptions.Compiled); public override object Deserialize(TextReader tr) { var value = tr.ReadToEnd(); var rs = CreateAndAssociate() as RequestStatus; if (rs == null) { return null; } // Decode the value as needed value = Decode(rs, value); // Push the object onto the serialization stack <API key>.Push(rs); try { var factory = GetService<ISerializerFactory>(); if (factory == null) { return null; } var match = NarrowRequestMatch.Match(value); if (!match.Success) { match = BroadRequestMatch.Match(value); } if (match.Success) { var serializer = factory.Build(typeof(StatusCode), <API key>) as IStringSerializer; if (serializer == null) { return null; } rs.StatusCode = serializer.Deserialize(new StringReader(Unescape(match.Groups[1].Value))) as StatusCode; rs.Description = Unescape(match.Groups[2].Value); if (match.Groups.Count == 4) { rs.ExtraData = Unescape(match.Groups[3].Value); } return rs; } } finally { // Pop the object off the serialization stack <API key>.Pop(); } return null; } } }