text
stringlengths 2
99.7k
| meta
dict |
|---|---|
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/BaseTypes.js
* @requires OpenLayers/Events.js
*/
/**
* Class: OpenLayers.Control.OverviewMap
* The OverMap control creates a small overview map, useful to display the
* extent of a zoomed map and your main map and provide additional
* navigation options to the User. By default the overview map is drawn in
* the lower right corner of the main map. Create a new overview map with the
* <OpenLayers.Control.OverviewMap> constructor.
*
* Inerits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.OverviewMap = OpenLayers.Class(OpenLayers.Control, {
/**
* Property: element
* {DOMElement} The DOM element that contains the overview map
*/
element: null,
/**
* APIProperty: ovmap
* {<OpenLayers.Map>} A reference to the overview map itself.
*/
ovmap: null,
/**
* APIProperty: size
* {<OpenLayers.Size>} The overvew map size in pixels. Note that this is
* the size of the map itself - the element that contains the map (default
* class name olControlOverviewMapElement) may have padding or other style
* attributes added via CSS.
*/
size: new OpenLayers.Size(180, 90),
/**
* APIProperty: layers
* {Array(<OpenLayers.Layer>)} Ordered list of layers in the overview map.
* If none are sent at construction, the base layer for the main map is used.
*/
layers: null,
/**
* APIProperty: minRectSize
* {Integer} The minimum width or height (in pixels) of the extent
* rectangle on the overview map. When the extent rectangle reaches
* this size, it will be replaced depending on the value of the
* <minRectDisplayClass> property. Default is 15 pixels.
*/
minRectSize: 15,
/**
* APIProperty: minRectDisplayClass
* {String} Replacement style class name for the extent rectangle when
* <minRectSize> is reached. This string will be suffixed on to the
* displayClass. Default is "RectReplacement".
*
* Example CSS declaration:
* (code)
* .olControlOverviewMapRectReplacement {
* overflow: hidden;
* cursor: move;
* background-image: url("img/overview_replacement.gif");
* background-repeat: no-repeat;
* background-position: center;
* }
* (end)
*/
minRectDisplayClass: "RectReplacement",
/**
* APIProperty: minRatio
* {Float} The ratio of the overview map resolution to the main map
* resolution at which to zoom farther out on the overview map.
*/
minRatio: 8,
/**
* APIProperty: maxRatio
* {Float} The ratio of the overview map resolution to the main map
* resolution at which to zoom farther in on the overview map.
*/
maxRatio: 32,
/**
* APIProperty: mapOptions
* {Object} An object containing any non-default properties to be sent to
* the overview map's map constructor. These should include any
* non-default options that the main map was constructed with.
*/
mapOptions: null,
/**
* APIProperty: autoPan
* {Boolean} Always pan the overview map, so the extent marker remains in
* the center. Default is false. If true, when you drag the extent
* marker, the overview map will update itself so the marker returns
* to the center.
*/
autoPan: false,
/**
* Property: handlers
* {Object}
*/
handlers: null,
/**
* Property: resolutionFactor
* {Object}
*/
resolutionFactor: 1,
/**
* APIProperty: maximized
* {Boolean} Start as maximized (visible). Defaults to false.
*/
maximized: false,
/**
* Constructor: OpenLayers.Control.OverviewMap
* Create a new overview map
*
* Parameters:
* object - {Object} Properties of this object will be set on the overview
* map object. Note, to set options on the map object contained in this
* control, set <mapOptions> as one of the options properties.
*/
initialize: function(options) {
this.layers = [];
this.handlers = {};
OpenLayers.Control.prototype.initialize.apply(this, [options]);
},
/**
* APIMethod: destroy
* Deconstruct the control
*/
destroy: function() {
if (!this.mapDiv) { // we've already been destroyed
return;
}
if (this.handlers.click) {
this.handlers.click.destroy();
}
if (this.handlers.drag) {
this.handlers.drag.destroy();
}
this.mapDiv.removeChild(this.extentRectangle);
this.extentRectangle = null;
if (this.rectEvents) {
this.rectEvents.destroy();
this.rectEvents = null;
}
if (this.ovmap) {
this.ovmap.destroy();
this.ovmap = null;
}
this.element.removeChild(this.mapDiv);
this.mapDiv = null;
this.div.removeChild(this.element);
this.element = null;
if (this.maximizeDiv) {
OpenLayers.Event.stopObservingElement(this.maximizeDiv);
this.div.removeChild(this.maximizeDiv);
this.maximizeDiv = null;
}
if (this.minimizeDiv) {
OpenLayers.Event.stopObservingElement(this.minimizeDiv);
this.div.removeChild(this.minimizeDiv);
this.minimizeDiv = null;
}
this.map.events.un({
"moveend": this.update,
"changebaselayer": this.baseLayerDraw,
scope: this
});
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* Render the control in the browser.
*/
draw: function() {
OpenLayers.Control.prototype.draw.apply(this, arguments);
if(!(this.layers.length > 0)) {
if (this.map.baseLayer) {
var layer = this.map.baseLayer.clone();
this.layers = [layer];
} else {
this.map.events.register("changebaselayer", this, this.baseLayerDraw);
return this.div;
}
}
// create overview map DOM elements
this.element = document.createElement('div');
this.element.className = this.displayClass + 'Element';
this.element.style.display = 'none';
this.mapDiv = document.createElement('div');
this.mapDiv.style.width = this.size.w + 'px';
this.mapDiv.style.height = this.size.h + 'px';
this.mapDiv.style.position = 'relative';
this.mapDiv.style.overflow = 'hidden';
this.mapDiv.id = OpenLayers.Util.createUniqueID('overviewMap');
this.extentRectangle = document.createElement('div');
this.extentRectangle.style.position = 'absolute';
this.extentRectangle.style.zIndex = 1000; //HACK
this.extentRectangle.className = this.displayClass+'ExtentRectangle';
this.mapDiv.appendChild(this.extentRectangle);
this.element.appendChild(this.mapDiv);
this.div.appendChild(this.element);
// Optionally add min/max buttons if the control will go in the
// map viewport.
if(!this.outsideViewport) {
this.div.className += " " + this.displayClass + 'Container';
var imgLocation = OpenLayers.Util.getImagesLocation();
// maximize button div
var img = imgLocation + 'layer-switcher-maximize.png';
this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv(
this.displayClass + 'MaximizeButton',
null,
new OpenLayers.Size(18,18),
img,
'absolute');
this.maximizeDiv.style.display = 'none';
this.maximizeDiv.className = this.displayClass + 'MaximizeButton';
OpenLayers.Event.observe(this.maximizeDiv, 'click',
OpenLayers.Function.bindAsEventListener(this.maximizeControl,
this)
);
this.div.appendChild(this.maximizeDiv);
// minimize button div
var img = imgLocation + 'layer-switcher-minimize.png';
this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv(
'OpenLayers_Control_minimizeDiv',
null,
new OpenLayers.Size(18,18),
img,
'absolute');
this.minimizeDiv.style.display = 'none';
this.minimizeDiv.className = this.displayClass + 'MinimizeButton';
OpenLayers.Event.observe(this.minimizeDiv, 'click',
OpenLayers.Function.bindAsEventListener(this.minimizeControl,
this)
);
this.div.appendChild(this.minimizeDiv);
var eventsToStop = ['dblclick','mousedown'];
for (var i=0, len=eventsToStop.length; i<len; i++) {
OpenLayers.Event.observe(this.maximizeDiv,
eventsToStop[i],
OpenLayers.Event.stop);
OpenLayers.Event.observe(this.minimizeDiv,
eventsToStop[i],
OpenLayers.Event.stop);
}
this.minimizeControl();
} else {
// show the overview map
this.element.style.display = '';
}
if(this.map.getExtent()) {
this.update();
}
this.map.events.register('moveend', this, this.update);
if (this.maximized) {
this.maximizeControl();
}
return this.div;
},
/**
* Method: baseLayerDraw
* Draw the base layer - called if unable to complete in the initial draw
*/
baseLayerDraw: function() {
this.draw();
this.map.events.unregister("changebaselayer", this, this.baseLayerDraw);
},
/**
* Method: rectDrag
* Handle extent rectangle drag
*
* Parameters:
* px - {<OpenLayers.Pixel>} The pixel location of the drag.
*/
rectDrag: function(px) {
var deltaX = this.handlers.drag.last.x - px.x;
var deltaY = this.handlers.drag.last.y - px.y;
if(deltaX != 0 || deltaY != 0) {
var rectTop = this.rectPxBounds.top;
var rectLeft = this.rectPxBounds.left;
var rectHeight = Math.abs(this.rectPxBounds.getHeight());
var rectWidth = this.rectPxBounds.getWidth();
// don't allow dragging off of parent element
var newTop = Math.max(0, (rectTop - deltaY));
newTop = Math.min(newTop,
this.ovmap.size.h - this.hComp - rectHeight);
var newLeft = Math.max(0, (rectLeft - deltaX));
newLeft = Math.min(newLeft,
this.ovmap.size.w - this.wComp - rectWidth);
this.setRectPxBounds(new OpenLayers.Bounds(newLeft,
newTop + rectHeight,
newLeft + rectWidth,
newTop));
}
},
/**
* Method: mapDivClick
* Handle browser events
*
* Parameters:
* evt - {<OpenLayers.Event>} evt
*/
mapDivClick: function(evt) {
var pxCenter = this.rectPxBounds.getCenterPixel();
var deltaX = evt.xy.x - pxCenter.x;
var deltaY = evt.xy.y - pxCenter.y;
var top = this.rectPxBounds.top;
var left = this.rectPxBounds.left;
var height = Math.abs(this.rectPxBounds.getHeight());
var width = this.rectPxBounds.getWidth();
var newTop = Math.max(0, (top + deltaY));
newTop = Math.min(newTop, this.ovmap.size.h - height);
var newLeft = Math.max(0, (left + deltaX));
newLeft = Math.min(newLeft, this.ovmap.size.w - width);
this.setRectPxBounds(new OpenLayers.Bounds(newLeft,
newTop + height,
newLeft + width,
newTop));
this.updateMapToRect();
},
/**
* Method: maximizeControl
* Unhide the control. Called when the control is in the map viewport.
*
* Parameters:
* e - {<OpenLayers.Event>}
*/
maximizeControl: function(e) {
this.element.style.display = '';
this.showToggle(false);
if (e != null) {
OpenLayers.Event.stop(e);
}
},
/**
* Method: minimizeControl
* Hide all the contents of the control, shrink the size,
* add the maximize icon
*
* Parameters:
* e - {<OpenLayers.Event>}
*/
minimizeControl: function(e) {
this.element.style.display = 'none';
this.showToggle(true);
if (e != null) {
OpenLayers.Event.stop(e);
}
},
/**
* Method: showToggle
* Hide/Show the toggle depending on whether the control is minimized
*
* Parameters:
* minimize - {Boolean}
*/
showToggle: function(minimize) {
this.maximizeDiv.style.display = minimize ? '' : 'none';
this.minimizeDiv.style.display = minimize ? 'none' : '';
},
/**
* Method: update
* Update the overview map after layers move.
*/
update: function() {
if(this.ovmap == null) {
this.createMap();
}
if(this.autoPan || !this.isSuitableOverview()) {
this.updateOverview();
}
// update extent rectangle
this.updateRectToMap();
},
/**
* Method: isSuitableOverview
* Determines if the overview map is suitable given the extent and
* resolution of the main map.
*/
isSuitableOverview: function() {
var mapExtent = this.map.getExtent();
var maxExtent = this.map.maxExtent;
var testExtent = new OpenLayers.Bounds(
Math.max(mapExtent.left, maxExtent.left),
Math.max(mapExtent.bottom, maxExtent.bottom),
Math.min(mapExtent.right, maxExtent.right),
Math.min(mapExtent.top, maxExtent.top));
if (this.ovmap.getProjection() != this.map.getProjection()) {
testExtent = testExtent.transform(
this.map.getProjectionObject(),
this.ovmap.getProjectionObject() );
}
var resRatio = this.ovmap.getResolution() / this.map.getResolution();
return ((resRatio > this.minRatio) &&
(resRatio <= this.maxRatio) &&
(this.ovmap.getExtent().containsBounds(testExtent)));
},
/**
* Method updateOverview
* Called by <update> if <isSuitableOverview> returns true
*/
updateOverview: function() {
var mapRes = this.map.getResolution();
var targetRes = this.ovmap.getResolution();
var resRatio = targetRes / mapRes;
if(resRatio > this.maxRatio) {
// zoom in overview map
targetRes = this.minRatio * mapRes;
} else if(resRatio <= this.minRatio) {
// zoom out overview map
targetRes = this.maxRatio * mapRes;
}
var center;
if (this.ovmap.getProjection() != this.map.getProjection()) {
center = this.map.center.clone();
center.transform(this.map.getProjectionObject(),
this.ovmap.getProjectionObject() );
} else {
center = this.map.center;
}
this.ovmap.setCenter(center, this.ovmap.getZoomForResolution(
targetRes * this.resolutionFactor));
this.updateRectToMap();
},
/**
* Method: createMap
* Construct the map that this control contains
*/
createMap: function() {
// create the overview map
var options = OpenLayers.Util.extend(
{controls: [], maxResolution: 'auto',
fallThrough: false}, this.mapOptions);
this.ovmap = new OpenLayers.Map(this.mapDiv, options);
// prevent ovmap from being destroyed when the page unloads, because
// the OverviewMap control has to do this (and does it).
OpenLayers.Event.stopObserving(window, 'unload', this.ovmap.unloadDestroy);
this.ovmap.addLayers(this.layers);
this.ovmap.zoomToMaxExtent();
// check extent rectangle border width
this.wComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-left-width')) +
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-right-width'));
this.wComp = (this.wComp) ? this.wComp : 2;
this.hComp = parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-top-width')) +
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,
'border-bottom-width'));
this.hComp = (this.hComp) ? this.hComp : 2;
this.handlers.drag = new OpenLayers.Handler.Drag(
this, {move: this.rectDrag, done: this.updateMapToRect},
{map: this.ovmap}
);
this.handlers.click = new OpenLayers.Handler.Click(
this, {
"click": this.mapDivClick
},{
"single": true, "double": false,
"stopSingle": true, "stopDouble": true,
"pixelTolerance": 1,
map: this.ovmap
}
);
this.handlers.click.activate();
this.rectEvents = new OpenLayers.Events(this, this.extentRectangle,
null, true);
this.rectEvents.register("mouseover", this, function(e) {
if(!this.handlers.drag.active && !this.map.dragging) {
this.handlers.drag.activate();
}
});
this.rectEvents.register("mouseout", this, function(e) {
if(!this.handlers.drag.dragging) {
this.handlers.drag.deactivate();
}
});
if (this.ovmap.getProjection() != this.map.getProjection()) {
var sourceUnits = this.map.getProjectionObject().getUnits() ||
this.map.units || this.map.baseLayer.units;
var targetUnits = this.ovmap.getProjectionObject().getUnits() ||
this.ovmap.units || this.ovmap.baseLayer.units;
this.resolutionFactor = sourceUnits && targetUnits ?
OpenLayers.INCHES_PER_UNIT[sourceUnits] /
OpenLayers.INCHES_PER_UNIT[targetUnits] : 1;
}
},
/**
* Method: updateRectToMap
* Updates the extent rectangle position and size to match the map extent
*/
updateRectToMap: function() {
// If the projections differ we need to reproject
var bounds;
if (this.ovmap.getProjection() != this.map.getProjection()) {
bounds = this.map.getExtent().transform(
this.map.getProjectionObject(),
this.ovmap.getProjectionObject() );
} else {
bounds = this.map.getExtent();
}
var pxBounds = this.getRectBoundsFromMapBounds(bounds);
if (pxBounds) {
this.setRectPxBounds(pxBounds);
}
},
/**
* Method: updateMapToRect
* Updates the map extent to match the extent rectangle position and size
*/
updateMapToRect: function() {
var lonLatBounds = this.getMapBoundsFromRectBounds(this.rectPxBounds);
if (this.ovmap.getProjection() != this.map.getProjection()) {
lonLatBounds = lonLatBounds.transform(
this.ovmap.getProjectionObject(),
this.map.getProjectionObject() );
}
this.map.panTo(lonLatBounds.getCenterLonLat());
},
/**
* Method: setRectPxBounds
* Set extent rectangle pixel bounds.
*
* Parameters:
* pxBounds - {<OpenLayers.Bounds>}
*/
setRectPxBounds: function(pxBounds) {
var top = Math.max(pxBounds.top, 0);
var left = Math.max(pxBounds.left, 0);
var bottom = Math.min(pxBounds.top + Math.abs(pxBounds.getHeight()),
this.ovmap.size.h - this.hComp);
var right = Math.min(pxBounds.left + pxBounds.getWidth(),
this.ovmap.size.w - this.wComp);
var width = Math.max(right - left, 0);
var height = Math.max(bottom - top, 0);
if(width < this.minRectSize || height < this.minRectSize) {
this.extentRectangle.className = this.displayClass +
this.minRectDisplayClass;
var rLeft = left + (width / 2) - (this.minRectSize / 2);
var rTop = top + (height / 2) - (this.minRectSize / 2);
this.extentRectangle.style.top = Math.round(rTop) + 'px';
this.extentRectangle.style.left = Math.round(rLeft) + 'px';
this.extentRectangle.style.height = this.minRectSize + 'px';
this.extentRectangle.style.width = this.minRectSize + 'px';
} else {
this.extentRectangle.className = this.displayClass +
'ExtentRectangle';
this.extentRectangle.style.top = Math.round(top) + 'px';
this.extentRectangle.style.left = Math.round(left) + 'px';
this.extentRectangle.style.height = Math.round(height) + 'px';
this.extentRectangle.style.width = Math.round(width) + 'px';
}
this.rectPxBounds = new OpenLayers.Bounds(
Math.round(left), Math.round(bottom),
Math.round(right), Math.round(top)
);
},
/**
* Method: getRectBoundsFromMapBounds
* Get the rect bounds from the map bounds.
*
* Parameters:
* lonLatBounds - {<OpenLayers.Bounds>}
*
* Returns:
* {<OpenLayers.Bounds>}A bounds which is the passed-in map lon/lat extent
* translated into pixel bounds for the overview map
*/
getRectBoundsFromMapBounds: function(lonLatBounds) {
var leftBottomLonLat = new OpenLayers.LonLat(lonLatBounds.left,
lonLatBounds.bottom);
var rightTopLonLat = new OpenLayers.LonLat(lonLatBounds.right,
lonLatBounds.top);
var leftBottomPx = this.getOverviewPxFromLonLat(leftBottomLonLat);
var rightTopPx = this.getOverviewPxFromLonLat(rightTopLonLat);
var bounds = null;
if (leftBottomPx && rightTopPx) {
bounds = new OpenLayers.Bounds(leftBottomPx.x, leftBottomPx.y,
rightTopPx.x, rightTopPx.y);
}
return bounds;
},
/**
* Method: getMapBoundsFromRectBounds
* Get the map bounds from the rect bounds.
*
* Parameters:
* pxBounds - {<OpenLayers.Bounds>}
*
* Returns:
* {<OpenLayers.Bounds>} Bounds which is the passed-in overview rect bounds
* translated into lon/lat bounds for the overview map
*/
getMapBoundsFromRectBounds: function(pxBounds) {
var leftBottomPx = new OpenLayers.Pixel(pxBounds.left,
pxBounds.bottom);
var rightTopPx = new OpenLayers.Pixel(pxBounds.right,
pxBounds.top);
var leftBottomLonLat = this.getLonLatFromOverviewPx(leftBottomPx);
var rightTopLonLat = this.getLonLatFromOverviewPx(rightTopPx);
return new OpenLayers.Bounds(leftBottomLonLat.lon, leftBottomLonLat.lat,
rightTopLonLat.lon, rightTopLonLat.lat);
},
/**
* Method: getLonLatFromOverviewPx
* Get a map location from a pixel location
*
* Parameters:
* overviewMapPx - {<OpenLayers.Pixel>}
*
* Returns:
* {<OpenLayers.LonLat>} Location which is the passed-in overview map
* OpenLayers.Pixel, translated into lon/lat by the overview map
*/
getLonLatFromOverviewPx: function(overviewMapPx) {
var size = this.ovmap.size;
var res = this.ovmap.getResolution();
var center = this.ovmap.getExtent().getCenterLonLat();
var delta_x = overviewMapPx.x - (size.w / 2);
var delta_y = overviewMapPx.y - (size.h / 2);
return new OpenLayers.LonLat(center.lon + delta_x * res ,
center.lat - delta_y * res);
},
/**
* Method: getOverviewPxFromLonLat
* Get a pixel location from a map location
*
* Parameters:
* lonlat - {<OpenLayers.LonLat>}
*
* Returns:
* {<OpenLayers.Pixel>} Location which is the passed-in OpenLayers.LonLat,
* translated into overview map pixels
*/
getOverviewPxFromLonLat: function(lonlat) {
var res = this.ovmap.getResolution();
var extent = this.ovmap.getExtent();
var px = null;
if (extent) {
px = new OpenLayers.Pixel(
Math.round(1/res * (lonlat.lon - extent.left)),
Math.round(1/res * (extent.top - lonlat.lat)));
}
return px;
},
CLASS_NAME: 'OpenLayers.Control.OverviewMap'
});
|
{
"pile_set_name": "Github"
}
|
/* eslint no-extend-native:0 */
// Load modules
var Code = require('code');
var Lab = require('lab');
var Qs = require('../');
// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var expect = Code.expect;
var describe = lab.experiment;
var it = lab.test;
describe('parse()', function () {
it('parses a simple string', function (done) {
expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' });
expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' });
expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } });
expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } });
expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } });
expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null });
expect(Qs.parse('foo' )).to.deep.equal({ foo: '' });
expect(Qs.parse('foo=')).to.deep.equal({ foo: '' });
expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' });
expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' });
expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' });
expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' });
expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' });
expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null });
expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' });
expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({
cht: 'p3',
chd: 't:60,40',
chs: '250x100',
chl: 'Hello|World'
});
done();
});
it('allows enabling dot notation', function (done) {
expect(Qs.parse('a.b=c')).to.deep.equal({ 'a.b': 'c' });
expect(Qs.parse('a.b=c', { allowDots: true })).to.deep.equal({ a: { b: 'c' } });
done();
});
it('parses a single nested string', function (done) {
expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } });
done();
});
it('parses a double nested string', function (done) {
expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } });
done();
});
it('defaults to a depth of 5', function (done) {
expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } });
done();
});
it('only parses one level when depth = 1', function (done) {
expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } });
expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } });
done();
});
it('parses a simple array', function (done) {
expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
done();
});
it('parses an explicit array', function (done) {
expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] });
expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] });
done();
});
it('parses a mix of simple and explicit arrays', function (done) {
expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] });
done();
});
it('parses a nested array', function (done) {
expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } });
expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } });
done();
});
it('allows to specify array indices', function (done) {
expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] });
expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] });
expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] });
done();
});
it('limits specific array indices to 20', function (done) {
expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] });
expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } });
done();
});
it('supports keys that begin with a number', function (done) {
expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } });
done();
});
it('supports encoded = signs', function (done) {
expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' });
done();
});
it('is ok with url encoded strings', function (done) {
expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } });
expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } });
done();
});
it('allows brackets in the value', function (done) {
expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' });
expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' });
done();
});
it('allows empty values', function (done) {
expect(Qs.parse('')).to.deep.equal({});
expect(Qs.parse(null)).to.deep.equal({});
expect(Qs.parse(undefined)).to.deep.equal({});
done();
});
it('transforms arrays to objects', function (done) {
expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } });
expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } });
expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } });
expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } });
done();
});
it('transforms arrays to objects (dot notation)', function (done) {
expect(Qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] });
expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] });
expect(Qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
expect(Qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } });
expect(Qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true })).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } });
expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } });
expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true })).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
done();
});
it('can add keys to objects', function (done) {
expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } });
done();
});
it('correctly prunes undefined values when converting an array to an object', function (done) {
expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } });
done();
});
it('supports malformed uri characters', function (done) {
expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null });
expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' });
expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' });
done();
});
it('doesn\'t produce empty keys', function (done) {
expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' });
done();
});
it('cannot access Object prototype', function (done) {
Qs.parse('constructor[prototype][bad]=bad');
Qs.parse('bad[constructor][prototype][bad]=bad');
expect(typeof Object.prototype.bad).to.equal('undefined');
done();
});
it('parses arrays of objects', function (done) {
expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] });
expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] });
done();
});
it('allows for empty strings in arrays', function (done) {
expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] });
expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 })).to.deep.equal({ a: ['b', null, 'c', ''] });
expect(Qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 })).to.deep.equal({ a: ['b', null, 'c', ''] });
expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 })).to.deep.equal({ a: ['b', '', 'c', null] });
expect(Qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 })).to.deep.equal({ a: ['b', '', 'c', null] });
expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] });
done();
});
it('compacts sparse arrays', function (done) {
expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] });
done();
});
it('parses semi-parsed strings', function (done) {
expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } });
expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } });
done();
});
it('parses buffers correctly', function (done) {
var b = new Buffer('test');
expect(Qs.parse({ a: b })).to.deep.equal({ a: b });
done();
});
it('continues parsing when no parent is found', function (done) {
expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' });
expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' });
expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' });
done();
});
it('does not error when parsing a very long array', function (done) {
var str = 'a[]=a';
while (Buffer.byteLength(str) < 128 * 1024) {
str += '&' + str;
}
expect(function () {
Qs.parse(str);
}).to.not.throw();
done();
});
it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) {
Object.prototype.crash = '';
Array.prototype.crash = '';
expect(Qs.parse.bind(null, 'a=b')).to.not.throw();
expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' });
expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw();
expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] });
delete Object.prototype.crash;
delete Array.prototype.crash;
done();
});
it('parses a string with an alternative string delimiter', function (done) {
expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' });
done();
});
it('parses a string with an alternative RegExp delimiter', function (done) {
expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' });
done();
});
it('does not use non-splittable objects as delimiters', function (done) {
expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' });
done();
});
it('allows overriding parameter limit', function (done) {
expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' });
done();
});
it('allows setting the parameter limit to Infinity', function (done) {
expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' });
done();
});
it('allows overriding array limit', function (done) {
expect(Qs.parse('a[0]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '0': 'b' } });
expect(Qs.parse('a[-1]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '-1': 'b' } });
expect(Qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 })).to.deep.equal({ a: { '0': 'b', '1': 'c' } });
done();
});
it('allows disabling array parsing', function (done) {
expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } });
done();
});
it('parses an object', function (done) {
var input = {
'user[name]': { 'pop[bob]': 3 },
'user[email]': null
};
var expected = {
'user': {
'name': { 'pop[bob]': 3 },
'email': null
}
};
var result = Qs.parse(input);
expect(result).to.deep.equal(expected);
done();
});
it('parses an object in dot notation', function (done) {
var input = {
'user.name': { 'pop[bob]': 3 },
'user.email.': null
};
var expected = {
'user': {
'name': { 'pop[bob]': 3 },
'email': null
}
};
var result = Qs.parse(input, { allowDots: true });
expect(result).to.deep.equal(expected);
done();
});
it('parses an object and not child values', function (done) {
var input = {
'user[name]': { 'pop[bob]': { 'test': 3 } },
'user[email]': null
};
var expected = {
'user': {
'name': { 'pop[bob]': { 'test': 3 } },
'email': null
}
};
var result = Qs.parse(input);
expect(result).to.deep.equal(expected);
done();
});
it('does not blow up when Buffer global is missing', function (done) {
var tempBuffer = global.Buffer;
delete global.Buffer;
var result = Qs.parse('a=b&c=d');
global.Buffer = tempBuffer;
expect(result).to.deep.equal({ a: 'b', c: 'd' });
done();
});
it('does not crash when parsing circular references', function (done) {
var a = {};
a.b = a;
var parsed;
expect(function () {
parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
}).to.not.throw();
expect(parsed).to.contain('foo');
expect(parsed.foo).to.contain('bar', 'baz');
expect(parsed.foo.bar).to.equal('baz');
expect(parsed.foo.baz).to.deep.equal(a);
done();
});
it('parses plain objects correctly', function (done) {
var a = Object.create(null);
a.b = 'c';
expect(Qs.parse(a)).to.deep.equal({ b: 'c' });
var result = Qs.parse({ a: a });
expect(result).to.contain('a');
expect(result.a).to.deep.equal(a);
done();
});
it('parses dates correctly', function (done) {
var now = new Date();
expect(Qs.parse({ a: now })).to.deep.equal({ a: now });
done();
});
it('parses regular expressions correctly', function (done) {
var re = /^test$/;
expect(Qs.parse({ a: re })).to.deep.equal({ a: re });
done();
});
it('can allow overwriting prototype properties', function (done) {
expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false });
expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false });
done();
});
it('can return plain objects', function (done) {
var expected = Object.create(null);
expected.a = Object.create(null);
expected.a.b = 'c';
expected.a.hasOwnProperty = 'd';
expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected);
expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null));
var expectedArray = Object.create(null);
expectedArray.a = Object.create(null);
expectedArray.a['0'] = 'b';
expectedArray.a.c = 'd';
expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray);
done();
});
});
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Validates contents based on NMTOKENS attribute type.
*/
class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef
{
public function validate($string, $config, $context) {
$string = trim($string);
// early abort: '' and '0' (strings that convert to false) are invalid
if (!$string) return false;
$tokens = $this->split($string, $config, $context);
$tokens = $this->filter($tokens, $config, $context);
if (empty($tokens)) return false;
return implode(' ', $tokens);
}
/**
* Splits a space separated list of tokens into its constituent parts.
*/
protected function split($string, $config, $context) {
// OPTIMIZABLE!
// do the preg_match, capture all subpatterns for reformulation
// we don't support U+00A1 and up codepoints or
// escaping because I don't know how to do that with regexps
// and plus it would complicate optimization efforts (you never
// see that anyway).
$pattern = '/(?:(?<=\s)|\A)'. // look behind for space or string start
'((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)'.
'(?:(?=\s)|\z)/'; // look ahead for space or string end
preg_match_all($pattern, $string, $matches);
return $matches[1];
}
/**
* Template method for removing certain tokens based on arbitrary criteria.
* @note If we wanted to be really functional, we'd do an array_filter
* with a callback. But... we're not.
*/
protected function filter($tokens, $config, $context) {
return $tokens;
}
}
// vim: et sw=4 sts=4
|
{
"pile_set_name": "Github"
}
|
Bridge.merge(new System.Globalization.CultureInfo("es-PR", true), {
englishName: "Spanish (Puerto Rico)",
nativeName: "español (Puerto Rico)",
numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), {
nanSymbol: "NaN",
negativeSign: "-",
positiveSign: "+",
negativeInfinitySymbol: "-∞",
positiveInfinitySymbol: "∞",
percentSymbol: "%",
percentGroupSizes: [3],
percentDecimalDigits: 2,
percentDecimalSeparator: ".",
percentGroupSeparator: ",",
percentPositivePattern: 0,
percentNegativePattern: 0,
currencySymbol: "$",
currencyGroupSizes: [3],
currencyDecimalDigits: 2,
currencyDecimalSeparator: ".",
currencyGroupSeparator: ",",
currencyNegativePattern: 1,
currencyPositivePattern: 0,
numberGroupSizes: [3],
numberDecimalDigits: 2,
numberDecimalSeparator: ".",
numberGroupSeparator: ",",
numberNegativePattern: 1
}),
dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), {
abbreviatedDayNames: ["dom.","lun.","mar.","mié.","jue.","vie.","sáb."],
abbreviatedMonthGenitiveNames: ["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic.",""],
abbreviatedMonthNames: ["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic.",""],
amDesignator: "a. m.",
dateSeparator: "/",
dayNames: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],
firstDayOfWeek: 0,
fullDateTimePattern: "dddd, d 'de' MMMM 'de' yyyy h:mm:ss tt",
longDatePattern: "dddd, d 'de' MMMM 'de' yyyy",
longTimePattern: "h:mm:ss tt",
monthDayPattern: "d 'de' MMMM",
monthGenitiveNames: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""],
monthNames: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""],
pmDesignator: "p. m.",
rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
shortDatePattern: "MM/dd/yyyy",
shortestDayNames: ["DO","LU","MA","MI","JU","VI","SA"],
shortTimePattern: "h:mm tt",
sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
sortableDateTimePattern1: "yyyy'-'MM'-'dd",
timeSeparator: ":",
universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
yearMonthPattern: "MMMM 'de' yyyy",
roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
}),
TextInfo: Bridge.merge(new System.Globalization.TextInfo(), {
ANSICodePage: 1252,
CultureName: "es-PR",
EBCDICCodePage: 20284,
IsRightToLeft: false,
LCID: 20490,
listSeparator: ";",
MacCodePage: 10000,
OEMCodePage: 850,
IsReadOnly: true
})
});
|
{
"pile_set_name": "Github"
}
|
MFAACEnc="Media Foundation AAC Kodierer"
Bitrate="Bitrate"
MF.H264.EncoderName="Media-Foundation-H264-Kodierer"
MF.H264.Encoder="Kodierername"
MF.H264.LowLatency="Niedrige Latenz (Deaktiviert Frameneuanordnung)"
MF.H264.BFrames="Konsekutive B-Frameanzahl"
MF.H264.CustomBufsize="Benutzerdefinierte Puffergröße verwenden"
MF.H264.BufferSize="Puffergröße"
MF.H264.CustomMaxBitrate="Benutzerdefinierte Max. Bitrate verwenden"
MF.H264.Bitrate="Bitrate"
MF.H264.MaxBitrate="Max. Bitrate"
MF.H264.KeyframeIntervalSec="Keyframeintervall (Sekunden, 0 – automatisch)"
MF.H264.RateControl="Qualitätsregulierungsmethode"
MF.H264.CBR="CBR (Konstante Bitrate)"
MF.H264.VBR="VBR (Variable Bitrate)"
MF.H264.CQP="CQP (Konstante Qualität)"
MF.H264.MinQP="Minimum QP"
MF.H264.MaxQP="Maximum QP"
MF.H264.QPI="QP-I-Frame"
MF.H264.QPP="QP-P-Frame"
MF.H264.QPB="QP-B-Frame"
MF.H264.Profile="Profil"
MF.H264.Advanced="Erweitert"
MF.H264.EncoderSWMicrosoft="Microsoft-Software-H.264-Kodierer"
MF.H264.EncoderHWAMD="AMD-Video-Coding-Engine-H.264-Kodierer (Media Foundation)"
MF.H264.EncoderHWIntel="Intel-Quick-Sync-H.264-Kodierer (Media Foundation)"
MF.H264.EncoderHWNVIDIA="NVIDIA-NVENC-H.264-Kodierer (Media Foundation)"
|
{
"pile_set_name": "Github"
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Encodings.Web.Tests
{
public class UnicodeRangeTests
{
[Theory]
[InlineData(-1, 16)]
[InlineData(0x10000, 16)]
public void Ctor_FailureCase_FirstCodePoint(int firstCodePoint, int rangeSize)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("firstCodePoint", () => new UnicodeRange(firstCodePoint, rangeSize));
}
[Theory]
[InlineData(0x0100, -1)]
[InlineData(0x0100, 0x10000)]
public void Ctor_FailureCase_RangeSize(int firstCodePoint, int rangeSize)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new UnicodeRange(firstCodePoint, rangeSize));
}
[Fact]
public void Ctor_SuccessCase()
{
// Act
var range = new UnicodeRange(0x0100, 128); // Latin Extended-A
// Assert
Assert.Equal(0x0100, range.FirstCodePoint);
Assert.Equal(128, range.Length);
}
[Fact]
public void FromSpan_FailureCase()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("lastCharacter", () => UnicodeRange.Create('\u0020', '\u0010'));
}
[Fact]
public void FromSpan_SuccessCase()
{
// Act
var range = UnicodeRange.Create('\u0180', '\u024F'); // Latin Extended-B
// Assert
Assert.Equal(0x0180, range.FirstCodePoint);
Assert.Equal(208, range.Length);
}
[Fact]
public void FromSpan_SuccessCase_All()
{
// Act
var range = UnicodeRange.Create('\u0000', '\uFFFF');
// Assert
Assert.Equal(0, range.FirstCodePoint);
Assert.Equal(0x10000, range.Length);
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"version": "0.25.1",
"description": "Terragrunt is a thin wrapper for Terraform that provides extra tools for keeping your Terraform configurations DRY, working with multiple Terraform modules, and managing remote state.",
"homepage": "https://github.com/gruntwork-io/terragrunt",
"license": "MIT",
"architecture": {
"64bit": {
"url": "https://github.com/gruntwork-io/terragrunt/releases/download/v0.25.1/terragrunt_windows_amd64.exe#/terragrunt.exe",
"hash": "f612864ea6ab929795d9a2fab5d68eea671565d2dde5b367cd20f1fe925f552f"
},
"32bit": {
"url": "https://github.com/gruntwork-io/terragrunt/releases/download/v0.25.1/terragrunt_windows_386.exe#/terragrunt.exe",
"hash": "47af485342bd372fbe68c6d50a83d187c11fb12c8ee0c23fc4729d12afbb0d92"
}
},
"bin": "terragrunt.exe",
"checkver": "github",
"autoupdate": {
"architecture": {
"64bit": {
"url": "https://github.com/gruntwork-io/terragrunt/releases/download/v$version/terragrunt_windows_amd64.exe#/terragrunt.exe"
},
"32bit": {
"url": "https://github.com/gruntwork-io/terragrunt/releases/download/v$version/terragrunt_windows_386.exe#/terragrunt.exe"
}
},
"hash": {
"url": "$baseurl/SHA256SUMS"
}
}
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_172) on Sun Jun 07 15:57:41 CEST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>simplenlg.server (SimpleNLG 4.5.0 API)</title>
<meta name="date" content="2020-06-07">
<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 = "simplenlg.server (SimpleNLG 4.5.0 API)";
}
}
catch (err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../simplenlg/realiser/english/package-summary.html">Prev Package</a></li>
<li><a href="../../simplenlg/syntax/english/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?simplenlg/server/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package simplenlg.server</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0"
summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../simplenlg/server/RealisationRequest.html" title="class in simplenlg.server">RealisationRequest</a></td>
<td class="colLast">
<div class="block">This class handles one realisation request.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../simplenlg/server/SimpleServer.html" title="class in simplenlg.server">SimpleServer</a></td>
<td class="colLast">
<div class="block">SimpleServer is a program that realises xml requests.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../simplenlg/realiser/english/package-summary.html">Prev Package</a></li>
<li><a href="../../simplenlg/syntax/english/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?simplenlg/server/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy">
<small>Copyright © 2020. All Rights Reserved.</small>
</p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform>
<ProjectGuid>{4E4AD5FA-7A69-4DFA-92F9-F846D528B084}</ProjectGuid>
<ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Exe</OutputType>
<RootNamespace>RpnCalculator.iOS</RootNamespace>
<AssemblyName>RpnCalculator.iOS</AssemblyName>
<IPhoneResourcePrefix>Resources</IPhoneResourcePrefix>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\iPhoneSimulator\Debug</OutputPath>
<DefineConstants>DEBUG;ENABLE_TEST_CLOUD;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<DeviceSpecificBuild>true</DeviceSpecificBuild>
<MtouchDebug>true</MtouchDebug>
<MtouchNoSymbolStrip>true</MtouchNoSymbolStrip>
<MtouchFastDev>true</MtouchFastDev>
<IOSDebuggerPort>65497</IOSDebuggerPort>
<MtouchLink>None</MtouchLink>
<MtouchArch>i386, x86_64</MtouchArch>
<MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhone\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchFloat32>true</MtouchFloat32>
<CodesignEntitlements>Entitlements.plist</CodesignEntitlements>
<MtouchLink>SdkOnly</MtouchLink>
<MtouchArch>ARMv7, ARM64</MtouchArch>
<MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhoneSimulator\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<DeviceSpecificBuild>true</DeviceSpecificBuild>
<MtouchNoSymbolStrip>true</MtouchNoSymbolStrip>
<MtouchLink>None</MtouchLink>
<MtouchArch>i386, x86_64</MtouchArch>
<MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\iPhone\Debug</OutputPath>
<DefineConstants>DEBUG;ENABLE_TEST_CLOUD;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<DeviceSpecificBuild>true</DeviceSpecificBuild>
<MtouchDebug>true</MtouchDebug>
<MtouchNoSymbolStrip>true</MtouchNoSymbolStrip>
<MtouchFastDev>true</MtouchFastDev>
<MtouchFloat32>true</MtouchFloat32>
<CodesignEntitlements>Entitlements.plist</CodesignEntitlements>
<IOSDebuggerPort>28507</IOSDebuggerPort>
<MtouchLink>SdkOnly</MtouchLink>
<MtouchArch>ARMv7, ARM64</MtouchArch>
<MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="Xamarin.iOS" />
<Reference Include="Xamarin.Forms.Core">
<HintPath>..\packages\Xamarin.Forms.2.3.4.231\lib\Xamarin.iOS10\Xamarin.Forms.Core.dll</HintPath>
</Reference>
<Reference Include="Xamarin.Forms.Platform">
<HintPath>..\packages\Xamarin.Forms.2.3.4.231\lib\Xamarin.iOS10\Xamarin.Forms.Platform.dll</HintPath>
</Reference>
<Reference Include="Xamarin.Forms.Platform.iOS">
<HintPath>..\packages\Xamarin.Forms.2.3.4.231\lib\Xamarin.iOS10\Xamarin.Forms.Platform.iOS.dll</HintPath>
</Reference>
<Reference Include="Xamarin.Forms.Xaml">
<HintPath>..\packages\Xamarin.Forms.2.3.4.231\lib\Xamarin.iOS10\Xamarin.Forms.Xaml.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<ImageAsset Include="Assets.xcassets\AppIcon.appiconset\Contents.json" />
<ImageAsset Include="Assets.xcassets\Contents.json" />
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<InterfaceDefinition Include="LaunchScreen.storyboard" />
</ItemGroup>
<ItemGroup>
<None Include="Info.plist" />
<None Include="Entitlements.plist" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AppDelegate.cs" />
</ItemGroup>
<Import Project="..\RpnCalculator\RpnCalculator.projitems" Label="Shared" Condition="Exists('..\RpnCalculator\RpnCalculator.projitems')" />
<Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets" />
<Import Project="..\packages\Xamarin.Forms.2.3.4.231\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+Xamarin.iOS10+xamarinmac20\Xamarin.Forms.targets" Condition="Exists('..\packages\Xamarin.Forms.2.3.4.231\build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+Xamarin.iOS10+xamarinmac20\Xamarin.Forms.targets')" />
</Project>
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script src="/bluetooth/resources/bluetooth-test.js"></script>
<script src="/bluetooth/resources/bluetooth-fake-devices.js"></script>
<script>
'use strict';
const test_desc_idl = 'BluetoothDevice IDL test.';
test(() => {
assert_throws_js(
TypeError, () => new BluetoothDevice(),
'the constructor should not be callable with "new"');
assert_throws_js(
TypeError, () => BluetoothDevice(),
'the constructor should not be callable');
}, test_desc_idl);
const test_desc_attr = 'BluetoothDevice attributes.';
let device;
bluetooth_test(
() => getConnectedHealthThermometerDevice().then(({device}) => {
assert_equals(device.constructor.name, 'BluetoothDevice');
var old_device_id = device.id;
assert_throws_js(
TypeError, () => device.id = 'overwritten',
'the device id should not be writable');
assert_throws_js(
TypeError, () => device.name = 'overwritten',
'the device name should not be writable');
assert_throws_js(
TypeError, () => device.watchingAdvertisements = true,
'the device watchingAdvertisements should not be writable');
assert_equals(device.id, old_device_id);
assert_equals(device.name, 'Health Thermometer');
assert_equals(device.watchingAdvertisements, false);
}),
test_desc_attr);
</script>
|
{
"pile_set_name": "Github"
}
|
package gregtech.common.render;
import gregtech.api.enums.GT_Values;
import gregtech.api.util.GT_Log;
import gregtech.api.util.GT_Utility;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.RenderPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderPlayerEvent;
import org.lwjgl.opengl.GL11;
import java.util.Collection;
public class GT_CapeRenderer
extends RenderPlayer {
private final ResourceLocation[] mCapes = {new ResourceLocation("gregtech:textures/BrainTechCape.png"), new ResourceLocation("gregtech:textures/GregTechCape.png"), new ResourceLocation("gregtech:textures/MrBrainCape.png"), new ResourceLocation("gregtech:textures/GregoriusCape.png")};
private final Collection<String> mCapeList;
public GT_CapeRenderer(Collection<String> aCapeList) {
this.mCapeList = aCapeList;
setRenderManager(RenderManager.instance);
}
public void receiveRenderSpecialsEvent(RenderPlayerEvent.Specials.Pre aEvent) {
AbstractClientPlayer aPlayer = (AbstractClientPlayer) aEvent.entityPlayer;
if (GT_Utility.getFullInvisibility(aPlayer)) {
aEvent.setCanceled(true);
return;
}
float aPartialTicks = aEvent.partialRenderTick;
if (aPlayer.isInvisible()) {
return;
}
if (GT_Utility.getPotion(aPlayer, Integer.valueOf(Potion.invisibility.id).intValue())) {
return;
}
try {
ResourceLocation tResource = null;
if (aPlayer.getDisplayName().equalsIgnoreCase("Friedi4321")) {
tResource = this.mCapes[0];
}
if (this.mCapeList.contains(aPlayer.getDisplayName().toLowerCase())) {
tResource = this.mCapes[1];
}
if (aPlayer.getDisplayName().equalsIgnoreCase("Mr_Brain")) {
tResource = this.mCapes[2];
}
if (aPlayer.getDisplayName().equalsIgnoreCase("GregoriusT")) {
tResource = this.mCapes[3];
}
if ((tResource != null) && (!aPlayer.getHideCape())) {
bindTexture(tResource);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, 0.0F, 0.125F);
double d0 = aPlayer.field_71091_bM + (aPlayer.field_71094_bP - aPlayer.field_71091_bM) * aPartialTicks - (aPlayer.prevPosX + (aPlayer.posX - aPlayer.prevPosX) * aPartialTicks);
double d1 = aPlayer.field_71096_bN + (aPlayer.field_71095_bQ - aPlayer.field_71096_bN) * aPartialTicks - (aPlayer.prevPosY + (aPlayer.posY - aPlayer.prevPosY) * aPartialTicks);
double d2 = aPlayer.field_71097_bO + (aPlayer.field_71085_bR - aPlayer.field_71097_bO) * aPartialTicks - (aPlayer.prevPosZ + (aPlayer.posZ - aPlayer.prevPosZ) * aPartialTicks);
float f6 = aPlayer.prevRenderYawOffset + (aPlayer.renderYawOffset - aPlayer.prevRenderYawOffset) * aPartialTicks;
double d3 = MathHelper.sin(f6 * 3.141593F / 180.0F);
double d4 = -MathHelper.cos(f6 * 3.141593F / 180.0F);
float f7 = (float) d1 * 10.0F;
float f8 = (float) (d0 * d3 + d2 * d4) * 100.0F;
float f9 = (float) (d0 * d4 - d2 * d3) * 100.0F;
if (f7 < -6.0F) {
f7 = -6.0F;
}
if (f7 > 32.0F) {
f7 = 32.0F;
}
if (f8 < 0.0F) {
f8 = 0.0F;
}
float f10 = aPlayer.prevCameraYaw + (aPlayer.cameraYaw - aPlayer.prevCameraYaw) * aPartialTicks;
f7 += MathHelper.sin((aPlayer.prevDistanceWalkedModified + (aPlayer.distanceWalkedModified - aPlayer.prevDistanceWalkedModified) * aPartialTicks) * 6.0F) * 32.0F * f10;
if (aPlayer.isSneaking()) {
f7 += 25.0F;
}
GL11.glRotatef(6.0F + f8 / 2.0F + f7, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(f9 / 2.0F, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(-f9 / 2.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
((ModelBiped) this.mainModel).renderCloak(0.0625F);
GL11.glPopMatrix();
}
} catch (Throwable e) {
if (GT_Values.D1) {
e.printStackTrace(GT_Log.err);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/vector.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
namespace aux {
template< int N >
struct vector_chooser;
}
namespace aux {
template<>
struct vector_chooser<0>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef vector0<
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<1>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector1<
T0
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<2>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector2<
T0, T1
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<3>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector3<
T0, T1, T2
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<4>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector4<
T0, T1, T2, T3
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<5>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector5<
T0, T1, T2, T3, T4
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<6>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector6<
T0, T1, T2, T3, T4, T5
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<7>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector7<
T0, T1, T2, T3, T4, T5, T6
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<8>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector8<
T0, T1, T2, T3, T4, T5, T6, T7
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<9>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector9<
T0, T1, T2, T3, T4, T5, T6, T7, T8
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<10>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector10<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<11>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector11<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<12>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector12<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<13>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector13<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<14>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector14<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<15>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector15<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<16>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector16<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<17>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector17<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<18>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector18<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<19>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector19<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct vector_chooser<20>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename vector20<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type type;
};
};
} // namespace aux
namespace aux {
template< typename T >
struct is_vector_arg
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_vector_arg<na>
{
BOOST_STATIC_CONSTANT(bool, value = false);
};
template<
typename T1, typename T2, typename T3, typename T4, typename T5
, typename T6, typename T7, typename T8, typename T9, typename T10
, typename T11, typename T12, typename T13, typename T14, typename T15
, typename T16, typename T17, typename T18, typename T19, typename T20
>
struct vector_count_args
{
BOOST_STATIC_CONSTANT(int, value =
is_vector_arg<T1>::value + is_vector_arg<T2>::value
+ is_vector_arg<T3>::value + is_vector_arg<T4>::value
+ is_vector_arg<T5>::value + is_vector_arg<T6>::value
+ is_vector_arg<T7>::value + is_vector_arg<T8>::value
+ is_vector_arg<T9>::value + is_vector_arg<T10>::value
+ is_vector_arg<T11>::value + is_vector_arg<T12>::value
+ is_vector_arg<T13>::value + is_vector_arg<T14>::value
+ is_vector_arg<T15>::value + is_vector_arg<T16>::value
+ is_vector_arg<T17>::value + is_vector_arg<T18>::value
+ is_vector_arg<T19>::value + is_vector_arg<T20>::value
);
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct vector_impl
{
typedef aux::vector_count_args<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
> arg_num_;
typedef typename aux::vector_chooser< arg_num_::value >
::template result_< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19 >::type type;
};
} // namespace aux
template<
typename T0 = na, typename T1 = na, typename T2 = na, typename T3 = na
, typename T4 = na, typename T5 = na, typename T6 = na, typename T7 = na
, typename T8 = na, typename T9 = na, typename T10 = na, typename T11 = na
, typename T12 = na, typename T13 = na, typename T14 = na
, typename T15 = na, typename T16 = na, typename T17 = na
, typename T18 = na, typename T19 = na
>
struct vector
: aux::vector_impl<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type
{
typedef typename aux::vector_impl<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type type;
};
}}
|
{
"pile_set_name": "Github"
}
|
import TestControl = require('../../mocks/TestControl');
export function load () {
QUnit.module("Markup/Media");
test("VisualStateManager", () => {
var xaml = "<Grid xmlns=\"http://schemas.wsick.com/fayde\" xmlns:x=\"http://schemas.wsick.com/fayde/x\">"
+ "<VisualStateManager.VisualStateGroups>"
+ "<VisualStateGroup x:Name=\"CommonStates\">"
+ "<VisualState x:Name=\"Normal\" />"
+ "<VisualState x:Name=\"Disabled\">"
+ " <!-- composite controls will gain focus and visualize it -->"
+ "</VisualState>"
+ "</VisualStateGroup>"
+ "</VisualStateManager.VisualStateGroups>"
+ "</Grid>";
var root = Fayde.Markup.LoadXaml<Fayde.Controls.Grid>(null, xaml);
var groups = Fayde.Media.VSM.VisualStateManager.GetVisualStateGroups(root);
strictEqual((<any>groups).constructor, Fayde.Media.VSM.VisualStateGroupCollection, "VisualStateGroups on Grid should be a VisualStateGroupCollection.");
strictEqual(groups.Count, 1, "There should be 1 VisualStateGroup in collection.");
var states = groups.GetValueAt(0).States;
strictEqual(states.Count, 2);
var storyboard = states.GetValueAt(0).Storyboard;
ok(storyboard == null || storyboard instanceof Fayde.Media.Animation.Storyboard);
storyboard = states.GetValueAt(1).Storyboard;
ok(storyboard == null || storyboard instanceof Fayde.Media.Animation.Storyboard);
});
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2015 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<set
xmlns:android="http://schemas.android.com/apk/res/android" >
<set
android:ordering="sequentially" >
<objectAnimator
android:duration="183"
android:propertyName="scaleX"
android:valueFrom="1.0"
android:valueTo="0.9"
android:valueType="floatType"
android:interpolator="@android:interpolator/fast_out_slow_in" />
<objectAnimator
android:duration="16"
android:propertyName="scaleX"
android:valueFrom="0.9"
android:valueTo="0.5"
android:valueType="floatType"
android:interpolator="@interpolator/btn_radio_to_off_mtrl_animation_interpolator_0" />
<objectAnimator
android:duration="300"
android:propertyName="scaleX"
android:valueFrom="0.5"
android:valueTo="1.0"
android:valueType="floatType"
android:interpolator="@interpolator/btn_radio_to_off_mtrl_animation_interpolator_0" />
</set>
<set
android:ordering="sequentially" >
<objectAnimator
android:duration="183"
android:propertyName="scaleY"
android:valueFrom="1.0"
android:valueTo="0.9"
android:valueType="floatType"
android:interpolator="@android:interpolator/fast_out_slow_in" />
<objectAnimator
android:duration="16"
android:propertyName="scaleY"
android:valueFrom="0.9"
android:valueTo="0.5"
android:valueType="floatType"
android:interpolator="@interpolator/btn_radio_to_off_mtrl_animation_interpolator_0" />
<objectAnimator
android:duration="300"
android:propertyName="scaleY"
android:valueFrom="0.5"
android:valueTo="1.0"
android:valueType="floatType"
android:interpolator="@interpolator/btn_radio_to_off_mtrl_animation_interpolator_0" />
</set>
</set>
|
{
"pile_set_name": "Github"
}
|
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Hardware.Camera2;
using Android.Graphics;
using Android.Hardware.Camera2.Params;
using Android.Media;
using Camera2Basic;
using Camera2Basic.Listeners;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Java.IO;
using Java.Lang;
using Java.Util;
using Java.Util.Concurrent;
using Boolean = Java.Lang.Boolean;
using Math = Java.Lang.Math;
using Orientation = Android.Content.Res.Orientation;
using System.Collections.Generic;
using Size = Android.Util.Size;
using Point = Android.Graphics.Point;
using System;
using ConferenceVision.Services;
[assembly: ExportRenderer(typeof(ConferenceVision.Views.Renderers.CameraPreview), typeof(ConferenceVision.Droid.Renderers.CameraPreviewRenderer))]
namespace ConferenceVision.Droid.Renderers
{
public class CameraPreviewRenderer : ViewRenderer<Views.Renderers.CameraPreview, AutoFitTextureView>, ICamera2Basic
{
private static readonly SparseIntArray ORIENTATIONS = new SparseIntArray();
public static readonly int REQUEST_CAMERA_PERMISSION = 1;
// Tag for the {@link Log}.
private static readonly string TAG = "Camera2BasicFragment";
// Max preview width that is guaranteed by Camera2 API
private static readonly int MAX_PREVIEW_WIDTH = 1920;
// Max preview height that is guaranteed by Camera2 API
private static readonly int MAX_PREVIEW_HEIGHT = 1080;
// TextureView.ISurfaceTextureListener handles several lifecycle events on a TextureView
private Camera2BasicSurfaceTextureListener mSurfaceTextureListener;
// ID of the current {@link CameraDevice}.
private string mCameraId;
// An AutoFitTextureView for camera preview
private AutoFitTextureView mTextureView;
// A {@link CameraCaptureSession } for camera preview.
public CameraCaptureSession mCaptureSession { get; set; }
// A reference to the opened CameraDevice
public CameraDevice mCameraDevice { get; set; }
// The size of the camera preview
private Size mPreviewSize;
// CameraDevice.StateListener is called when a CameraDevice changes its state
private CameraStateListener mStateCallback;
// An additional thread for running tasks that shouldn't block the UI.
private HandlerThread mBackgroundThread;
// A {@link Handler} for running tasks in the background.
public Handler mBackgroundHandler { get; set; }
// An {@link ImageReader} that handles still image capture.
private ImageReader mImageReader;
// This is the output file for our picture.
public File mFile;
// This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
// still image is ready to be saved.
private ImageAvailableListener mOnImageAvailableListener;
//{@link CaptureRequest.Builder} for the camera preview
public CaptureRequest.Builder mPreviewRequestBuilder { get; set; }
// {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
public CaptureRequest mPreviewRequest { get; set; }
// The current state of camera state for taking pictures.
public Camera2BasicState mState { get; set; } = Camera2BasicState.STATE_PREVIEW;
// A {@link Semaphore} to prevent the app from exiting before closing the camera.
public Semaphore mCameraOpenCloseLock { get; set; } = new Semaphore(1);
// Whether the current camera device supports Flash or not.
private bool mFlashSupported;
// Orientation of the camera sensor
private int mSensorOrientation;
// A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture.
public CameraCaptureListener mCaptureCallback { get; set; }
public Activity Activity { get; set; }
byte[] imageBytes;
public CameraPreviewRenderer(Context context) : base(context)
{
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90);
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0);
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270);
ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180);
}
Android.Views.View view;
protected override void OnElementChanged(ElementChangedEventArgs<Views.Renderers.CameraPreview> e)
{
if (Xamarin.Forms.DesignMode.IsDesignModeEnabled)
{
return;
}
if (e.OldElement != null) // Clear old element event
{
}
if (e.NewElement != null)
{
e.NewElement.StartRecording = (() => { TakePicture(); });
e.NewElement.StopRecording = (() => { CloseCamera(); });
if (Control == null)
{
Activity = this.Context as Activity;
SetNativeControl(new AutoFitTextureView(Context));
}
mTextureView = Control as AutoFitTextureView;
mStateCallback = new CameraStateListener(this);
mSurfaceTextureListener = new Camera2BasicSurfaceTextureListener(this);
//mFile = new File(Activity.GetExternalFilesDir(null), $"{Element.Filename}.jpg");
//var path = System.IO.Path.Combine(
// System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments),
// $"{Element.Filename}"
//);
var path = System.IO.Path.Combine(
DependencyService.Get<IMediaFolder>().Path,
Element.Filename);
mFile = new File(
path
);
mCaptureCallback = new CameraCaptureListener(this);
mOnImageAvailableListener = new ImageAvailableListener(this, mFile);
StartTheCamera();
}
base.OnElementChanged(e);
}
private void StartTheCamera()
{
StartBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.IsAvailable)
{
OpenCamera(mTextureView.Width, mTextureView.Height);
}
else
{
mTextureView.SurfaceTextureListener = mSurfaceTextureListener;
}
}
public void OnCaptureComplete()
{
var exists = mFile.Exists();
if (exists)
{
Element.OnMediaSaved(
$"{Element.Filename}",
string.Empty,
isLandscape(),
0);
}
}
bool isLandscape()
{
var orientation = Resources.Configuration.Orientation;
return orientation == Orientation.Landscape;
}
private static Size ChooseOptimalSize(Size[] choices, int textureViewWidth,
int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio)
{
// Collect the supported resolutions that are at least as big as the preview Surface
var bigEnough = new List<Size>();
// Collect the supported resolutions that are smaller than the preview Surface
var notBigEnough = new List<Size>();
int w = aspectRatio.Width;
int h = aspectRatio.Height;
for (var i = 0; i < choices.Length; i++)
{
Size option = choices[i];
if ((option.Width <= maxWidth) && (option.Height <= maxHeight) &&
option.Height == option.Width * h / w)
{
if (option.Width >= textureViewWidth &&
option.Height >= textureViewHeight)
{
bigEnough.Add(option);
}
else
{
notBigEnough.Add(option);
}
}
}
// Pick the smallest of those big enough. If there is no one big enough, pick the
// largest of those not big enough.
if (bigEnough.Count > 0)
{
return (Size)Collections.Min(bigEnough, new CompareSizesByArea());
}
else if (notBigEnough.Count > 0)
{
return (Size)Collections.Max(notBigEnough, new CompareSizesByArea());
}
else
{
Log.Error(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
//protected override void OnLayout(bool changed, int l, int t, int r, int b)
//{
// base.OnLayout(changed, l, t, r, b);
// Control.Measure(global::Android.Views.View.MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly),
// global::Android.Views.View.MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly)
// );// measures control at the size just before layout
// Control.Layout(0, 0, r - l, b - t); // coords relative to self, at 0,0
//}
// Sets up member variables related to camera.
private void SetUpCameraOutputs(int width, int height)
{
var activity = Activity;
var manager = (CameraManager)activity.GetSystemService(Context.CameraService);
try
{
for (var i = 0; i < manager.GetCameraIdList().Length; i++)
{
var cameraId = manager.GetCameraIdList()[i];
CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
var facing = (Integer)characteristics.Get(CameraCharacteristics.LensFacing);
if (facing != null && facing == (Integer.ValueOf((int)LensFacing.Front)))
{
continue;
}
var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
if (map == null)
{
continue;
}
// For still image captures, we use the largest available size.
Size largest = (Size)Collections.Max(Arrays.AsList(map.GetOutputSizes((int)ImageFormatType.Jpeg)),
new CompareSizesByArea());
mImageReader = ImageReader.NewInstance(largest.Width, largest.Height, ImageFormatType.Jpeg, /*maxImages*/2);
mImageReader.SetOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
// Find out if we need to swap dimension to get the preview size relative to sensor
// coordinate.
var displayRotation = activity.WindowManager.DefaultDisplay.Rotation;
//noinspection ConstantConditions
mSensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation);
bool swappedDimensions = false;
switch (displayRotation)
{
case SurfaceOrientation.Rotation0:
case SurfaceOrientation.Rotation180:
if (mSensorOrientation == 90 || mSensorOrientation == 270)
{
swappedDimensions = true;
}
break;
case SurfaceOrientation.Rotation90:
case SurfaceOrientation.Rotation270:
if (mSensorOrientation == 0 || mSensorOrientation == 180)
{
swappedDimensions = true;
}
break;
default:
Log.Error(TAG, "Display rotation is invalid: " + displayRotation);
break;
}
Point displaySize = new Point();
activity.WindowManager.DefaultDisplay.GetSize(displaySize);
var rotatedPreviewWidth = width;
var rotatedPreviewHeight = height;
var maxPreviewWidth = displaySize.X;
var maxPreviewHeight = displaySize.Y;
if (swappedDimensions)
{
rotatedPreviewWidth = height;
rotatedPreviewHeight = width;
maxPreviewWidth = displaySize.Y;
maxPreviewHeight = displaySize.X;
}
if (maxPreviewWidth > MAX_PREVIEW_WIDTH)
{
maxPreviewWidth = MAX_PREVIEW_WIDTH;
}
if (maxPreviewHeight > MAX_PREVIEW_HEIGHT)
{
maxPreviewHeight = MAX_PREVIEW_HEIGHT;
}
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
mPreviewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))),
rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
maxPreviewHeight, largest);
// We fit the aspect ratio of TextureView to the size of preview we picked.
var orientation = Resources.Configuration.Orientation;
if (orientation == Orientation.Landscape)
{
mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
}
else
{
mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
}
// Check if the flash is supported.
var available = (Boolean)characteristics.Get(CameraCharacteristics.FlashInfoAvailable);
if (available == null)
{
mFlashSupported = false;
}
else
{
mFlashSupported = (bool)available;
}
mCameraId = cameraId;
return;
}
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
catch (NullPointerException e)
{
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
//ErrorDialog.NewInstance(GetString(Resource.String.camera_error)).Show(ChildFragmentManager, FRAGMENT_DIALOG);
}
}
// Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
public void OpenCamera(int width, int height)
{
SetUpCameraOutputs(width, height);
ConfigureTransform(width, height);
var activity = Activity;
var manager = (CameraManager)activity.GetSystemService(Context.CameraService);
try
{
if (!mCameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds))
{
throw new RuntimeException("Time out waiting to lock camera opening.");
}
if (!string.IsNullOrEmpty(mCameraId))
manager.OpenCamera(mCameraId, mStateCallback, mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
catch (InterruptedException e)
{
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
// Closes the current {@link CameraDevice}.
private void CloseCamera()
{
if (mCaptureSession == null)
return;
try
{
mCameraOpenCloseLock.Acquire();
if (null != mCaptureSession)
{
try
{
mCaptureSession.StopRepeating();
mCaptureSession.AbortCaptures();
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
catch (IllegalStateException e)
{
e.PrintStackTrace();
}
mCaptureSession.Close();
mCaptureSession = null;
}
if (null != mCameraDevice)
{
mCameraDevice.Close();
mCameraDevice = null;
}
if (null != mImageReader)
{
mImageReader.Close();
mImageReader = null;
}
}
catch (InterruptedException e)
{
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
}
finally
{
mCameraOpenCloseLock.Release();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
CloseCamera();
StopBackgroundThread();
if (Element != null)
{
Element.StartRecording = null;
Element.StopRecording = null;
}
}
base.Dispose(disposing);
}
// Starts a background thread and its {@link Handler}.
private void StartBackgroundThread()
{
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.Start();
mBackgroundHandler = new Handler(mBackgroundThread.Looper);
}
// Stops the background thread and its {@link Handler}.
private void StopBackgroundThread()
{
if (mBackgroundThread == null)
return;
mBackgroundThread.QuitSafely();
try
{
mBackgroundThread.Join();
mBackgroundThread = null;
mBackgroundHandler = null;
}
catch (InterruptedException e)
{
e.PrintStackTrace();
}
}
// Creates a new {@link CameraCaptureSession} for camera preview.
public void CreateCameraPreviewSession()
{
try
{
SurfaceTexture texture = mTextureView.SurfaceTexture;
if (texture == null)
{
throw new IllegalStateException("texture is null");
}
// We configure the size of default buffer to be the size of camera preview we want.
texture.SetDefaultBufferSize(mPreviewSize.Width, mPreviewSize.Height);
// This is the output Surface we need to start preview.
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.Preview);
mPreviewRequestBuilder.AddTarget(surface);
// Here, we create a CameraCaptureSession for camera preview.
List<Surface> surfaces = new List<Surface>();
surfaces.Add(surface);
surfaces.Add(mImageReader.Surface);
mCameraDevice.CreateCaptureSession(surfaces, new CameraCaptureSessionCallback(this), null);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
public static T Cast<T>(Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
// Configures the necessary {@link android.graphics.Matrix}
// transformation to `mTextureView`.
// This method should be called after the camera preview size is determined in
// setUpCameraOutputs and also the size of `mTextureView` is fixed.
public void ConfigureTransform(int viewWidth, int viewHeight)
{
Activity activity = Activity;
if (null == mTextureView || null == mPreviewSize || null == activity)
{
return;
}
var rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.Height, mPreviewSize.Width);
float centerX = viewRect.CenterX();
float centerY = viewRect.CenterY();
if ((int)SurfaceOrientation.Rotation90 == rotation || (int)SurfaceOrientation.Rotation270 == rotation)
{
bufferRect.Offset(centerX - bufferRect.CenterX(), centerY - bufferRect.CenterY());
matrix.SetRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.Fill);
float scale = Math.Max((float)viewHeight / mPreviewSize.Height, (float)viewWidth / mPreviewSize.Width);
matrix.PostScale(scale, scale, centerX, centerY);
matrix.PostRotate(90 * (rotation - 2), centerX, centerY);
}
else if ((int)SurfaceOrientation.Rotation180 == rotation)
{
matrix.PostRotate(180, centerX, centerY);
}
mTextureView.SetTransform(matrix);
}
// Initiate a still image capture.
private void TakePicture()
{
//LockFocus();
CaptureStillPicture();
}
// Lock the focus as the first step for a still image capture.
private void LockFocus()
{
try
{
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Start);
// Tell #mCaptureCallback to wait for the lock.
mState = Camera2BasicState.STATE_WAITING_LOCK;
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback,
mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
// Run the precapture sequence for capturing a still image. This method should be called when
// we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
public void RunPrecaptureSequence()
{
try
{
// This is how to tell the camera to trigger.
mPreviewRequestBuilder.Set(CaptureRequest.ControlAePrecaptureTrigger, (int)ControlAEPrecaptureTrigger.Start);
// Tell #mCaptureCallback to wait for the precapture sequence to be set.
mState = Camera2BasicState.STATE_WAITING_PRECAPTURE;
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback, mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
private CaptureRequest.Builder stillCaptureBuilder;
// Capture a still picture. This method should be called when we get a response in
// {@link #mCaptureCallback} from both {@link #lockFocus()}.
public void CaptureStillPicture()
{
try
{
var activity = Activity;
if (null == activity || null == mCameraDevice)
{
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
if (stillCaptureBuilder == null)
stillCaptureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
stillCaptureBuilder.AddTarget(mImageReader.Surface);
// Use the same AE and AF modes as the preview.
stillCaptureBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture);
//SetAutoFlash(stillCaptureBuilder);
// Orientation
int rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
stillCaptureBuilder.Set(CaptureRequest.JpegOrientation, GetOrientation(rotation));
mCaptureSession.StopRepeating();
mCaptureSession.Capture(stillCaptureBuilder.Build(), new CameraCaptureStillPictureSessionCallback(this), null);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
// Retrieves the JPEG orientation from the specified screen rotation.
private int GetOrientation(int rotation)
{
// Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
// We have to take that into account and rotate JPEG properly.
// For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
// For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
return (ORIENTATIONS.Get(rotation) + mSensorOrientation + 270) % 360;
}
// Unlock the focus. This method should be called when still image capture sequence is
// finished.
public void UnlockFocus()
{
try
{
// Reset the auto-focus trigger
mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Cancel);
//SetAutoFlash(mPreviewRequestBuilder);
mCaptureSession.Capture(mPreviewRequestBuilder.Build(), mCaptureCallback,
mBackgroundHandler);
// After this, the camera will go back to the normal state of preview.
mState = Camera2BasicState.STATE_PREVIEW;
mCaptureSession.SetRepeatingRequest(mPreviewRequest, mCaptureCallback,
mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
---
# Page settings
layout: default
keywords: autocorrelation convergence mixing
comments: false
version: 0.0.24
permalink: /docs/0_0_24/autocorrelation/
# Hero section
title: Calculating Autocorrelation
description: How do you calculate the autocorrelation of your samples?
# Micro navigation
micro_nav: true
# Page navigation
page_nav:
prev:
content: Previous page
url: '/docs/0_0_24/sequences/'
next:
content: Next page
url: '/docs/0_0_24/save-and-load/'
---
## Autocorrelation
Autocorrelation is a useful statistic for assessing mixing of a Markov chain. Keanu provides a method of
calculating autocorrelation on samples.
### Example
#### Java
With a network defined, we can get the autocorrelation vertex A. The result is
a tensor containing the autocorrelation at varying lags.
```java
NetworkSamples posteriorSamples = Keanu.Sampling.MetropolisHastings.withDefaultConfig().getPosteriorSamples(
model,
model.getLatentVariables(),
100
);
DoubleTensor autocorrelation = posteriorSamples.getDoubleTensorSamples(A).getAutocorrelation();
```
When the samples are tensors, we need to specify the tensor index on which to calculate the autocorrelation.
For example, if the sample shape is `[1,5]` we can evaluate the autocorrelation at index `[0,1]`.
```java
NetworkSamples posteriorSamples = Keanu.Sampling.MetropolisHastings.withDefaultConfig().getPosteriorSamples(
model,
model.getLatentVariables(),
100
);
DoubleTensor autocorrelation = posteriorSamples.getDoubleTensorSamples(A).getAutocorrelation(0, 1);
```
#### Python
It's also possible to calculate the autocorrelation of samples in Python.
```python
algo = MetropolisHastingsSampler(proposal_distribution='prior', latents=bayes_net.iter_latent_vertices())
posterior_samples = sample(net=bayes_net, sample_from=bayes_net.iter_latent_vertices(),
sampling_algorithm=algo, draws=100)
vertex_samples = posterior_samples.get('a')
ac = stats.autocorrelation(vertex_samples)
```
When the samples are `ndarrays` the index on which to calculate the autocorrelation can be specified
as a tuple.
```python
algo = MetropolisHastingsSampler(proposal_distribution='prior', latents=bayes_net.iter_latent_vertices())
posterior_samples = sample(net=bayes_net, sample_from=bayes_net.iter_latent_vertices(),
sampling_algorithm=algo, draws=100)
vertex_samples = posterior_samples.get(('a', (0, 1)))
ac = stats.autocorrelation(vertex_samples)
```
|
{
"pile_set_name": "Github"
}
|
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-secure.json#",
"title": "Meta-schema for the security assessment of JSON Schemas",
"description": "If a JSON Schema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": {"$ref": "#"}
}
},
"dependencies": {
"patternProperties": {
"description": "prevent slow validation of large property names",
"required": ["propertyNames"],
"properties": {
"propertyNames": {
"required": ["maxLength"]
}
}
},
"uniqueItems": {
"description": "prevent slow validation of large non-scalar arrays",
"if": {
"properties": {
"uniqueItems": {"const": true},
"items": {
"properties": {
"type": {
"anyOf": [
{
"enum": ["object", "array"]
},
{
"type": "array",
"contains": {"enum": ["object", "array"]}
}
]
}
}
}
}
},
"then": {
"required": ["maxItems"]
}
},
"pattern": {
"description": "prevent slow pattern matching of large strings",
"required": ["maxLength"]
},
"format": {
"description": "prevent slow format validation of large strings",
"required": ["maxLength"]
}
},
"properties": {
"additionalItems": {"$ref": "#"},
"additionalProperties": {"$ref": "#"},
"dependencies": {
"additionalProperties": {
"anyOf": [
{"type": "array"},
{"$ref": "#"}
]
}
},
"items": {
"anyOf": [
{"$ref": "#"},
{"$ref": "#/definitions/schemaArray"}
]
},
"definitions": {
"additionalProperties": {"$ref": "#"}
},
"patternProperties": {
"additionalProperties": {"$ref": "#"}
},
"properties": {
"additionalProperties": {"$ref": "#"}
},
"if": {"$ref": "#"},
"then": {"$ref": "#"},
"else": {"$ref": "#"},
"allOf": {"$ref": "#/definitions/schemaArray"},
"anyOf": {"$ref": "#/definitions/schemaArray"},
"oneOf": {"$ref": "#/definitions/schemaArray"},
"not": {"$ref": "#"},
"contains": {"$ref": "#"},
"propertyNames": {"$ref": "#"}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace Microsoft.VisualStudio.FSharp.Editor.Tests.Roslyn
open System
open NUnit.Framework
open Microsoft.VisualStudio.FSharp.Editor
open FSharp.Compiler.Text
open Microsoft.CodeAnalysis.Text
[<TestFixture>]
module RoslynSourceTextTests =
[<Test>]
let SourceText () =
let text = "test\ntest2\r\ntest3\n\ntest4\ntest5\rtest6\n"
let sourceText = SourceText.From(text).ToFSharpSourceText()
Assert.AreEqual("test", sourceText.GetLineString(0))
Assert.AreEqual("test2", sourceText.GetLineString(1))
Assert.AreEqual("test3", sourceText.GetLineString(2))
Assert.AreEqual("", sourceText.GetLineString(3))
Assert.AreEqual("test4", sourceText.GetLineString(4))
Assert.AreEqual("test5", sourceText.GetLineString(5))
Assert.AreEqual("test6", sourceText.GetLineString(6))
Assert.AreEqual("", sourceText.GetLineString(7))
Assert.AreEqual(8, sourceText.GetLineCount())
let (count, length) = sourceText.GetLastCharacterPosition()
Assert.AreEqual(8, count)
Assert.AreEqual(0, length)
Assert.True(sourceText.SubTextEquals("test", 0))
Assert.True(sourceText.SubTextEquals("test2", 5))
Assert.True(sourceText.SubTextEquals("test3", 12))
Assert.Throws<ArgumentException>(fun () -> sourceText.SubTextEquals("test", -1) |> ignore) |> ignore
Assert.Throws<ArgumentException>(fun () -> sourceText.SubTextEquals("test", text.Length) |> ignore) |> ignore
Assert.Throws<ArgumentException>(fun () -> sourceText.SubTextEquals("", 0) |> ignore) |> ignore
Assert.Throws<ArgumentException>(fun () -> sourceText.SubTextEquals(text + text, 0) |> ignore) |> ignore
Assert.False(sourceText.SubTextEquals("test", 1))
Assert.False(sourceText.SubTextEquals("test", 4))
Assert.False(sourceText.SubTextEquals("test", 11))
|
{
"pile_set_name": "Github"
}
|
<template>
<div>
<van-tabs :active="activeNav" @change="changeTab">
<van-tab v-for="nav in navList" :title="nav.name" v-bind:key="nav.id">
</van-tab>
</van-tabs>
<swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1000">
<block v-for="(item, index) in banners" :index="index" :key="key">
<swiper-item>
<navigator :url="item.url">
<image :src="item.imgUrl" class="slide-image" mode="aspectFill"/>
</navigator>
</swiper-item>
</block>
</swiper>
<van-card v-for="(goods,index) in goodsList" :key="index"
:num="goods.num"
:price="goods.price"
:desc="goods.descript"
:title="goods.name"
:thumb="goods.imgUrl"
@click="viewGoodsDetail(goods.id)"
/>
</div>
</template>
<script>
import card from '@/components/card'
import utils from '@/utils/index.js'
export default {
config: {
navigationBarTitleText: '邻家小铺'
},
data() {
return {
banners: [],
navList: [],
goodsList: [],
activeNav: 0,
listQuery: {
page: 1,
limit: 20,
idCategory: undefined
}
}
},
components: {
card
},
methods: {
changeTab(event) {
const index = event.mp.detail.index
const idCategory = this.navList[index].id
this.listQuery.idCategory = idCategory
this.banners = this.processBanners(this.navList[index].bannerList)
this.getGoodsList()
},
getGoodsList() {
this.$API.get('/goods/queryGoods?page=' + this.listQuery.page + '&limit=' + this.listQuery.limit + '&idCategory=' + this.listQuery.idCategory, this.listQuery).then(res => {
let goodsList = res.data.records
for (let i = 0; i < goodsList.length; i++) {
goodsList[i].price = utils.formatPrice(goodsList[i].price)
goodsList[i].imgUrl = utils.fileMgrUrl + goodsList[i].pic
}
this.goodsList = goodsList
})
},
viewGoodsDetail(id) {
const url = '../goods/index?id=' + id
wx.navigateTo({url})
},
processBanners(banners) {
for (let i = 0; i < banners.length; i++) {
let url = ''
let page = banners[i].page
let param = banners[i].param
if (!utils.startWith(page, 'http')) {
url = '../' + page + '/index'
}
if (param !== '') {
const paramJson = JSON.parse(param)
let i = 0
for (const key in paramJson) {
if (i === 0) {
url += '?' + key + '=' + paramJson[key]
} else {
url += '&' + key + '=' + paramJson[key]
}
i++
}
}
banners[i].url = url
banners[i].imgUrl = utils.fileMgrUrl + banners[i].idFile
}
return banners
}
},
created() {
// let app = getApp()
},
onLoad() {
this.$API.get('/category/list').then(res => {
this.navList = res.data
this.banners = this.processBanners(res.data[0].bannerList)
this.listQuery.idCategory = res.data[0].id
this.getGoodsList()
}).catch(e => {
console.log('e', e)
})
}
}
</script>
<style>
swiper {
height: 220px;
}
swiper-item > navigator > image {
width: 100%;
}
</style>
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
#import <RunningBoard/RBBundleProperties-Protocol.h>
@class NSDictionary, NSString, NSURL;
@interface RBLSBundleProperties : NSObject <RBBundleProperties>
{
BOOL _backgroundRefreshEnabled;
BOOL _hasPreferredJetsamBand;
BOOL _supportsBackgroundContentFetching;
BOOL _supportsBackgroundNetworkAuthentication;
BOOL _supportsBackgroundAudio;
BOOL _supportsUnboundedTaskCompletion;
BOOL _usesSocketMonitoring;
BOOL _isExtension;
int _preferredJetsamBand;
NSString *_identifier;
NSString *_path;
NSString *_executablePath;
NSString *_extensionPointIdentifier;
NSURL *_dataContainerURL;
NSDictionary *_environmentVariables;
}
- (void).cxx_destruct;
@property(readonly, nonatomic) BOOL isExtension; // @synthesize isExtension=_isExtension;
@property(readonly, nonatomic) BOOL usesSocketMonitoring; // @synthesize usesSocketMonitoring=_usesSocketMonitoring;
@property(readonly, nonatomic) BOOL supportsUnboundedTaskCompletion; // @synthesize supportsUnboundedTaskCompletion=_supportsUnboundedTaskCompletion;
@property(readonly, nonatomic) BOOL supportsBackgroundAudio; // @synthesize supportsBackgroundAudio=_supportsBackgroundAudio;
@property(readonly, nonatomic) BOOL supportsBackgroundNetworkAuthentication; // @synthesize supportsBackgroundNetworkAuthentication=_supportsBackgroundNetworkAuthentication;
@property(readonly, nonatomic) BOOL supportsBackgroundContentFetching; // @synthesize supportsBackgroundContentFetching=_supportsBackgroundContentFetching;
@property(readonly, nonatomic) int preferredJetsamBand; // @synthesize preferredJetsamBand=_preferredJetsamBand;
@property(readonly, nonatomic) BOOL hasPreferredJetsamBand; // @synthesize hasPreferredJetsamBand=_hasPreferredJetsamBand;
@property(readonly, nonatomic) NSDictionary *environmentVariables; // @synthesize environmentVariables=_environmentVariables;
@property(readonly, nonatomic) NSURL *dataContainerURL; // @synthesize dataContainerURL=_dataContainerURL;
@property(readonly, nonatomic, getter=isBackgroundRefreshEnabled) BOOL backgroundRefreshEnabled; // @synthesize backgroundRefreshEnabled=_backgroundRefreshEnabled;
@property(readonly, copy, nonatomic) NSString *extensionPointIdentifier;
@property(readonly, copy, nonatomic) NSString *executablePath;
@property(readonly, copy, nonatomic) NSString *bundlePath;
@property(readonly, copy, nonatomic) NSString *bundleIdentifier;
- (id)bundleInfoValuesForKeys:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
{
"pile_set_name": "Github"
}
|
/**** (c) Valve Corporation. Use is governed by the terms of the Steam Subscriber Agreement http://store.steampowered.com/subscriber_agreement/.
****/
(window.webpackJsonp = window.webpackJsonp || []).push([
[7],
{
"3WEt": function(e, t, a) {
"use strict";
a.r(t);
var o,
i,
u = a("mrSG"),
r = a("lkRc"),
n = a("TyAF"),
s = a("2vnA"),
c = a("q1tI"),
P = a.n(c),
U = a("Ophz"),
w = a("6Y59"),
M = a("exH9"),
x = a("TLQK"),
l = a("bxiW"),
F = a("Asqs"),
d = a("1h/R"),
m = a.n(d),
p = a("vDqi"),
_ = a.n(p);
((i = o = o || {})[(i.Unrequested = 0)] = "Unrequested"),
(i[(i.Pending = 1)] = "Pending"),
(i[(i.Valid = 2)] = "Valid"),
(i[(i.Failed = 3)] = "Failed"),
(i[(i.Rerequest = 4)] = "Rerequest");
var h,
g,
v = (function() {
function e() {
(this.eState = o.Unrequested), (this.nExpirationTime = 0);
}
return (
(e.prototype.getData = function(t, a, i) {
var n = this,
r = Date.now() / 1e3,
e = this.eState == o.Pending || this.eState == o.Rerequest;
return (
r >= this.nExpirationTime &&
!e &&
((this.eState = o.Pending),
a().then(function(e) {
return n.eState == o.Rerequest
? (n.expireData(), void n.getData(t, a, i))
: void (e
? ((n.data = i ? i(e) : e),
(n.nExpirationTime = r + t),
(n.eState = o.Valid))
: (n.eState = o.Failed));
})),
this.data
);
}),
(e.prototype.clearData = function() {
var e = Date.now() / 1e3;
(this.eState = o.Unrequested),
(this.data = null),
(this.nExpirationTime = e);
}),
(e.prototype.expireData = function() {
var e = Date.now() / 1e3;
this.nExpirationTime = e;
}),
(e.prototype.isExpired = function() {
var e = Date.now() / 1e3;
return this.nExpirationTime < e;
}),
(e.prototype.delayNewData = function(e) {
var t = Date.now() / 1e3;
this.nExpirationTime = t + e;
}),
(e.prototype.rerequestDataIfPending = function() {
this.eState == o.Pending && (this.eState = o.Rerequest);
}),
Object(u.c)([s.C], e.prototype, "data", void 0),
Object(u.c)([s.C], e.prototype, "nExpirationTime", void 0),
e
);
})(),
k = {
EUNIVERSE: 0,
WEB_UNIVERSE: "",
LANGUAGE: "english",
BASE_URL: "",
COMMUNITY_BASE_URL: "",
STORE_BASE_URL: "",
RELATIVE_URL: "",
IMG_URL: "",
IMG_URL_BASE: "",
CDN_URL: "",
RENDER_TIMESTAMP: 0,
EXPLORE_URL: "",
ACCOUNT_ID: 0,
STEAM_ID: "",
SESSION_ID: "",
LOGIN_REDIRECT: "",
AVATAR_URL: "",
PERSONA_NAME: "",
LINK_PARAM: "",
NUM_POPULARITY_STEPS: 0,
NUM_RECENCY_STEPS: 0,
MAX_PLAYED_GAMES: 0,
RESET_OPTIONS: !1,
INCLUDE_PLAYED: !1,
ALGORITHM: 0,
REINFERENCE: !1,
MODEL_VERSION: 0,
PERSISTENT_IGNORE: !1,
DEFAULT_RECENCY_SLIDER: 0,
DEFAULT_POPULARITY_SLIDER: 0,
DEFAULT_INCLUDED_TAGS: [],
DEFAULT_EXCLUDED_TAGS: [],
DEFAULT_IGNORED_PLAYED_APPS: [],
EXCLUDE_WISHLIST: !1,
USE_MICROTRAILERS: !1
};
((g = h = h || {})[(g.ClickThrough = 1)] = "ClickThrough"),
(g[(g.AddToWishlist = 2)] = "AddToWishlist"),
(g[(g.AddToCart = 3)] = "AddToCart");
var V = new ((function() {
function e() {
var e = this;
(this.m_rgFilterTags = []),
(this.m_rgExcludeTags = []),
(this.m_rgSavedFilterTags = []),
(this.m_rgSavedExcludeTags = []),
(this.m_mapAppDetailsCache = new Map()),
(this.m_ResultDataCache = new v()),
(this.m_InputAppsCache = new v()),
(this.m_TagsCache = new v()),
(this.m_TagNameMap = new Map()),
(this.m_fPopularityValue = window.history.state
? window.history.state.popularity
: 0.25),
(this.m_fRecencyValue = window.history.state
? window.history.state.recency
: 0),
(this.m_bExcludeWishlisted =
!!window.history.state && window.history.state.excludewishlisted),
(this.m_fQueuedPopularityValue = this.m_fPopularityValue),
(this.m_fQueuedRecencyValue = this.m_fRecencyValue),
(this.m_bStateUpdated = !1),
(this.m_bShouldMute = !0),
(this.m_bIgnoredEdited = !1),
(this.m_bUseMicrotrailers = !1),
setInterval(function() {
e.m_bStateUpdated &&
(window.history.replaceState(
{
popularity: e.m_fPopularityValue,
recency: e.m_fRecencyValue,
excludewishlisted: e.m_bExcludeWishlisted
},
""
),
(e.m_bStateUpdated = !1));
}, 1e3),
setInterval(function() {
(e.m_fPopularityValue == e.m_fQueuedPopularityValue &&
e.m_fQueuedRecencyValue == e.m_fRecencyValue) ||
((e.m_fPopularityValue = e.m_fQueuedPopularityValue),
(e.m_fRecencyValue = e.m_fQueuedRecencyValue),
(e.m_bStateUpdated = !0));
}, 400);
}
return (
(e.prototype.Init = function() {
(this.m_fPopularityValue = k.DEFAULT_POPULARITY_SLIDER),
(this.m_fRecencyValue = k.DEFAULT_RECENCY_SLIDER),
(this.m_rgSavedExcludeTags = Object(u.g)(
k.DEFAULT_EXCLUDED_TAGS
)),
(this.m_rgSavedFilterTags = Object(u.g)(k.DEFAULT_INCLUDED_TAGS)),
(this.m_rgExcludeTags = Object(u.g)(this.m_rgSavedExcludeTags)),
(this.m_rgFilterTags = Object(u.g)(this.m_rgSavedFilterTags)),
(this.m_fQueuedPopularityValue = this.m_fPopularityValue),
(this.m_fQueuedRecencyValue = this.m_fRecencyValue),
(this.m_bExcludeWishlisted = !1),
(this.m_bStateUpdated = !0),
(this.m_bExcludeWishlisted = k.EXCLUDE_WISHLIST),
(this.m_bUseMicrotrailers = k.USE_MICROTRAILERS);
}),
(e.prototype.getDetails = function(t) {
var e = this;
return (
this.m_mapAppDetailsCache.has(t) ||
this.m_mapAppDetailsCache.set(t, new v()),
this.m_mapAppDetailsCache.get(t).getData(
60,
function() {
return Object(u.b)(e, void 0, void 0, function() {
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return [
4,
_.a.get(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/details?appid=" +
t +
"&sessionid=" +
k.SESSION_ID
)
];
case 1:
return [2, e.sent()];
}
});
});
},
function(e) {
return e.data;
}
)
);
}),
(e.prototype.getResults = function(e, t, a, i) {
var n = this,
r = e ? "1" : "0",
o = t ? "" + t : "0",
s = a ? "1" : "0",
c = i ? "" + i : "0",
l = "",
d = this.getInputApps();
if (d) {
var m = [];
return (
Object.keys(d).map(function(e) {
(d[e].i || d[e].ip) && m.push(d[e].a);
}),
0 < m.length && (l = "&ignored=" + m.join()),
this.m_ResultDataCache.getData(
9999999,
function() {
return Object(u.b)(n, void 0, void 0, function() {
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return [
4,
_.a.get(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/results?sessionid=" +
k.SESSION_ID +
"&steamid=" +
k.STEAM_ID +
"&include_played=" +
r +
"&algorithm=" +
o +
"&reinference=" +
s +
"&model_version=" +
c +
l
)
];
case 1:
return [2, e.sent()];
}
});
});
},
function(e) {
return e.data;
}
)
);
}
}),
(e.prototype.areResultsExpired = function() {
return this.m_ResultDataCache.isExpired();
}),
(e.prototype.getRecommendations = function() {
var e = V.getResults(
k.INCLUDE_PLAYED,
k.ALGORITHM,
k.REINFERENCE,
k.MODEL_VERSION
);
return e ? e.recommendations : void 0;
}),
(e.prototype.getInputApps = function() {
var e = this;
return this.m_InputAppsCache.getData(
9999999,
function() {
return Object(u.b)(e, void 0, void 0, function() {
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return [
4,
_.a.get(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/inputs?sessionid=" +
k.SESSION_ID +
"&steamid=" +
k.STEAM_ID
)
];
case 1:
return [2, e.sent()];
}
});
});
},
function(e) {
return e.data;
}
);
}),
(e.prototype.getAppInfo = function() {
var e = V.getResults(
k.INCLUDE_PLAYED,
k.ALGORITHM,
k.REINFERENCE,
k.MODEL_VERSION
);
return e ? e.app_info : void 0;
}),
(e.prototype.getTags = function() {
var n = this;
return this.m_TagsCache.getData(
9999999,
function() {
return Object(u.b)(n, void 0, void 0, function() {
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return [
4,
_.a.get(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/tags?sessionid=" +
k.SESSION_ID
)
];
case 1:
return [2, e.sent()];
}
});
});
},
function(e) {
n.m_TagNameMap.clear();
for (var t = 0, a = e.data; t < a.length; t++) {
var i = a[t];
n.m_TagNameMap.set(i.tagid, i.name);
}
return e.data;
}
);
}),
(e.prototype.getTagName = function(e) {
return this.getTags(), this.m_TagNameMap.get(e);
}),
(e.prototype.getTagHeight = function() {
return Math.max(
this.m_rgFilterTags.length,
this.m_rgExcludeTags.length
);
}),
(e.prototype.onPopularityChanged = function(e) {
this.m_fQueuedPopularityValue = Number(e.target.value);
}),
(e.prototype.onRecencyChanged = function(e) {
this.m_fQueuedRecencyValue = Number(e.target.value);
}),
(e.prototype.onTagFilterAdd = function(e) {
this.m_rgFilterTags.push(e), (this.m_bStateUpdated = !0);
}),
(e.prototype.onTagFilterRemove = function(e) {
for (var t = 0; t < this.m_rgFilterTags.length; t++)
if (this.m_rgFilterTags[t] == e) {
this.m_rgFilterTags.splice(t, 1);
break;
}
this.m_bStateUpdated = !0;
}),
(e.prototype.onTagExcludeAdd = function(e) {
this.m_rgExcludeTags.push(e), (this.m_bStateUpdated = !0);
}),
(e.prototype.onTagExcludeRemove = function(e) {
for (var t = 0; t < this.m_rgExcludeTags.length; t++)
if (this.m_rgExcludeTags[t] == e) {
this.m_rgExcludeTags.splice(t, 1);
break;
}
this.m_bStateUpdated = !0;
}),
(e.prototype.doTagsPassFilter = function(e) {
for (var t = 0, a = this.m_rgFilterTags; t < a.length; t++) {
var i = a[t];
if (-1 == e.indexOf(i)) return !1;
}
return !0;
}),
(e.prototype.doTagsFailExclusion = function(e) {
for (var t = 0, a = this.m_rgExcludeTags; t < a.length; t++) {
var i = a[t];
if (-1 != e.indexOf(i)) return !0;
}
return !1;
}),
(e.prototype.onExcludeWishlistedToggled = function(e) {
(this.m_bExcludeWishlisted = !this.m_bExcludeWishlisted),
(this.m_bStateUpdated = !0);
}),
(e.prototype.onSaveUserSettings = function(e) {
return Object(u.b)(this, void 0, void 0, function() {
var t, a, i, n, r, o;
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
for (
t = [], a = this.getInputApps(), i = 0, n = a;
i < n.length;
i++
)
((r = n[i]).i || r.ip) && t.push(r.a);
return this.m_fRecencyValue != k.DEFAULT_RECENCY_SLIDER ||
this.m_fPopularityValue != k.DEFAULT_POPULARITY_SLIDER ||
this.m_rgFilterTags
.slice()
.sort()
.join(",") !==
this.m_rgSavedFilterTags.sort().join(",") ||
this.m_rgExcludeTags
.slice()
.sort()
.join(",") !==
this.m_rgSavedExcludeTags.sort().join(",") ||
t
.slice()
.sort()
.join(",") !==
k.DEFAULT_IGNORED_PLAYED_APPS.sort().join(",") ||
this.m_bExcludeWishlisted != k.EXCLUDE_WISHLIST
? [3, 1]
: [3, 3];
case 1:
return (
(o = {
session_id: k.SESSION_ID,
recency_position: this.m_fRecencyValue,
popularity_position: this.m_fPopularityValue,
included_tags: this.m_rgFilterTags,
excluded_tags: this.m_rgExcludeTags,
ignored_played_apps: t,
exclude_wishlist: this.m_bExcludeWishlisted
}),
(k.DEFAULT_RECENCY_SLIDER = this.m_fRecencyValue),
(k.DEFAULT_POPULARITY_SLIDER = this.m_fPopularityValue),
(k.DEFAULT_INCLUDED_TAGS = Object(u.g)(
this.m_rgFilterTags
)),
(k.DEFAULT_EXCLUDED_TAGS = Object(u.g)(
this.m_rgExcludeTags
)),
(this.m_rgSavedFilterTags = Object(u.g)(
this.m_rgFilterTags
)),
(this.m_rgSavedExcludeTags = Object(u.g)(
this.m_rgExcludeTags
)),
(k.DEFAULT_IGNORED_PLAYED_APPS = Object(u.g)(t)),
(k.EXCLUDE_WISHLIST = this.m_bExcludeWishlisted),
[
4,
_.a.post(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/savesettings",
o
)
]
);
case 2:
e.sent(), (e.label = 3);
case 3:
return [2];
}
});
});
}),
(e.prototype.onToggleIgnore = function(r) {
return Object(u.b)(this, void 0, void 0, function() {
var t, a, i, n;
return Object(u.e)(this, function(e) {
for (t = this.getInputApps(), a = 0, i = t; a < i.length; a++)
if ((n = i[a]).a == r) {
n.i || n.ip ? ((n.i = !1), (n.ip = !1)) : (n.ip = !0);
break;
}
return (
this.m_ResultDataCache.expireData(),
(this.m_bIgnoredEdited = !0),
[2]
);
});
});
}),
(e.prototype.onUpdateWithIgnored = function() {
this.m_ResultDataCache.expireData(), (this.m_bIgnoredEdited = !1);
}),
(e.prototype.onAppClicked = function(a, i) {
return Object(u.b)(this, void 0, void 0, function() {
var t;
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return (
(t = {
account_id: k.ACCOUNT_ID,
session_id: k.SESSION_ID,
app_id: a,
app_rank: i,
action: h.ClickThrough,
algorithm: 1,
setting_1: 100 * this.m_fPopularityValue,
setting_2: 100 * this.m_fRecencyValue
}),
[
4,
_.a.post(
k.BASE_URL + "recommender/" + k.STEAM_ID + "/stats",
t
)
]
);
case 1:
return e.sent(), [2];
}
});
});
}),
(e.prototype.onAddToWishlist = function(n, r) {
return Object(u.b)(this, void 0, void 0, function() {
var t, a, i;
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return (
(V.getAppInfo()[n].w = !0),
(t = { sessionid: k.SESSION_ID, appid: n }),
[
4,
_.a.post(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/wishlist?snr=" +
k.LINK_PARAM,
t
)
]
);
case 1:
return (
(a = e.sent()),
(i = {
account_id: k.ACCOUNT_ID,
session_id: k.SESSION_ID,
app_id: n,
app_rank: r,
action: h.AddToWishlist,
algorithm: 1,
setting_1: 100 * this.m_fPopularityValue,
setting_2: 100 * this.m_fRecencyValue
}),
[
4,
_.a.post(
k.BASE_URL + "recommender/" + k.STEAM_ID + "/stats",
i
)
]
);
case 2:
return e.sent(), [2, a];
}
});
});
}),
(e.prototype.onGoToWishlist = function() {
window.location.href =
k.COMMUNITY_BASE_URL + "profiles/" + k.STEAM_ID + "/wishlist";
}),
(e.prototype.onAddToCart = function(i, n) {
return Object(u.b)(this, void 0, void 0, function() {
var t, a;
return Object(u.e)(this, function(e) {
switch (e.label) {
case 0:
return (
(t = { sessionid: k.SESSION_ID, appid: i }),
[
4,
_.a.post(
k.BASE_URL +
"recommender/" +
k.STEAM_ID +
"/cart?snr=" +
k.LINK_PARAM,
t
)
]
);
case 1:
return (
e.sent(),
(a = {
account_id: k.ACCOUNT_ID,
session_id: k.SESSION_ID,
app_id: i,
app_rank: n,
action: h.AddToCart,
algorithm: 1,
setting_1: 100 * this.m_fPopularityValue,
setting_2: 100 * this.m_fRecencyValue
}),
[
4,
_.a.post(
k.BASE_URL + "recommender/" + k.STEAM_ID + "/stats",
a
)
]
);
case 2:
return (
e.sent(),
(window.location.href = r.c.STORE_BASE_URL + "cart"),
[2]
);
}
});
});
}),
(e.prototype.onMuteClicked = function() {
this.m_bShouldMute = !0;
}),
(e.prototype.onUnMuteClicked = function() {
this.m_bShouldMute = !1;
}),
(e.prototype.shouldMute = function() {
return this.m_bShouldMute;
}),
(e.prototype.shouldUseMicrotrailers = function() {
return this.m_bUseMicrotrailers;
}),
Object(u.c)([s.C], e.prototype, "m_fPopularityValue", void 0),
Object(u.c)([s.C], e.prototype, "m_fRecencyValue", void 0),
Object(u.c)([s.C], e.prototype, "m_rgFilterTags", void 0),
Object(u.c)([s.C], e.prototype, "m_rgExcludeTags", void 0),
Object(u.c)([s.C], e.prototype, "m_fQueuedPopularityValue", void 0),
Object(u.c)([s.C], e.prototype, "m_fQueuedRecencyValue", void 0),
Object(u.c)([s.C], e.prototype, "m_bExcludeWishlisted", void 0),
Object(u.c)([s.C], e.prototype, "m_bShouldMute", void 0),
Object(u.c)([s.C], e.prototype, "m_bUseMicrotrailers", void 0),
Object(u.c)([s.C], e.prototype, "m_bIgnoredEdited", void 0),
Object(u.c)([l.a], e.prototype, "getTagHeight", null),
Object(u.c)([l.a], e.prototype, "onPopularityChanged", null),
Object(u.c)([l.a], e.prototype, "onRecencyChanged", null),
Object(u.c)([l.a], e.prototype, "onTagFilterAdd", null),
Object(u.c)([l.a], e.prototype, "onTagFilterRemove", null),
Object(u.c)([l.a], e.prototype, "onTagExcludeAdd", null),
Object(u.c)([l.a], e.prototype, "onTagExcludeRemove", null),
Object(u.c)([l.a], e.prototype, "doTagsPassFilter", null),
Object(u.c)([l.a], e.prototype, "doTagsFailExclusion", null),
Object(u.c)([l.a], e.prototype, "onExcludeWishlistedToggled", null),
Object(u.c)([l.a], e.prototype, "onSaveUserSettings", null),
Object(u.c)([l.a], e.prototype, "onToggleIgnore", null),
Object(u.c)([l.a], e.prototype, "onUpdateWithIgnored", null),
Object(u.c)([l.a], e.prototype, "onAppClicked", null),
Object(u.c)([l.a], e.prototype, "onAddToWishlist", null),
Object(u.c)([l.a], e.prototype, "onGoToWishlist", null),
Object(u.c)([l.a], e.prototype, "onAddToCart", null),
Object(u.c)([l.a], e.prototype, "onMuteClicked", null),
Object(u.c)([l.a], e.prototype, "onUnMuteClicked", null),
Object(u.c)([l.a], e.prototype, "shouldMute", null),
Object(u.c)([l.a], e.prototype, "shouldUseMicrotrailers", null),
e
);
})())();
window.g_InteractiveRecommender = V;
var E,
f = a("BFsE");
(E = Object(r.f)("ir_config", "application_config")) &&
(Object.assign(k, E), V.Init());
function b(e) {
e.accountID;
var t = V.getInputApps(),
a = Object.keys(t).length,
i = 0;
return (
Object.keys(t).map(function(e) {
i += t[e].p;
}),
P.a.createElement(
"div",
{ className: F.IdentityBlock },
P.a.createElement("img", {
className: F.Avatar,
src: k.AVATAR_URL
}),
P.a.createElement(
"div",
{ className: F.PersonalInfo },
P.a.createElement(
"div",
{ className: F.Persona },
k.PERSONA_NAME
),
P.a.createElement(
"div",
{ className: F.GameCount },
Object(x.e)("#PlaytimeList_RecentGames", a)
),
P.a.createElement(
"div",
{ className: F.TotalTime },
Object(x.e)("#PlaytimeList_HoursTotal", i)
)
)
)
);
}
function S(e) {
var t = e.appID,
a = e.name,
i = e.hours,
n = e.lastPlayed,
r = e.ignored,
o = k.CDN_URL + "apps/" + t + "/header.jpg",
s = Date.now() / 1e3 - n,
c = "",
l = "",
l =
n <= 86400
? Object(x.e)("#PlaytimeList_LastPlayedMax")
: ((c = 31449600 < s ? Object(x.n)(n) : Object(x.p)(s)),
Object(x.e)("#PlaytimeList_LastPlayed", c));
return P.a.createElement(
"div",
{ className: Object(M.a)(F.PlayedGame, r && F.Ignored) },
P.a.createElement(
"a",
{ href: k.BASE_URL + "app/" + t },
P.a.createElement("img", { className: F.Logo, src: o })
),
P.a.createElement(
"div",
{ className: F.PlaytimeInfo },
P.a.createElement(
"div",
{ className: F.HoursPlayed },
Object(x.e)("#PlaytimeList_Hours", i)
),
P.a.createElement("div", { className: F.Title }, a),
P.a.createElement("div", { className: F.LastPlayed }, l),
P.a.createElement(
"div",
{
className: F.IgnoreToggle,
onClick: function() {
return V.onToggleIgnore(t);
}
},
Object(x.e)(r ? "#PlaytimeList_UnIgnore" : "#PlaytimeList_Ignore")
)
)
);
}
function y(e) {
var t = e.titleLabel,
a = e.minLabel,
i = e.maxLabel,
n = e.minValue,
r = e.maxValue,
o = e.value,
s = e.onChange,
c = e.sliderLabels,
l = c ? Math.round((c.length - 1) * ((o - n) / (r - n))) : void 0,
d = c ? c[l] : "";
return P.a.createElement(
"div",
{ className: F.OptionSlider },
P.a.createElement("div", { className: F.Title }, t),
P.a.createElement(
"div",
{ className: F.Labels },
P.a.createElement("div", { className: F.Min }, a),
P.a.createElement("div", { className: F.Max }, i)
),
P.a.createElement("input", {
type: "range",
min: n,
max: r,
step: (r - n) / 100,
value: o,
onChange: s
}),
P.a.createElement("div", { className: F.OptionalLabel }, d)
);
}
function T(e) {
var t = e.className,
a = e.titleLabel,
i = e.checked,
n = e.onChange;
return P.a.createElement(
"label",
{ className: Object(M.a)(F.OptionCheckbox, t && t) },
P.a.createElement("input", {
type: "checkbox",
className: F.Checkbox,
checked: i,
onChange: n
}),
a
);
}
var O = (function(a) {
function e(e) {
var t = a.call(this, e) || this;
return (t.state = {}), t;
}
return (
Object(u.d)(e, a),
(e.prototype.render = function() {
var e = V.getInputApps(),
a = [];
if (!e)
return P.a.createElement(
"div",
{ className: F.PlaytimeList },
P.a.createElement(
"div",
{ className: F.Header },
Object(x.e)("#PlaytimeList_Header")
),
P.a.createElement("div", { className: F.Loading })
);
V.getAppInfo();
var i = e.slice().sort(function(e, t) {
return t.l - e.l;
});
return (
Object.keys(i).map(function(e) {
var t = i[e];
a.push(
P.a.createElement(S, {
key: "PlayedGame_" + t.a,
appID: t.a,
name: t.t,
hours: t.p,
lastPlayed: t.l,
ignored: t.i || t.ip
})
);
}),
P.a.createElement(
"div",
{ className: F.PlaytimeList },
P.a.createElement(
"div",
{ className: F.Header },
Object(x.e)("#PlaytimeList_Header")
),
P.a.createElement(b, { accountID: this.props.accountID }),
P.a.createElement("div", { className: F.List }, a)
)
);
}),
(e = Object(u.c)([n.a], e))
);
})(P.a.Component),
R = (function(a) {
function e(e) {
var t = a.call(this, e) || this;
return (
(t.selectedtags = []),
(t.rgTags = []),
(t.selectedtags = Object(u.g)(e.selectedtags)),
(t.state = { value: "", suggestions: [] }),
t
);
}
return (
Object(u.d)(e, a),
(e.prototype.componentDidMount = function() {
var e = V.getTags();
if (e)
for (var t = 0, a = e; t < a.length; t++) {
var i = a[t];
this.rgTags.push({ id: parseInt(i.tagid), name: i.name });
}
}),
(e.prototype.onFetchRequested = function(e) {
var t = e.value.trim().toLowerCase(),
a = t.length,
i =
0 === a
? this.props.tagoptions.slice(0, 10)
: this.props.tagoptions.filter(function(e) {
return e.name.toLowerCase().slice(0, a) === t;
});
this.setState({ suggestions: i });
}),
(e.prototype.onClearRequested = function() {}),
(e.prototype.onChange = function(e, t) {
this.setState({ value: t.newValue });
}),
(e.prototype.onKeyDown = function(e) {
if (13 == e.keyCode)
for (var t = 0, a = this.props.tagoptions; t < a.length; t++) {
var i = a[t];
if (i.name.toLowerCase() == this.state.value.toLowerCase()) {
var n = {
suggestion: { id: i.id, name: i.name },
suggestionValue: i.name,
suggestionIndex: 0,
sectionIndex: 0,
method: "enter"
};
this.onSuggestionSelected(e, n);
break;
}
}
}),
(e.prototype.shouldRenderSuggestions = function(e) {
return !0;
}),
(e.prototype.onSuggestionSelected = function(e, t) {
for (var a = 0, i = this.selectedtags; a < i.length; a++) {
if (i[a] == t.suggestion.id) return;
}
this.selectedtags.push(t.suggestion.id),
this.props.onAddTag(t.suggestion.id);
}),
(e.prototype.onRemoveSelectedTag = function(e) {
for (var t = 0; t < this.selectedtags.length; t++)
if (this.selectedtags[t] == e) {
this.props.onRemoveTag(this.selectedtags[t]),
this.selectedtags.splice(t, 1);
break;
}
}),
(e.prototype.render = function() {
for (
var a = this,
e = {
placeholder: Object(x.e)("#TagSelect"),
value: this.state.value,
onChange: this.onChange,
onKeyDown: this.onKeyDown
},
i = [],
t = 0,
n = this.selectedtags;
t < n.length;
t++
) {
!(function(t) {
var e = V.m_TagNameMap.get(t);
i.push(
P.a.createElement(
"div",
{
key: t,
className: F.SelectedTag,
onClick: function(e) {
return a.onRemoveSelectedTag(t);
}
},
P.a.createElement("div", null, e),
P.a.createElement("div", { className: F.Close }, "X")
)
);
})(n[t]);
}
return P.a.createElement(
"div",
{ className: F.OptionTagList },
P.a.createElement(
"div",
{ className: F.Label },
this.props.title
),
P.a.createElement(m.a, {
suggestions: this.state.suggestions,
onSuggestionsFetchRequested: this.onFetchRequested,
onSuggestionsClearRequested: this.onClearRequested,
onSuggestionSelected: this.onSuggestionSelected,
shouldRenderSuggestions: this.shouldRenderSuggestions,
getSuggestionValue: function(e) {
return e.name;
},
renderSuggestion: function(e) {
return P.a.createElement("div", null, e.name);
},
inputProps: e,
theme: {
input: F.SuggestionInput,
suggestion: F.OptionSuggestion,
suggestionsList: F.SuggestionsList,
suggestionsContainerOpen: F.SuggestionContainerOpen
}
}),
i
);
}),
Object(u.c)([s.C], e.prototype, "selectedtags", void 0),
Object(u.c)([l.a], e.prototype, "onFetchRequested", null),
Object(u.c)([l.a], e.prototype, "onClearRequested", null),
Object(u.c)([l.a], e.prototype, "onChange", null),
Object(u.c)([l.a], e.prototype, "onKeyDown", null),
Object(u.c)([l.a], e.prototype, "shouldRenderSuggestions", null),
Object(u.c)([l.a], e.prototype, "onSuggestionSelected", null),
Object(u.c)([l.a], e.prototype, "onRemoveSelectedTag", null),
(e = Object(u.c)([n.a], e))
);
})(P.a.Component),
j = Object(n.a)(function() {
var e = V.getTags(),
t = [];
if (e)
for (var a = 0, i = e; a < i.length; a++) {
var n = i[a];
t.push({ id: parseInt(n.tagid), name: n.name });
}
var r = [
Object(x.e)("#FilterAge_120"),
Object(x.e)("#FilterAge_60"),
Object(x.e)("#FilterAge_36"),
Object(x.e)("#FilterAge_24"),
Object(x.e)("#FilterAge_12"),
Object(x.e)("#FilterAge_6")
],
o = V.m_rgSavedExcludeTags,
s = V.m_rgSavedFilterTags;
return P.a.createElement(
"div",
{ className: F.RecommendationOptions },
P.a.createElement(
"div",
{ className: Object(M.a)(F.Row, F.FirstRow) },
P.a.createElement(y, {
minLabel: Object(x.e)("#Popularity_Popular"),
titleLabel: Object(x.e)("#Popularity_Title"),
maxLabel: Object(x.e)("#Popularity_Niche"),
minValue: 0,
maxValue: 1,
value: V.m_fQueuedPopularityValue,
onChange: V.onPopularityChanged
}),
P.a.createElement(y, {
minLabel: Object(x.e)("#Recency_Older"),
titleLabel: Object(x.e)("#Recency_Title"),
maxLabel: Object(x.e)("#Recency_Newer"),
minValue: 0,
maxValue: 1,
value: V.m_fQueuedRecencyValue,
onChange: V.onRecencyChanged,
sliderLabels: r
})
),
P.a.createElement(
"div",
{ className: Object(M.a)(F.Row, F.SecondRow) },
P.a.createElement(R, {
title: Object(x.e)("#TagFilterMultiple_Title"),
tagoptions: t,
selectedtags: s,
key: "Filter" + s.toString(),
onAddTag: V.onTagFilterAdd,
onRemoveTag: V.onTagFilterRemove
}),
P.a.createElement(R, {
title: Object(x.e)("#TagExcludeMultiple_Title"),
tagoptions: t,
selectedtags: o,
key: "Exclude" + o.toString(),
onAddTag: V.onTagExcludeAdd,
onRemoveTag: V.onTagExcludeRemove
}),
P.a.createElement(T, {
className: F.WishlistCheckbox,
titleLabel: Object(x.e)("#ExcludeWishlisted"),
checked: V.m_bExcludeWishlisted,
onChange: V.onExcludeWishlistedToggled
}),
P.a.createElement(
"button",
{
className: F.SaveUserSettingsButton,
onClick: V.onSaveUserSettings,
title: Object(x.e)("#SaveUserSettingsTooltip")
},
Object(x.e)("#SaveUserSettings")
)
)
);
}),
D = (function(a) {
function e(e) {
var t = a.call(this, e) || this;
return (
(t.m_videoRef = P.a.createRef()),
(t.state = {
hovered: !1,
wishlisted: V.getAppInfo()[e.appID].w
}),
t
);
}
return (
Object(u.d)(e, a),
(e.prototype.componentDidMount = function() {
this.m_videoRef.current.defaultMuted = !0;
}),
(e.prototype.componentDidUpdate = function() {
var e;
this.state.hovered &&
this.m_videoRef &&
this.m_videoRef.current &&
0 == this.m_videoRef.current.currentTime &&
((e = this.m_videoRef.current.play()) &&
e.then(function() {}, function() {}));
}),
(e.prototype.OnHover = function() {
this.setState({ hovered: !0 });
}),
(e.prototype.OnUnHover = function() {
this.setState({ hovered: !1 }),
this.m_videoRef &&
this.m_videoRef.current &&
((this.m_videoRef.current.currentTime = 0),
this.m_videoRef.current.pause());
}),
(e.prototype.onMuteToggle = function(e) {
V.shouldMute()
? (V.onUnMuteClicked(),
this.m_videoRef &&
this.m_videoRef.current &&
(this.m_videoRef.current.muted = !1))
: (V.onMuteClicked(),
this.m_videoRef &&
this.m_videoRef.current &&
(this.m_videoRef.current.muted = !0)),
e.preventDefault(),
e.stopPropagation();
}),
(e.prototype.onAddToWishlist = function(e) {
V.onAddToWishlist(this.props.appID, this.props.rank),
this.setState({ wishlisted: !0 }),
e.preventDefault(),
e.stopPropagation();
}),
(e.prototype.onGoToWishlist = function(e) {
V.onGoToWishlist(), e.preventDefault(), e.stopPropagation();
}),
(e.prototype.onAddToCart = function(e) {
V.onAddToCart(this.props.appID, this.props.rank),
e.preventDefault(),
e.stopPropagation();
}),
(e.prototype.render = function() {
var t = this,
e = this.props,
a = e.appID,
i = e.score,
n = e.rank,
r = e.width,
o =
"https://steamcdn-a.akamaihd.net/steam/apps/" +
a +
"/header.jpg",
s = V.getAppInfo()[a];
if (!s) return P.a.createElement("div", null);
var c = s.n,
l =
0 < s.r
? Object(x.e)(
"#Recommendation_ReleasedOn",
Object(x.n)(s.r)
)
: "",
d = [];
if (s.t)
for (var m = 0, u = 0, p = s.t; u < p.length; u++) {
var _ = p[u];
if (
(d.push(
P.a.createElement(
"div",
{ key: a + "_" + _, className: F.Tag },
V.getTagName(_)
)
),
5 == ++m)
)
break;
}
var h = parseInt(F.smallentrywidth),
g = parseInt(F.optionswrapwidth),
v = 112,
E = !0;
r < h ? (E = !(v = 66)) : r < g && (E = !(v = 87));
var f,
b = E && this.state.hovered,
S = Math.min(Number(i) / 10, 1e3),
y = (Math.max(1, i), !1),
T = !1,
O = !0,
R = "",
N = "",
C = "",
L = "",
I = "",
A = !1,
j = !0;
!b ||
((f = V.getDetails(this.props.appID)) &&
((y = !0),
(T = 0 < f.discount_pct),
(O = "0" == f.discount_price),
"probably" ==
document
.createElement("video")
.canPlayType('video/webm; codecs="vp8, vorbis"')
? V.shouldUseMicrotrailers() && f.microtrailer_webm
? ((I = f.microtrailer_webm), (j = !(A = !0)))
: (I = f.video_webm)
: V.shouldUseMicrotrailers() && f.microtrailer_mp4
? ((I = f.microtrailer_mp4), (j = !(A = !0)))
: (I = f.video_mp4),
(R = "-" + f.discount_pct + "%"),
(N = f.base_price),
(C = O ? Object(x.e)("#FreeToPlay") : f.discount_price),
(L = f.description)));
var D = I && 0 < I.length;
return P.a.createElement(
U.a,
{ appID: a, snr: k.LINK_PARAM },
P.a.createElement(
"a",
{
href: k.BASE_URL + "app/" + a + "?snr=" + k.LINK_PARAM,
onClick: function() {
return V.onAppClicked(a, n);
},
className: Object(M.a)(
F.RecommendationEntry,
"ds_flagged",
"ds_wishlist",
30 < n && F.Hidden,
b && F.Hovered
),
style: { top: Math.min(31, n) * v },
onMouseEnter: this.OnHover,
onMouseLeave: this.OnUnHover
},
P.a.createElement(
"div",
{ className: F.TopEntrySection },
P.a.createElement(
"div",
{ className: F.LeftSection },
P.a.createElement("img", {
className: Object(M.a)(
F.Logo,
(!D || !b) && F.Revealed
),
src: o
}),
P.a.createElement("video", {
ref: this.m_videoRef,
className: Object(M.a)(
"highlight_player_item",
"highlight_movie",
F.Video,
D && b && F.Revealed
),
playsInline: !0,
autoPlay: !0,
muted: j && V.shouldMute(),
src: I,
loop: A
}),
j &&
P.a.createElement(
"div",
{
className: Object(M.a)(F.UnMute, D && F.Revealed),
onClick: function(e) {
return t.onMuteToggle(e);
}
},
P.a.createElement(w.ab, { muted: V.shouldMute() })
),
this.state.wishlisted &&
P.a.createElement(
"div",
{
className: Object(M.a)(
"ds_flag",
"ds_wishlist_flag",
F.WishlistFlag
)
},
Object(x.e)("#Recommendation_OnWishlist") + " "
)
),
P.a.createElement(
"div",
{ className: F.RightSection },
P.a.createElement("div", { className: F.Name }, c),
P.a.createElement(
"div",
{ className: F.CenterSection },
P.a.createElement(
"div",
{
className: Object(M.a)(
F.CenterOption,
F.CenterDefault,
b && F.Hidden
)
},
P.a.createElement(
"div",
{ className: F.Released },
l
),
P.a.createElement(
"div",
{ className: F.BarContainer },
P.a.createElement("div", {
className: F.Bar,
style: { width: S + "%" }
})
),
P.a.createElement("div", { className: F.Tags }, d)
),
P.a.createElement(
"div",
{
className: Object(M.a)(
F.CenterOption,
F.CenterHovered,
!b && F.Hidden
)
},
L
)
),
y &&
P.a.createElement(
"div",
{ className: F.BottomEntrySection },
P.a.createElement(
"div",
{
className: Object(M.a)(
"game_purchase_action",
F.PurchaseSection
)
},
P.a.createElement(
"div",
{
className: Object(M.a)(
"game_purchase_action_bg",
F.PurchaseBG
)
},
T &&
P.a.createElement(
"div",
{
className:
"discount_block game_purchase_discount"
},
P.a.createElement(
"div",
{ className: "discount_pct" },
R
),
P.a.createElement(
"div",
{ className: "discount_prices" },
P.a.createElement(
"div",
{ className: "discount_original_price" },
N
),
P.a.createElement(
"div",
{ className: "discount_final_price" },
C
)
)
),
!T &&
P.a.createElement(
"div",
{
className: Object(M.a)(
"game_purchase_price",
"price",
F.Price
)
},
C
),
!O &&
P.a.createElement(
"div",
{
className: "btn_addtocart",
onClick: function(e) {
return t.onAddToCart(e);
}
},
P.a.createElement(
"span",
{
className:
"btnv6_green_white_innerfade btn_medium"
},
P.a.createElement(
"span",
null,
Object(x.e)("#btn_add_to_cart")
)
)
)
)
),
!this.state.wishlisted &&
!O &&
P.a.createElement(
"div",
{
id: "add_to_wishlist_area",
className: F.WishlistSection,
onClick: function(e) {
return t.onAddToWishlist(e);
}
},
P.a.createElement(
"div",
{
className: "btnv6_blue_hoverfade btn_medium"
},
P.a.createElement(
"span",
null,
Object(x.e)("#wishlist_add_to_wishlist")
)
)
),
this.state.wishlisted &&
!O &&
P.a.createElement(
"div",
{
className: Object(M.a)(
"btnv6_blue_hoverfade btn_medium",
"queue_btn_active",
F.Wishlisted,
F.WishlistSection
),
"data-tooltip-text": Object(x.e)(
"#OnWishlistTooltip"
),
onClick: function(e) {
return t.onGoToWishlist(e);
}
},
P.a.createElement(
"span",
null,
P.a.createElement("img", {
src:
k.IMG_URL_BASE + "/v6/ico/ico_selected.png"
}),
" " + Object(x.e)("#OnWishlist")
)
)
)
)
)
)
);
}),
Object(u.c)([l.a], e.prototype, "OnHover", null),
Object(u.c)([l.a], e.prototype, "OnUnHover", null),
Object(u.c)([l.a], e.prototype, "onMuteToggle", null),
Object(u.c)([l.a], e.prototype, "onAddToWishlist", null),
Object(u.c)([l.a], e.prototype, "onGoToWishlist", null),
Object(u.c)([l.a], e.prototype, "onAddToCart", null),
(e = Object(u.c)([n.a], e))
);
})(P.a.Component),
N = (function(a) {
function e(e) {
var t = a.call(this, e) || this;
return (t.state = { sortedRecommendedApps: [] }), t;
}
return (
Object(u.d)(e, a),
(e.prototype.render = function() {
var e = V.m_fRecencyValue * (k.NUM_RECENCY_STEPS - 1 - 0.001),
t = Math.floor(e),
a = t + 1,
i = 1 - (e - t),
n = 1 - i,
r = V.m_fPopularityValue * (k.NUM_POPULARITY_STEPS - 1 - 0.001),
o = Math.floor(r),
s = o + 1,
c = 1 - (r - o),
l = 1 - c,
d = [];
d.push({ index: o * k.NUM_RECENCY_STEPS + t, weight: c * i }),
d.push({ index: s * k.NUM_RECENCY_STEPS + t, weight: l * i }),
d.push({ index: o * k.NUM_RECENCY_STEPS + a, weight: c * n }),
d.push({ index: s * k.NUM_RECENCY_STEPS + a, weight: l * n });
var m = new Map(),
u = 0,
p = V.getRecommendations(),
_ = V.getAppInfo(),
h = [];
if (p) {
for (var g = 0, v = d; g < v.length; g++) {
var E = v[g],
f = p[E.index],
u = Math.max(u, f.score_scale);
if (f)
for (var b = 0; b < f.app_ids.length; b++) {
var S,
y = f.app_ids[b];
!_[y] ||
_[y].o ||
_[y].i ||
_[y].ti ||
(_[y].w && V.m_bExcludeWishlisted) ||
((S =
(m.get(y) || 0) +
f.scores[b] * E.weight * f.score_scale),
m.set(y, S));
}
}
m.forEach(function(e, t) {
return m.set(t, e / u);
});
var T = [];
m.forEach(function(e, t) {
return T.push({ appid: t, score: e });
});
var O = (T = (T = (T = T.filter(function(e) {
return _[e.appid].t && V.doTagsPassFilter(_[e.appid].t);
})).filter(function(e) {
return _[e.appid].t && !V.doTagsFailExclusion(_[e.appid].t);
})).filter(function(e) {
return 0 < e.score;
})).sort(function(e, t) {
return t.score - e.score;
});
if (0 < O.length) {
for (
var R = 0, N = 0, C = (O = O.slice(0, 30));
N < C.length;
N++
) {
(C[N].rank = R), R++;
}
for (var L = 0, I = O; L < I.length; L++) {
var A = I[L];
h.push(
P.a.createElement(D, {
key: A.appid,
appID: A.appid,
score: A.score,
rank: A.rank,
width: this.props.width
})
);
}
} else
h.push(
P.a.createElement(
"div",
{
key: "no_recommedations_due_to_filter",
className: F.NoRecommendationsMessage
},
Object(x.e)("#NoRecommendationsDueToFilter")
)
);
} else
h.push(
P.a.createElement("div", {
key: "recommendations_loading",
className: F.RecommendationsLoading
})
);
return P.a.createElement(
"div",
{ className: F.RecommendationList },
P.a.createElement(
"div",
{ className: F.Header },
Object(x.e)("#Recommendations_Header")
),
P.a.createElement(j, null),
P.a.createElement(
"div",
{
className: Object(M.a)(
F.List,
V.areResultsExpired() && F.Updating
)
},
h
)
);
}),
(e = Object(u.c)([n.a], e))
);
})(P.a.Component),
C = (function(t) {
function e() {
var e = (null !== t && t.apply(this, arguments)) || this;
return (e.state = { width: window.innerWidth }), e;
}
return (
Object(u.d)(e, t),
(e.prototype.updateDimensions = function() {
this.setState({ width: window.innerWidth });
}),
(e.prototype.componentDidMount = function() {
window.addEventListener("resize", this.updateDimensions);
}),
(e.prototype.ShowLoginDialog = function() {
Object(f.a)();
}),
(e.prototype.render = function() {
return r.i.logged_in
? P.a.createElement(
"div",
{
className: F.App,
style: { height: 3840 + 26 * V.getTagHeight() }
},
P.a.createElement(
"div",
{ className: F.Container },
P.a.createElement(
"div",
{ className: F.TopSection },
P.a.createElement(
"div",
{ className: F.Header },
Object(x.e)("#HeaderTitle")
),
P.a.createElement(
"div",
{ className: F.Body },
Object(x.e)("#HeaderBody1")
)
),
P.a.createElement(
"div",
{ className: F.BottomSection },
P.a.createElement(O, { accountID: r.i.accountid }),
P.a.createElement("div", { className: F.VerticalBar }),
P.a.createElement(N, { width: this.state.width })
)
)
)
: P.a.createElement(
"div",
{ className: F.App },
P.a.createElement(
"div",
{ className: F.Login },
P.a.createElement(
"div",
{ className: F.Text },
Object(x.e)("#LoginText")
),
P.a.createElement(
"div",
{
className: Object(M.a)(
"btn_green_white_innerfade",
" btn_medium"
),
onClick: this.ShowLoginDialog
},
P.a.createElement(
"span",
null,
Object(x.e)("#LoginButton")
)
)
)
);
}),
Object(u.c)([l.a], e.prototype, "updateDimensions", null),
Object(u.c)([l.a], e.prototype, "ShowLoginDialog", null),
(e = Object(u.c)([n.a], e))
);
})(P.a.Component);
t.default = C;
},
Asqs: function(e, t, a) {
e.exports = {
smallentrywidth: "600px",
optionswrapwidth: "777px",
App: "interactiverecommender_App_u3SD8",
Login: "interactiverecommender_Login_3wfCR",
Text: "interactiverecommender_Text_1PXPv",
Container: "interactiverecommender_Container_2g8SX",
TopSection: "interactiverecommender_TopSection_fR3i6",
Header: "interactiverecommender_Header_2CDNs",
Body: "interactiverecommender_Body_174-d",
Spacer: "interactiverecommender_Spacer_1f2cz",
BottomSection: "interactiverecommender_BottomSection_3A60h",
VerticalBar: "interactiverecommender_VerticalBar_2qL2p",
PlaytimeList: "interactiverecommender_PlaytimeList_3qtYu",
Loading: "interactiverecommender_Loading_3pjYy",
IdentityBlock: "interactiverecommender_IdentityBlock_qLWcn",
Avatar: "interactiverecommender_Avatar_VmdbP",
PersonalInfo: "interactiverecommender_PersonalInfo_2oJXF",
Persona: "interactiverecommender_Persona_2vp7F",
GameCount: "interactiverecommender_GameCount_1AIEP",
TotalTime: "interactiverecommender_TotalTime_1tOWe",
PlayedGame: "interactiverecommender_PlayedGame_sNb81",
Ignored: "interactiverecommender_Ignored_30mws",
PlaytimeInfo: "interactiverecommender_PlaytimeInfo_1UkGo",
IgnoreToggle: "interactiverecommender_IgnoreToggle_3hXvg",
Logo: "interactiverecommender_Logo_26qua",
HoursPlayed: "interactiverecommender_HoursPlayed_3Ye_W",
Title: "interactiverecommender_Title_Eucai",
LastPlayed: "interactiverecommender_LastPlayed_1DwCl",
UpdateSaveBlock: "interactiverecommender_UpdateSaveBlock_iaGmJ",
UpdateButton: "interactiverecommender_UpdateButton_wcFtI",
Enabled: "interactiverecommender_Enabled_3QyVu",
RecommendationList: "interactiverecommender_RecommendationList_1krh3",
List: "interactiverecommender_List_C6mYR",
Updating: "interactiverecommender_Updating_1m954",
NoRecommendationsMessage:
"interactiverecommender_NoRecommendationsMessage_1Ps6j",
RecommendationOptions:
"interactiverecommender_RecommendationOptions_2F61j",
Row: "interactiverecommender_Row_1sYIz",
SecondRow: "interactiverecommender_SecondRow_K-rzA",
OptionCheckbox: "interactiverecommender_OptionCheckbox_2Cb6n",
Checkbox: "interactiverecommender_Checkbox_29uP5",
WishlistCheckbox: "interactiverecommender_WishlistCheckbox_1cnxU",
SaveUserSettingsButton:
"interactiverecommender_SaveUserSettingsButton_1VRgd",
OptionSlider: "interactiverecommender_OptionSlider_26ek6",
Labels: "interactiverecommender_Labels_22UxF",
Min: "interactiverecommender_Min_1uiM2",
Max: "interactiverecommender_Max_17wCM",
OptionalLabel: "interactiverecommender_OptionalLabel_1JIe5",
OptionDropdown: "interactiverecommender_OptionDropdown_1dKx5",
Label: "interactiverecommender_Label_XPFnC",
OptionTagList: "interactiverecommender_OptionTagList_uNxeG",
SelectedTag: "interactiverecommender_SelectedTag_2uInW",
Close: "interactiverecommender_Close_2bZrr",
RecommendationEntry: "interactiverecommender_RecommendationEntry_3opuX",
BottomEntrySection: "interactiverecommender_BottomEntrySection_2U08C",
WishlistSection: "interactiverecommender_WishlistSection_dS7Rz",
Hidden: "interactiverecommender_Hidden_2teee",
TopEntrySection: "interactiverecommender_TopEntrySection_1IvHp",
LeftSection: "interactiverecommender_LeftSection_1shxg",
Video: "interactiverecommender_Video_3oNv9",
Revealed: "interactiverecommender_Revealed_3aiFy",
UnMute: "interactiverecommender_UnMute_21t3_",
RightSection: "interactiverecommender_RightSection_27p3s",
CenterSection: "interactiverecommender_CenterSection_M9CWJ",
CenterOption: "interactiverecommender_CenterOption_3mXMY",
Name: "interactiverecommender_Name_2FQXD",
Released: "interactiverecommender_Released_3EvdK",
BarContainer: "interactiverecommender_BarContainer_3qWin",
Bar: "interactiverecommender_Bar_16q7Q",
Score: "interactiverecommender_Score_17yr_",
Tags: "interactiverecommender_Tags_3KlI0",
Tag: "interactiverecommender_Tag_1rNtz",
Hovered: "interactiverecommender_Hovered_3b9wG",
Wishlisted: "interactiverecommender_Wishlisted_2uh0O",
PurchaseSection: "interactiverecommender_PurchaseSection_mjTZM",
PurchaseBG: "interactiverecommender_PurchaseBG_2UHKw",
Price: "interactiverecommender_Price_18mm0",
WishlistFlag: "interactiverecommender_WishlistFlag_2TuuQ",
SelectionBox: "interactiverecommender_SelectionBox_2W7pR",
SuggestionInput: "interactiverecommender_SuggestionInput_3OdNp",
SuggestionContainerOpen:
"interactiverecommender_SuggestionContainerOpen_2NTkL",
SuggestionsList: "interactiverecommender_SuggestionsList_2zgal",
OptionSuggestion: "interactiverecommender_OptionSuggestion_3VKY5"
};
}
}
]);
|
{
"pile_set_name": "Github"
}
|
//BSD, 2014-present, WinterDev
namespace PixelFarm.Drawing.GLES2
{
partial class MyGLDrawBoard
{
//TODO: review drawstring again ***
Color _currentTextColor;
public override RequestFont CurrentFont
{
get => _gpuPainter.CurrentFont;
set => _gpuPainter.CurrentFont = value;
}
/// <summary>
/// current text fill color
/// </summary>
public override Color CurrentTextColor
{
get => _currentTextColor;
set
{
_currentTextColor = value;
//set this to
_gpuPainter.TextPrinter?.ChangeFillColor(value);
}
}
public override RenderVxFormattedString CreateFormattedString(char[] buffer, int startAt, int len, bool delay)
{
if (_gpuPainter.TextPrinter == null)
{
#if DEBUG
throw new System.Exception("no text printer");
#endif
}
//create blank render vx
var renderVxFmtStr = new DrawingGL.GLRenderVxFormattedString();
renderVxFmtStr.Delay = delay;
#if DEBUG
renderVxFmtStr.dbugText = new string(buffer, startAt, len);
#endif
if (_gpuPainter.TextPrinter != null)
{
//we create
//1. texture coords for this string
//2. (if not delay) => an image for this string inside a larger img texture
_gpuPainter.TextPrinter.PrepareStringForRenderVx(renderVxFmtStr, buffer, 0, buffer.Length);
return renderVxFmtStr;
}
else
{
#if DEBUG
throw new System.NotSupportedException();
#else
return null;
#endif
}
}
public void PrepareWordStrips(System.Collections.Generic.List<DrawingGL.GLRenderVxFormattedString> fmtStringList)
{
_gpuPainter.CreateWordStrips(fmtStringList);
}
public override void DrawRenderVx(RenderVx renderVx, float x, float y)
{
if (renderVx is DrawingGL.GLRenderVxFormattedString vxFmtStr)
{
_gpuPainter.TextPrinter.DrawString(vxFmtStr, x, y);
//if (vxFmtStr.BmpOnTransparentBackground)
//{
// DrawingGL.GlyphTexturePrinterDrawingTechnique prevTech = _gpuPainter.TextPrinterDrawingTechnique; //save
// _gpuPainter.TextPrinterDrawingTechnique = DrawingGL.GlyphTexturePrinterDrawingTechnique.Copy;
// _gpuPainter.TextPrinter.DrawString(vxFmtStr, x, y);
// _gpuPainter.TextPrinterDrawingTechnique = prevTech;//restore
//}
//else
//{
// _gpuPainter.TextPrinter.DrawString(vxFmtStr, x, y);
//}
}
}
public override void DrawText(char[] buffer, int left, int top)
{
#if DEBUG
if (_gpuPainter.FontFillColor.A == 0)
{
}
#endif
_gpuPainter.TextPrinter.DrawString(buffer, 0, buffer.Length, left, top);
}
public override void DrawText(char[] buffer, Rectangle logicalTextBox, int textAlignment)
{
#if DEBUG
if (_gpuPainter.FontFillColor.A == 0)
{
}
#endif
_gpuPainter.TextPrinter.DrawString(buffer, 0, buffer.Length, logicalTextBox.X, logicalTextBox.Y);
}
public override void DrawText(char[] str, int startAt, int len, Rectangle logicalTextBox, int textAlignment)
{
#if DEBUG
if (_gpuPainter.FontFillColor.A == 0)
{
}
#endif
_gpuPainter.TextPrinter.DrawString(str, startAt, len, logicalTextBox.X, logicalTextBox.Y);
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "restc-example-koa2",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"accepts": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
"integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
"requires": {
"mime-types": "~2.1.24",
"negotiator": "0.6.2"
}
},
"any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
"integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8="
},
"cache-content-type": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/cache-content-type/-/cache-content-type-1.0.1.tgz",
"integrity": "sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==",
"requires": {
"mime-types": "^2.1.18",
"ylru": "^1.2.0"
}
},
"co": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz",
"integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ="
},
"content-disposition": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
"integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==",
"requires": {
"safe-buffer": "5.1.2"
}
},
"content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
"integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA=="
},
"cookies": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/cookies/-/cookies-0.7.3.tgz",
"integrity": "sha512-+gixgxYSgQLTaTIilDHAdlNPZDENDQernEMiIcZpYYP14zgHsCt4Ce1FEjFtcp6GefhozebB6orvhAAWx/IS0A==",
"requires": {
"depd": "~1.1.2",
"keygrip": "~1.0.3"
}
},
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"deep-equal": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz",
"integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU="
},
"delegates": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
"integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o="
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak="
},
"destroy": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
},
"error-inject": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/error-inject/-/error-inject-1.0.0.tgz",
"integrity": "sha1-4rPZG1Su1nLzCdlQ0VSFD6EdTzc="
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"http-assert": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/http-assert/-/http-assert-1.4.1.tgz",
"integrity": "sha512-rdw7q6GTlibqVVbXr0CKelfV5iY8G2HqEUkhSk297BMbSpSL8crXC+9rjKoMcZZEsksX30le6f/4ul4E28gegw==",
"requires": {
"deep-equal": "~1.0.1",
"http-errors": "~1.7.2"
}
},
"http-errors": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
"integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==",
"requires": {
"depd": "~1.1.2",
"inherits": "2.0.3",
"setprototypeof": "1.1.1",
"statuses": ">= 1.5.0 < 2",
"toidentifier": "1.0.0"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
},
"is-generator-function": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.7.tgz",
"integrity": "sha512-YZc5EwyO4f2kWCax7oegfuSr9mFz1ZvieNYBEjmukLxgXfBUbxAWGVF7GZf0zidYtoBl3WvC07YK0wT76a+Rtw=="
},
"keygrip": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.0.3.tgz",
"integrity": "sha512-/PpesirAIfaklxUzp4Yb7xBper9MwP6hNRA6BGGUFCgbJ+BM5CKBtsoxinNXkLHAr+GXS1/lSlF2rP7cv5Fl+g=="
},
"koa": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/koa/-/koa-2.7.0.tgz",
"integrity": "sha512-7ojD05s2Q+hFudF8tDLZ1CpCdVZw8JQELWSkcfG9bdtoTDzMmkRF6BQBU7JzIzCCOY3xd3tftiy/loHBUYaY2Q==",
"requires": {
"accepts": "^1.3.5",
"cache-content-type": "^1.0.0",
"content-disposition": "~0.5.2",
"content-type": "^1.0.4",
"cookies": "~0.7.1",
"debug": "~3.1.0",
"delegates": "^1.0.0",
"depd": "^1.1.2",
"destroy": "^1.0.4",
"error-inject": "^1.0.0",
"escape-html": "^1.0.3",
"fresh": "~0.5.2",
"http-assert": "^1.3.0",
"http-errors": "^1.6.3",
"is-generator-function": "^1.0.7",
"koa-compose": "^4.1.0",
"koa-convert": "^1.2.0",
"koa-is-json": "^1.0.0",
"on-finished": "^2.3.0",
"only": "~0.0.2",
"parseurl": "^1.3.2",
"statuses": "^1.5.0",
"type-is": "^1.6.16",
"vary": "^1.1.2"
}
},
"koa-compose": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz",
"integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw=="
},
"koa-convert": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/koa-convert/-/koa-convert-1.2.0.tgz",
"integrity": "sha1-2kCHXfSd4FOQmNFwC1CCDOvNIdA=",
"requires": {
"co": "^4.6.0",
"koa-compose": "^3.0.0"
},
"dependencies": {
"koa-compose": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-3.2.1.tgz",
"integrity": "sha1-qFzLQLfZhtjlo0Wzoazo6rz1Tec=",
"requires": {
"any-promise": "^1.1.0"
}
}
}
},
"koa-is-json": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/koa-is-json/-/koa-is-json-1.0.0.tgz",
"integrity": "sha1-JzwH7c3Ljfaiwat9We52SRRR7BQ="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g="
},
"mime-db": {
"version": "1.40.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz",
"integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA=="
},
"mime-types": {
"version": "2.1.24",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz",
"integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==",
"requires": {
"mime-db": "1.40.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"negotiator": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
"requires": {
"ee-first": "1.1.1"
}
},
"only": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/only/-/only-0.0.2.tgz",
"integrity": "sha1-Kv3oTQPlC5qO3EROMGEKcCle37Q="
},
"parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
},
"safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"setprototypeof": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
"integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
},
"statuses": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
"integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
},
"toidentifier": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
"integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw=="
},
"type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"requires": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
}
},
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
},
"ylru": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ylru/-/ylru-1.2.1.tgz",
"integrity": "sha512-faQrqNMzcPCHGVC2aaOINk13K+aaBDUPjGWl0teOXywElLjyVAB6Oe2jj62jHYtwsU49jXhScYbvPENK+6zAvQ=="
}
}
}
|
{
"pile_set_name": "Github"
}
|
//
// PageTabMenuViewController.swift
// PageMenuExample
//
// Created by Tamanyan on 3/7/17.
// Copyright © 2017 Tamanyan. All rights reserved.
//
import UIKit
import SwiftPageMenu
class PageTabMenuViewController: PageMenuController {
let items: [[String]]
let titles: [String]
init(items: [[String]], titles: [String], options: PageMenuOptions? = nil) {
self.items = items
self.titles = titles
super.init(options: options)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = []
if options.layout == .layoutGuide && options.tabMenuPosition == .bottom {
self.view.backgroundColor = Theme.mainColor
} else {
self.view.backgroundColor = .white
}
if self.options.tabMenuPosition == .custom {
self.view.addSubview(self.tabMenuView)
self.tabMenuView.translatesAutoresizingMaskIntoConstraints = false
self.tabMenuView.heightAnchor.constraint(equalToConstant: self.options.menuItemSize.height).isActive = true
self.tabMenuView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.tabMenuView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
if #available(iOS 11.0, *) {
self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
} else {
self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
}
self.delegate = self
self.dataSource = self
}
}
extension PageTabMenuViewController: PageMenuControllerDataSource {
func viewControllers(forPageMenuController pageMenuController: PageMenuController) -> [UIViewController] {
return self.items.map(ChildViewController.init)
}
func menuTitles(forPageMenuController pageMenuController: PageMenuController) -> [String] {
return self.titles
}
func defaultPageIndex(forPageMenuController pageMenuController: PageMenuController) -> Int {
return 0
}
}
extension PageTabMenuViewController: PageMenuControllerDelegate {
func pageMenuController(_ pageMenuController: PageMenuController, didScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) {
// The page view controller will begin scrolling to a new page.
print("didScrollToPageAtIndex index:\(index)")
}
func pageMenuController(_ pageMenuController: PageMenuController, willScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) {
// The page view controller scroll progress between pages.
print("willScrollToPageAtIndex index:\(index)")
}
func pageMenuController(_ pageMenuController: PageMenuController, scrollingProgress progress: CGFloat, direction: PageMenuNavigationDirection) {
// The page view controller did complete scroll to a new page.
print("scrollingProgress progress: \(progress)")
}
func pageMenuController(_ pageMenuController: PageMenuController, didSelectMenuItem index: Int, direction: PageMenuNavigationDirection) {
print("didSelectMenuItem index: \(index)")
}
}
|
{
"pile_set_name": "Github"
}
|
package utils
import (
"bytes"
"strconv"
"strings"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/spf13/cobra"
"github.com/weaveworks/eksctl/pkg/ctl/cmdutils"
)
func TestValidateLoggingFlags(t *testing.T) {
var (
errBothEmpty = "at least one flag has to be provided"
errAllBoth = "cannot use `all` for both"
errOverlappingTypes = "log types cannot be part of --enable-types and --disable-types"
errUnknownType = "unknown log type"
)
flagTests := []struct {
toEnable []string
toDisable []string
errPattern string
}{
{
toEnable: []string{"all"},
toDisable: []string{"audit", "scheduler", "api"},
errPattern: "",
},
{
toEnable: []string{"audit", "scheduler", "api"},
toDisable: []string{"controllerManager", "authenticator"},
errPattern: "",
},
{
toEnable: []string{"all"},
toDisable: []string{"controllerManager", "authenticator"},
errPattern: "",
},
{
toEnable: []string{"all"},
toDisable: []string{"all"},
errPattern: errAllBoth,
},
{
toEnable: []string{"all", "api"},
toDisable: []string{"all"},
// TODO improve error reporting for {"all", "api", ...}
errPattern: errUnknownType,
},
{
toEnable: []string{""},
toDisable: []string{"all"},
errPattern: errUnknownType,
},
{
toEnable: []string{"all", "invalid"},
errPattern: errUnknownType,
},
{
toDisable: []string{"all", "api", "invalid", "scheduler"},
errPattern: errUnknownType,
},
{
toEnable: []string{""},
errPattern: errUnknownType,
},
{
toEnable: []string{""},
toDisable: []string{""},
errPattern: errUnknownType,
},
{
errPattern: errBothEmpty,
},
{
toEnable: []string{"api", "audit"},
toDisable: []string{"audit", "authenticator", "scheduler"},
errPattern: errOverlappingTypes,
},
{
toEnable: []string{"audit", "authenticator", "scheduler"},
toDisable: []string{"api", "scheduler", "controllerManager"},
errPattern: errOverlappingTypes,
},
}
for i, tt := range flagTests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
err := validateLoggingFlags(tt.toEnable, tt.toDisable)
if err != nil {
if tt.errPattern == "" {
t.Errorf("unexpected error: %v", err)
} else if !strings.Contains(err.Error(), tt.errPattern) {
t.Errorf("expected error %q to match %q", err, tt.errPattern)
}
} else if tt.errPattern != "" {
t.Errorf("expected error %q; got nil", tt.errPattern)
}
})
}
}
var _ = Describe("utils", func() {
Describe("invalid-resource", func() {
It("with no flag", func() {
cmd := newMockCmd("invalid-resource")
out, err := cmd.execute()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("unknown command \"invalid-resource\" for \"utils\""))
Expect(out).To(ContainSubstring("usage"))
})
It("with invalid-resource and some flag", func() {
cmd := newMockCmd("invalid-resource", "--invalid-flag", "foo")
out, err := cmd.execute()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("unknown command \"invalid-resource\" for \"utils\""))
Expect(out).To(ContainSubstring("usage"))
})
It("with invalid-resource and additional argument", func() {
cmd := newMockCmd("invalid-resource", "foo")
out, err := cmd.execute()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("unknown command \"invalid-resource\" for \"utils\""))
Expect(out).To(ContainSubstring("usage"))
})
})
})
func newMockCmd(args ...string) *mockVerbCmd {
flagGrouping := cmdutils.NewGrouping()
cmd := Command(flagGrouping)
cmd.SetArgs(args)
return &mockVerbCmd{
parentCmd: cmd,
}
}
type mockVerbCmd struct {
parentCmd *cobra.Command
}
func (c mockVerbCmd) execute() (string, error) {
buf := new(bytes.Buffer)
c.parentCmd.SetOut(buf)
err := c.parentCmd.Execute()
return buf.String(), err
}
|
{
"pile_set_name": "Github"
}
|
package telemetry
import (
"github.com/sirupsen/logrus"
)
type MetricsConfig struct {
FileConfig FileConfig
Logger logrus.FieldLogger
ServiceName string
Sinks []Sink
}
type FileConfig struct {
Prometheus *PrometheusConfig `hcl:"Prometheus"`
DogStatsd []DogStatsdConfig `hcl:"DogStatsd"`
Statsd []StatsdConfig `hcl:"Statsd"`
M3 []M3Config `hcl:"M3"`
InMem *InMem `hcl:"InMem"`
UnusedKeys []string `hcl:",unusedKeys"`
}
type DogStatsdConfig struct {
Address string `hcl:"address"`
UnusedKeys []string `hcl:",unusedKeys"`
}
type PrometheusConfig struct {
Host string `hcl:"host"`
Port int `hcl:"port"`
UnusedKeys []string `hcl:",unusedKeys"`
}
type StatsdConfig struct {
Address string `hcl:"address"`
UnusedKeys []string `hcl:",unusedKeys"`
}
type M3Config struct {
Address string `hcl:"address"`
Env string `hcl:"env"`
UnusedKeys []string `hcl:",unusedKeys"`
}
type InMem struct {
Enabled *bool `hcl:"enabled"`
UnusedKeys []string `hcl:",unusedKeys"`
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
This is the basic layout for a screen, with all of its features enabled.
-->
<!-- Title bar and content -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- Popout bar for action modes -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/abc_action_mode_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!-- Title bar -->
<RelativeLayout android:id="@+id/title_container"
style="?android:attr/windowTitleBackgroundStyle"
android:layout_width="fill_parent"
android:layout_height="?android:attr/windowTitleSize"
>
<ImageView android:id="@+id/left_icon"
android:layout_width="16dip"
android:layout_height="16dip"
android:layout_marginRight="5dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:visibility="gone"
android:scaleType="fitCenter"
/>
<LinearLayout android:id="@+id/right_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
>
<ImageView android:id="@+id/right_icon"
android:layout_width="16dip"
android:layout_height="16dip"
android:layout_marginLeft="5dip"
android:layout_gravity="center_vertical"
android:visibility="gone"
android:scaleType="fitCenter"
/>
<ProgressBar android:id="@+id/progress_circular"
style="?android:attr/progressBarStyleSmallTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_gravity="center_vertical"
android:visibility="gone"
android:max="10000"
/>
</LinearLayout>
<ProgressBar android:id="@+id/progress_horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="2dip"
android:layout_toLeftOf="@id/right_container"
android:layout_toRightOf="@id/left_icon"
android:layout_centerVertical="true"
android:visibility="gone"
android:max="10000"
/>
<TextView android:id="@+id/title"
style="?android:attr/windowTitleStyle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@null"
android:fadingEdge="horizontal"
android:scrollHorizontally="true"
android:gravity="center_vertical"
android:layout_toLeftOf="@id/right_container"
android:layout_toRightOf="@id/left_icon"
/>
</RelativeLayout>
<!-- Content -->
<FrameLayout android:id="@id/action_bar_activity_content"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay"
/>
</LinearLayout>
|
{
"pile_set_name": "Github"
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/webcrypto/algorithm_registry.h"
#include "base/lazy_instance.h"
#include "components/webcrypto/algorithm_implementation.h"
#include "components/webcrypto/algorithm_implementations.h"
#include "components/webcrypto/status.h"
#include "crypto/openssl_util.h"
namespace webcrypto {
namespace {
// This class is used as a singleton. All methods must be threadsafe.
class AlgorithmRegistry {
public:
AlgorithmRegistry()
: sha_(CreateShaImplementation()),
aes_gcm_(CreateAesGcmImplementation()),
aes_cbc_(CreateAesCbcImplementation()),
aes_ctr_(CreateAesCtrImplementation()),
aes_kw_(CreateAesKwImplementation()),
hmac_(CreateHmacImplementation()),
rsa_ssa_(CreateRsaSsaImplementation()),
rsa_oaep_(CreateRsaOaepImplementation()),
rsa_pss_(CreateRsaPssImplementation()),
ecdsa_(CreateEcdsaImplementation()),
ecdh_(CreateEcdhImplementation()),
hkdf_(CreateHkdfImplementation()),
pbkdf2_(CreatePbkdf2Implementation()) {
crypto::EnsureOpenSSLInit();
}
const AlgorithmImplementation* GetAlgorithm(
blink::WebCryptoAlgorithmId id) const {
switch (id) {
case blink::WebCryptoAlgorithmIdSha1:
case blink::WebCryptoAlgorithmIdSha256:
case blink::WebCryptoAlgorithmIdSha384:
case blink::WebCryptoAlgorithmIdSha512:
return sha_.get();
case blink::WebCryptoAlgorithmIdAesGcm:
return aes_gcm_.get();
case blink::WebCryptoAlgorithmIdAesCbc:
return aes_cbc_.get();
case blink::WebCryptoAlgorithmIdAesCtr:
return aes_ctr_.get();
case blink::WebCryptoAlgorithmIdAesKw:
return aes_kw_.get();
case blink::WebCryptoAlgorithmIdHmac:
return hmac_.get();
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
return rsa_ssa_.get();
case blink::WebCryptoAlgorithmIdRsaOaep:
return rsa_oaep_.get();
case blink::WebCryptoAlgorithmIdRsaPss:
return rsa_pss_.get();
case blink::WebCryptoAlgorithmIdEcdsa:
return ecdsa_.get();
case blink::WebCryptoAlgorithmIdEcdh:
return ecdh_.get();
case blink::WebCryptoAlgorithmIdHkdf:
return hkdf_.get();
case blink::WebCryptoAlgorithmIdPbkdf2:
return pbkdf2_.get();
default:
return NULL;
}
}
private:
const std::unique_ptr<AlgorithmImplementation> sha_;
const std::unique_ptr<AlgorithmImplementation> aes_gcm_;
const std::unique_ptr<AlgorithmImplementation> aes_cbc_;
const std::unique_ptr<AlgorithmImplementation> aes_ctr_;
const std::unique_ptr<AlgorithmImplementation> aes_kw_;
const std::unique_ptr<AlgorithmImplementation> hmac_;
const std::unique_ptr<AlgorithmImplementation> rsa_ssa_;
const std::unique_ptr<AlgorithmImplementation> rsa_oaep_;
const std::unique_ptr<AlgorithmImplementation> rsa_pss_;
const std::unique_ptr<AlgorithmImplementation> ecdsa_;
const std::unique_ptr<AlgorithmImplementation> ecdh_;
const std::unique_ptr<AlgorithmImplementation> hkdf_;
const std::unique_ptr<AlgorithmImplementation> pbkdf2_;
};
} // namespace
base::LazyInstance<AlgorithmRegistry>::Leaky g_algorithm_registry =
LAZY_INSTANCE_INITIALIZER;
Status GetAlgorithmImplementation(blink::WebCryptoAlgorithmId id,
const AlgorithmImplementation** impl) {
*impl = g_algorithm_registry.Get().GetAlgorithm(id);
if (*impl)
return Status::Success();
return Status::ErrorUnsupported();
}
} // namespace webcrypto
|
{
"pile_set_name": "Github"
}
|
package info.ephyra.questionanalysis;
import info.ephyra.nlp.NETagger;
import info.ephyra.nlp.OpenNLP;
import info.ephyra.nlp.VerbFormConverter;
import info.ephyra.nlp.semantics.ontologies.WordNet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javatools.PlingStemmer;
/**
* This class provides methods that modify a question to facilitate pattern
* matching and to anticipate the format of text passages that answer the
* question.
*
* @author Nico Schlaefer
* @version 2006-06-18
*/
public class QuestionNormalizer {
/**
* Replaces short forms of "is" and "are" that occur in combination with
* interrogatives.
*
* @param question the question string
* @return modified question string
*/
private static String replaceShortForms(String question) {
// only replace occurences of "'s" and "'re" in combination with
// interrogatives
Pattern p = Pattern.compile("(?i)(how|what|which|when|where|who|why)'" +
"(s|re)");
Matcher m = p.matcher(question);
if (m.find()) {
String original = m.group();
String replaced = original.replace("'s", " is");
replaced = replaced.replace("'re", " are");
return question.replace(original, replaced);
}
return question; // no such short forms in the question
}
/**
* Drops filler words from the question string.
*
* @param question the question string
* @return modified question string
*/
private static String dropFillers(String question) {
String fillers = "(approximate|approximately|one of|so-called)";
return question.replaceAll(fillers + " ", "");
}
/**
* <p>Modifies the question string by applying the following rule:</p>
*
* <p><code>is/are/was/were [...] gerund / past participle ->
* is/are/was/were gerund / past participle</code></p>
*
* @param question question string
* @param tagged tagged question
* @return modified question strings
*/
private static String[] handleAuxIs(String question, String tagged) {
Pattern p = Pattern.compile("(?i)(.* )?(is|are|was|were)/.*? " +
"(\\S*)/vb(g|n).*");
Matcher m = p.matcher(tagged);
String[] results;
if (m.matches()) {
String aux = m.group(2);
String verb = m.group(3);
results = new String[1];
results[0] = question.replaceFirst(verb, aux + " " + verb);
results[0] = results[0].replaceFirst(aux + " ", "");
return results;
}
return null;
}
/**
* <p>Modifies the question string by applying the following rule:</p>
*
* <p><code>can/could/will/would/shall/should/may/might/must [...]
* infinitive -> can/could/will/would/shall/should/may/might/must
* infinitive</code></p>
*
* @param question question string
* @param tagged tagged question
* @return modified question strings
*/
private static String[] handleAuxCanMay(String question, String tagged) {
Pattern p = Pattern.compile("(?i)(.* )?(can|could|will|would|shall" +
"|should|may|might|must)/.*? " +
"(\\S*)/vb(\\W.*)?");
Matcher m = p.matcher(tagged);
String[] results;
if (m.matches()) {
String aux = m.group(2);
String verb = m.group(3);
results = new String[1];
results[0] = question.replaceFirst(verb, aux + " " + verb);
results[0] = results[0].replaceFirst(aux + " ", "");
return results;
}
return null;
}
/**
* <p>Modifies the question string by applying the following rule:</p>
*
* <p><code>have/has/had [...] past_participle -> has/have/had
* past_participle / simple_past</code></p>
*
* @param question question string
* @param tagged tagged question
* @return modified question strings
*/
private static String[] handleAuxHasHad(String question, String tagged) {
Pattern p = Pattern.compile("(?i)(.* )?(has|have|had)/.*? " +
"(\\S*)/vbn.*");
Matcher m = p.matcher(tagged);
String[] results;
if (m.matches()) {
String aux = m.group(2);
String verb = m.group(3);
String[] sp = VerbFormConverter.pastParticipleToSimplePast(verb);
results = new String[sp.length + 1];
results[0] = question.replaceFirst(verb, aux + " " + verb);
results[0] = results[0].replaceFirst(aux + " ", "");
for (int i = 0; i < sp.length; i++) {
results[i + 1] = question.replaceFirst(verb, sp[i]);
results[i + 1] = results[i + 1].replaceFirst(aux + " ", "");
}
return results;
}
return null;
}
/**
* <p>Modifies the question string by applying the following rule:</p>
*
* <p><code>do [...] infinitive -> infinitive</code></p>
*
* @param question question string
* @param tagged tagged question
* @return modified question strings
*/
private static String[] handleAuxDo(String question, String tagged) {
Pattern p = Pattern.compile("(?i)(.* )?do/.*? (\\S*)/vb(\\W.*)?");
Matcher m = p.matcher(tagged);
String[] results;
if (m.matches()) {
results = new String[1];
results[0] = question.replaceFirst("do ", "");
return results;
}
return null;
}
/**
* <p>Modifies the question string by applying the following rule:</p>
*
* <p><code>does [...] infinitive -> 3rd person singular</code></p>
*
* @param question question string
* @param tagged tagged question
* @return modified question strings
*/
private static String[] handleAuxDoes(String question, String tagged) {
Pattern p = Pattern.compile("(?i)(.* )?does/.*? (\\S*)/vb(\\W.*)?");
Matcher m = p.matcher(tagged);
String[] results;
if (m.matches()) {
String verb = m.group(2);
String tps = VerbFormConverter.infinitiveToThirdPersonS(verb);
results = new String[1];
results[0] = question.replaceFirst(verb, tps);
results[0] = results[0].replaceFirst("does ", "");
return results;
}
return null;
}
/**
* <p>Modifies the question string by applying the following rule:</p>
*
* <p><code>did [...] infinitive -> simple_past</code></p>
*
* @param question question string
* @param tagged tagged question
* @return modified question strings
*/
private static String[] handleAuxDid(String question, String tagged) {
Pattern p = Pattern.compile("(?i)(.* )?did/.*? (\\S*)/vb(\\W.*)?");
Matcher m = p.matcher(tagged);
String[] results;
if (m.matches()) {
String verb = m.group(2);
results = VerbFormConverter.infinitiveToSimplePast(verb);
for (int i = 0; i < results.length; i++) {
results[i] = question.replace(verb, results[i]);
results[i] = results[i].replace("did ", "");
}
return results;
}
return null;
}
/**
* Removes the final punctuation mark and quotation marks from the question
* string.
*
* @param question the question string
* @return modified question string
*/
private static String dropPunctuationMarks(String question) {
// drop final punctuation mark
question = question.replaceAll("(\\.|\\?|!)$", "");
// drop quotation marks
return question.replaceAll("\"", "");
}
// /**
// * Converts the first letter of the question string to lower case.
// *
// * @param question the question string
// * @return modified question string
// */
// private static String lowerFirstLetter(String question) {
// if (question.length() > 0) {
// String upper = question.substring(0, 1); // get first letter
// String lower = upper.toLowerCase();
//
// if (!lower.equals(upper))
// return question.replaceFirst(upper, lower);
// }
//
// return question;
// }
/**
* Normalizes a question string by removing abundant whitespaces, replacing
* short forms and dropping filler words.
*
* @param question question string
* @return normalized question string
*/
public static String normalize(String question) {
//remove leading and trailing whitespaces
question = question.trim();
//replace multiple whitespaces by a single blank
question = question.replaceAll("\\s+", " ");
// replace short forms of "is" and "are"
question = replaceShortForms(question);
// drop filler words
question = dropFillers(question);
return question;
}
/**
* Converts the verbs to infinitive and the nouns to their singular forms.
*
* @param qn normalized question string
* @return stemmed question string
*/
public static String stemVerbsAndNouns(String qn) {
// tokenize, tag POS and convert to lower case
String[] tokens = OpenNLP.tokenize(qn);
String[] pos = OpenNLP.tagPos(tokens);
qn = qn.toLowerCase();
for (int i = 0; i < tokens.length; i++)
tokens[i] = tokens[i].toLowerCase();
for (int i = 0; i < tokens.length; i++) {
if (pos[i].startsWith("VB")) {
String rep = WordNet.getLemma(tokens[i], WordNet.VERB);
if (rep == null) rep = tokens[i];
qn = qn.replace(tokens[i], rep);
} else if (pos[i].startsWith("NN")) {
String rep = PlingStemmer.stem(tokens[i]);
qn = qn.replace(tokens[i], rep);
}
}
// drop final punctuation mark and quotation marks
qn = dropPunctuationMarks(qn);
// convert the first letter to lower case
// qn = lowerFirstLetter(qn);
return qn;
}
/**
* Unstems a substring of the stemmed question string by mapping it to the
* normalized question string.
*
* @param sub a substring of the stemmed question string
* @param stemmed the stemmed question string
* @param qn the normalized question string
* @return unstemmed string or <code>sub</code>, if it is not a substring of
* <code>stemmed</code>
*/
public static String unstem(String sub, String stemmed, String qn) {
String result = sub;
// preprocess the normalized question string
// - drop final punctuation mark and quotation marks
qn = dropPunctuationMarks(qn);
// - convert the first letter to lower case
// qn = lowerFirstLetter(qn);
String[] truncs = stemmed.split(sub, -1);
if (truncs.length > 1) { // substring occurs in stemmed string?
int start = NETagger.tokenize(truncs[0]).length;
int end = start + NETagger.tokenize(sub).length;
String[] tokens = NETagger.tokenize(qn);
result = tokens[start];
for (int i = start + 1; i < end; i++) result += " " + tokens[i];
result = OpenNLP.untokenize(result, qn);
}
return result;
}
/**
* <p>Handles auxiliary verbs by applying the rules specified in the
* documentations of the <code>handleAux...()</code> methods.</p>
*
* @param qn normalized question string
* @return question strings with modified verbs
*/
public static String[] handleAuxiliaries(String qn) {
String[] results = {qn};
// tokenize, tag POS and convert to lower case
String tokens = OpenNLP.tokenizeWithSpaces(qn);
String tagged = OpenNLP.tagPos(tokens).toLowerCase();
// is/are/was/were [...] gerund / past participle ->
// is/are/was/were gerund / past participle
results = handleAuxIs(qn, tagged);
// can/could/will/would/shall/should/may/might/must [...] infinitive ->
// can/could/will/would/shall/should/may/might/must infinitive
if (results == null) results = handleAuxCanMay(qn, tagged);
// have/has/had [...] past_participle ->
// has/have/had past_participle / simple_past
if (results == null) results = handleAuxHasHad(qn, tagged);
// do [...] infinitive -> infinitive
if (results == null) results = handleAuxDo(qn, tagged);
// does [...] infinitive -> infinitive + "s"
if (results == null) results = handleAuxDoes(qn, tagged);
// did [...] infinitive -> simple_past
if (results == null) results = handleAuxDid(qn, tagged);
// none of the above rules applies
if (results == null) results = new String[] {qn};
for (int i = 0; i < results.length; i++) {
// drop final punctuation mark and quotation marks
results[i] = dropPunctuationMarks(results[i]);
// convert the first letter to lower case
// results[i] = lowerFirstLetter(results[i]);
}
return results;
}
/**
* Replaces certain expressions in a list question to transform it into a
* factoid question.
*
* @param question a list question
* @return transformed question
*/
public static String transformList(String question) {
question = normalize(question);
String listPattern = ("(?i)^") +
"(name|(what|which|who)( (is|are|was|were))?|list|give|provide|identify) " +
"((a list of )?((the )?names of )?(all|every|a few|more|(the )?other|(the )?several|some( of)?|(the )?various) )?";
Matcher m = Pattern.compile(listPattern).matcher(question);
if (m.find()) {
String match = m.group(0);
String rep = m.group(1);
if (rep.matches("(?i)(list|give|provide|identify)")) rep = "name";
question = question.replaceFirst(match, rep + " ");
}
return question;
}
}
|
{
"pile_set_name": "Github"
}
|
{% extends "orga/schedule/base.html" %}
{% load compress %}
{% load i18n %}
{% load static %}
{% block scripts %}
{% compress js %}
<script defer src="{% static "vendored/moment-with-locales.js" %}"></script>
<script defer src="{% static "vendored/moment-timezone-with-data-2012-2022.js" %}"></script>
{% if debug %}
<script defer src="{% static "vendored/vue.js" %}"></script>
{% else %}
<script defer src="{% static "vendored/vue.min.js" %}"></script>
{% endif %}
<script defer src="{% static "vendored/vue-async-computed.js" %}"></script>
<script defer src="{% static "orga/js/schedule.js" %}"></script>
{% endcompress %}
{% endblock %}
{% block schedule_content %}
{% if schedule_version %}
<div class="alert alert-warning schedule-alert">
{% translate "You're currently viewing a released schedule version. Released versions cannot be edited directly." %}
</div>
{% endif %}
<div class="schedule-header">
<div id="schedule-choice">
<div class="input-group">
<form class="form-inline">
<div class="input-group">
<select name="version" id="version" class="form-control">
<option value="">{% translate "Current draft" %}</option>
{% for schedule in request.event.schedules.all %}
{% if schedule.version %}
<option value="{{ schedule.version }}" {% if schedule.version == schedule_version %}selected{% endif %}>{{ schedule.version }}</option>
{% endif %}
{% endfor %}
</select>
<button type="submit" class="btn btn-info">{% translate "Show" %}</button>
</div>
</form>
</div>
</div>
{% if not schedule_version %}
<a id="schedule-release" href="{{ request.event.orga_urls.release_schedule }}" class="btn btn-success"><i class="fa fa-plus"></i> {% translate "New release" %}</a>
{% else %}
<form method="post" action="{{ request.event.orga_urls.reset_schedule }}?{{ request.GET.urlencode }}">
{% csrf_token %}
<button type="submit" class="btn btn-info">{% translate "Reset to current version" %}</button>
</form>
{% endif %}
<details class="dropdown">
<summary class="btn btn-info" id="schedule-actions">
{% translate "Actions" %} <i class="fa fa-caret-down"></i>
</summary>
<ul class="dropdown-content dropdown-front dropdown-content-sw">
<li><a class="dropdown-item" href="{{ active_schedule.urls.public }}" target="_blank" rel="noopener">
<i class="fa fa-link"></i> {% translate "View in frontend" %}
</a></li>
{% if request.event.settings.show_schedule %}
<li><a class="dropdown-item" href="{{ request.event.orga_urls.toggle_schedule }}">
<i class="fa fa-eye"></i> {% translate "Hide schedule" %}
</a></li>
{% else %}
<li><a class="dropdown-item" href="{{ request.event.orga_urls.toggle_schedule }}">
<i class="fa fa-eye"></i> {% translate "Make schedule public" %}
</a></li>
{% endif %}
<li><a href="{{ request.event.orga_urls.submission_cards }}" class="dropdown-item">
<i class="fa fa-print"></i> {% translate "Print cards" %}
</a></li>
<li><a href="resend_mails" class="dropdown-item">
<i class="fa fa-envelope"></i> {% translate "Resend speaker notifications" %}
</a></li>
</ul>
</details>
</div>
{% if not request.event.rooms.count %}
<div class="alert alert-warning schedule-alert">
<span>
{% translate "You can start planning your schedule once you have configured some rooms for talks to take place in." %}
<a href="{{ request.event.orga_urls.new_room }}">{% translate "Configure rooms" %}</a>
</span>
</div>
{% else %}
<div id="fahrplan">
</div>
{% endif %}
{% endblock %}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage Technorati
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Collection of utilities for various Zend_Service_Technorati classes.
*
* @category Zend
* @package Zend_Service
* @subpackage Technorati
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Technorati_Utils
{
/**
* Parses, validates and returns a valid Zend_Uri object
* from given $input.
*
* @param string|Zend_Uri_Http $input
* @return null|Zend_Uri_Http
* @throws Zend_Service_Technorati_Exception
* @static
*/
public static function normalizeUriHttp($input)
{
// allow null as value
if ($input === null) {
return null;
}
/**
* @see Zend_Uri
*/
//$1 'Zend/Uri.php';
if ($input instanceof Zend_Uri_Http) {
$uri = $input;
} else {
try {
$uri = Zend_Uri::factory((string) $input);
}
// wrap exception under Zend_Service_Technorati_Exception object
catch (Exception $e) {
/**
* @see Zend_Service_Technorati_Exception
*/
//$1 'Zend/Service/Technorati/Exception.php';
throw new Zend_Service_Technorati_Exception($e->getMessage(), 0, $e);
}
}
// allow inly Zend_Uri_Http objects or child classes
if (!($uri instanceof Zend_Uri_Http)) {
/**
* @see Zend_Service_Technorati_Exception
*/
//$1 'Zend/Service/Technorati/Exception.php';
throw new Zend_Service_Technorati_Exception(
"Invalid URL $uri, only HTTP(S) protocols can be used");
}
return $uri;
}
/**
* Parses, validates and returns a valid Zend_Date object
* from given $input.
*
* $input can be either a string, an integer or a Zend_Date object.
* If $input is string or int, it will be provided to Zend_Date as it is.
* If $input is a Zend_Date object, the object instance will be returned.
*
* @param mixed|Zend_Date $input
* @return null|Zend_Date
* @throws Zend_Service_Technorati_Exception
* @static
*/
public static function normalizeDate($input)
{
/**
* @see Zend_Date
*/
//$1 'Zend/Date.php';
/**
* @see Zend_Locale
*/
//$1 'Zend/Locale.php';
// allow null as value and return valid Zend_Date objects
if (($input === null) || ($input instanceof Zend_Date)) {
return $input;
}
// due to a BC break as of ZF 1.5 it's not safe to use Zend_Date::isDate() here
// see ZF-2524, ZF-2334
if (@strtotime($input) !== FALSE) {
return new Zend_Date($input);
} else {
/**
* @see Zend_Service_Technorati_Exception
*/
//$1 'Zend/Service/Technorati/Exception.php';
throw new Zend_Service_Technorati_Exception("'$input' is not a valid Date/Time");
}
}
/**
* @todo public static function xpathQueryAndSet() {}
*/
/**
* @todo public static function xpathQueryAndSetIf() {}
*/
/**
* @todo public static function xpathQueryAndSetUnless() {}
*/
}
|
{
"pile_set_name": "Github"
}
|
/*
Aggregator is a reporter used by the Ginkgo CLI to aggregate and present parallel test output
coherently as tests complete. You shouldn't need to use this in your code. To run tests in parallel:
ginkgo -nodes=N
where N is the number of nodes you desire.
*/
package remote
import (
"time"
"github.com/onsi/ginkgo/config"
"github.com/onsi/ginkgo/reporters/stenographer"
"github.com/onsi/ginkgo/types"
)
type configAndSuite struct {
config config.GinkgoConfigType
summary *types.SuiteSummary
}
type Aggregator struct {
nodeCount int
config config.DefaultReporterConfigType
stenographer stenographer.Stenographer
result chan bool
suiteBeginnings chan configAndSuite
aggregatedSuiteBeginnings []configAndSuite
beforeSuites chan *types.SetupSummary
aggregatedBeforeSuites []*types.SetupSummary
afterSuites chan *types.SetupSummary
aggregatedAfterSuites []*types.SetupSummary
specCompletions chan *types.SpecSummary
completedSpecs []*types.SpecSummary
suiteEndings chan *types.SuiteSummary
aggregatedSuiteEndings []*types.SuiteSummary
specs []*types.SpecSummary
startTime time.Time
}
func NewAggregator(nodeCount int, result chan bool, config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *Aggregator {
aggregator := &Aggregator{
nodeCount: nodeCount,
result: result,
config: config,
stenographer: stenographer,
suiteBeginnings: make(chan configAndSuite),
beforeSuites: make(chan *types.SetupSummary),
afterSuites: make(chan *types.SetupSummary),
specCompletions: make(chan *types.SpecSummary),
suiteEndings: make(chan *types.SuiteSummary),
}
go aggregator.mux()
return aggregator
}
func (aggregator *Aggregator) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) {
aggregator.suiteBeginnings <- configAndSuite{config, summary}
}
func (aggregator *Aggregator) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {
aggregator.beforeSuites <- setupSummary
}
func (aggregator *Aggregator) AfterSuiteDidRun(setupSummary *types.SetupSummary) {
aggregator.afterSuites <- setupSummary
}
func (aggregator *Aggregator) SpecWillRun(specSummary *types.SpecSummary) {
//noop
}
func (aggregator *Aggregator) SpecDidComplete(specSummary *types.SpecSummary) {
aggregator.specCompletions <- specSummary
}
func (aggregator *Aggregator) SpecSuiteDidEnd(summary *types.SuiteSummary) {
aggregator.suiteEndings <- summary
}
func (aggregator *Aggregator) mux() {
loop:
for {
select {
case configAndSuite := <-aggregator.suiteBeginnings:
aggregator.registerSuiteBeginning(configAndSuite)
case setupSummary := <-aggregator.beforeSuites:
aggregator.registerBeforeSuite(setupSummary)
case setupSummary := <-aggregator.afterSuites:
aggregator.registerAfterSuite(setupSummary)
case specSummary := <-aggregator.specCompletions:
aggregator.registerSpecCompletion(specSummary)
case suite := <-aggregator.suiteEndings:
finished, passed := aggregator.registerSuiteEnding(suite)
if finished {
aggregator.result <- passed
break loop
}
}
}
}
func (aggregator *Aggregator) registerSuiteBeginning(configAndSuite configAndSuite) {
aggregator.aggregatedSuiteBeginnings = append(aggregator.aggregatedSuiteBeginnings, configAndSuite)
if len(aggregator.aggregatedSuiteBeginnings) == 1 {
aggregator.startTime = time.Now()
}
if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount {
return
}
aggregator.stenographer.AnnounceSuite(configAndSuite.summary.SuiteDescription, configAndSuite.config.RandomSeed, configAndSuite.config.RandomizeAllSpecs, aggregator.config.Succinct)
totalNumberOfSpecs := 0
if len(aggregator.aggregatedSuiteBeginnings) > 0 {
totalNumberOfSpecs = configAndSuite.summary.NumberOfSpecsBeforeParallelization
}
aggregator.stenographer.AnnounceTotalNumberOfSpecs(totalNumberOfSpecs, aggregator.config.Succinct)
aggregator.stenographer.AnnounceAggregatedParallelRun(aggregator.nodeCount, aggregator.config.Succinct)
aggregator.flushCompletedSpecs()
}
func (aggregator *Aggregator) registerBeforeSuite(setupSummary *types.SetupSummary) {
aggregator.aggregatedBeforeSuites = append(aggregator.aggregatedBeforeSuites, setupSummary)
aggregator.flushCompletedSpecs()
}
func (aggregator *Aggregator) registerAfterSuite(setupSummary *types.SetupSummary) {
aggregator.aggregatedAfterSuites = append(aggregator.aggregatedAfterSuites, setupSummary)
aggregator.flushCompletedSpecs()
}
func (aggregator *Aggregator) registerSpecCompletion(specSummary *types.SpecSummary) {
aggregator.completedSpecs = append(aggregator.completedSpecs, specSummary)
aggregator.specs = append(aggregator.specs, specSummary)
aggregator.flushCompletedSpecs()
}
func (aggregator *Aggregator) flushCompletedSpecs() {
if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount {
return
}
for _, setupSummary := range aggregator.aggregatedBeforeSuites {
aggregator.announceBeforeSuite(setupSummary)
}
for _, specSummary := range aggregator.completedSpecs {
aggregator.announceSpec(specSummary)
}
for _, setupSummary := range aggregator.aggregatedAfterSuites {
aggregator.announceAfterSuite(setupSummary)
}
aggregator.aggregatedBeforeSuites = []*types.SetupSummary{}
aggregator.completedSpecs = []*types.SpecSummary{}
aggregator.aggregatedAfterSuites = []*types.SetupSummary{}
}
func (aggregator *Aggregator) announceBeforeSuite(setupSummary *types.SetupSummary) {
aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput)
if setupSummary.State != types.SpecStatePassed {
aggregator.stenographer.AnnounceBeforeSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace)
}
}
func (aggregator *Aggregator) announceAfterSuite(setupSummary *types.SetupSummary) {
aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput)
if setupSummary.State != types.SpecStatePassed {
aggregator.stenographer.AnnounceAfterSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace)
}
}
func (aggregator *Aggregator) announceSpec(specSummary *types.SpecSummary) {
if aggregator.config.Verbose && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped {
aggregator.stenographer.AnnounceSpecWillRun(specSummary)
}
aggregator.stenographer.AnnounceCapturedOutput(specSummary.CapturedOutput)
switch specSummary.State {
case types.SpecStatePassed:
if specSummary.IsMeasurement {
aggregator.stenographer.AnnounceSuccessfulMeasurement(specSummary, aggregator.config.Succinct)
} else if specSummary.RunTime.Seconds() >= aggregator.config.SlowSpecThreshold {
aggregator.stenographer.AnnounceSuccessfulSlowSpec(specSummary, aggregator.config.Succinct)
} else {
aggregator.stenographer.AnnounceSuccessfulSpec(specSummary)
}
case types.SpecStatePending:
aggregator.stenographer.AnnouncePendingSpec(specSummary, aggregator.config.NoisyPendings && !aggregator.config.Succinct)
case types.SpecStateSkipped:
aggregator.stenographer.AnnounceSkippedSpec(specSummary, aggregator.config.Succinct || !aggregator.config.NoisySkippings, aggregator.config.FullTrace)
case types.SpecStateTimedOut:
aggregator.stenographer.AnnounceSpecTimedOut(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace)
case types.SpecStatePanicked:
aggregator.stenographer.AnnounceSpecPanicked(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace)
case types.SpecStateFailed:
aggregator.stenographer.AnnounceSpecFailed(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace)
}
}
func (aggregator *Aggregator) registerSuiteEnding(suite *types.SuiteSummary) (finished bool, passed bool) {
aggregator.aggregatedSuiteEndings = append(aggregator.aggregatedSuiteEndings, suite)
if len(aggregator.aggregatedSuiteEndings) < aggregator.nodeCount {
return false, false
}
aggregatedSuiteSummary := &types.SuiteSummary{}
aggregatedSuiteSummary.SuiteSucceeded = true
for _, suiteSummary := range aggregator.aggregatedSuiteEndings {
if !suiteSummary.SuiteSucceeded {
aggregatedSuiteSummary.SuiteSucceeded = false
}
aggregatedSuiteSummary.NumberOfSpecsThatWillBeRun += suiteSummary.NumberOfSpecsThatWillBeRun
aggregatedSuiteSummary.NumberOfTotalSpecs += suiteSummary.NumberOfTotalSpecs
aggregatedSuiteSummary.NumberOfPassedSpecs += suiteSummary.NumberOfPassedSpecs
aggregatedSuiteSummary.NumberOfFailedSpecs += suiteSummary.NumberOfFailedSpecs
aggregatedSuiteSummary.NumberOfPendingSpecs += suiteSummary.NumberOfPendingSpecs
aggregatedSuiteSummary.NumberOfSkippedSpecs += suiteSummary.NumberOfSkippedSpecs
aggregatedSuiteSummary.NumberOfFlakedSpecs += suiteSummary.NumberOfFlakedSpecs
}
aggregatedSuiteSummary.RunTime = time.Since(aggregator.startTime)
aggregator.stenographer.SummarizeFailures(aggregator.specs)
aggregator.stenographer.AnnounceSpecRunCompletion(aggregatedSuiteSummary, aggregator.config.Succinct)
return true, aggregatedSuiteSummary.SuiteSucceeded
}
|
{
"pile_set_name": "Github"
}
|
"""
Interface for CANtact devices from Linklayer Labs
"""
import time
import logging
from unittest.mock import Mock
from can import BusABC, Message
logger = logging.getLogger(__name__)
try:
import cantact
except ImportError:
logger.warning(
"The CANtact module is not installed. Install it using `python3 -m pip install cantact`"
)
class CantactBus(BusABC):
"""CANtact interface"""
@staticmethod
def _detect_available_configs():
try:
interface = cantact.Interface()
except NameError:
# couldn't import cantact, so no configurations are available
return []
channels = []
for i in range(0, interface.channel_count()):
channels.append({"interface": "cantact", "channel": "ch:%d" % i})
return channels
def __init__(
self,
channel,
bitrate=500000,
poll_interval=0.01,
monitor=False,
bit_timing=None,
_testing=False,
**kwargs
):
"""
:param int channel:
Channel number (zero indexed, labeled on multi-channel devices)
:param int bitrate:
Bitrate in bits/s
:param bool monitor:
If true, operate in listen-only monitoring mode
:param BitTiming bit_timing
Optional BitTiming to use for custom bit timing setting. Overrides bitrate if not None.
"""
if _testing:
self.interface = MockInterface()
else:
self.interface = cantact.Interface()
self.channel = int(channel)
self.channel_info = "CANtact: ch:%s" % channel
# configure the interface
if bit_timing is None:
# use bitrate
self.interface.set_bitrate(int(channel), int(bitrate))
else:
# use custom bit timing
self.interface.set_bit_timing(
int(channel),
int(bit_timing.brp),
int(bit_timing.tseg1),
int(bit_timing.tseg2),
int(bit_timing.sjw),
)
self.interface.set_enabled(int(channel), True)
self.interface.set_monitor(int(channel), monitor)
self.interface.start()
super().__init__(
channel=channel, bitrate=bitrate, poll_interval=poll_interval, **kwargs
)
def _recv_internal(self, timeout):
frame = self.interface.recv(int(timeout * 1000))
if frame is None:
# timeout occured
return None, False
msg = Message(
arbitration_id=frame["id"],
is_extended_id=frame["extended"],
timestamp=frame["timestamp"],
is_remote_frame=frame["rtr"],
dlc=frame["dlc"],
data=frame["data"][: frame["dlc"]],
channel=frame["channel"],
is_rx=(not frame["loopback"]), # received if not loopback frame
)
return msg, False
def send(self, msg, timeout=None):
self.interface.send(
self.channel,
msg.arbitration_id,
bool(msg.is_extended_id),
bool(msg.is_remote_frame),
msg.dlc,
msg.data,
)
def shutdown(self):
self.interface.stop()
def mock_recv(timeout):
if timeout > 0:
frame = {}
frame["id"] = 0x123
frame["extended"] = False
frame["timestamp"] = time.time()
frame["loopback"] = False
frame["rtr"] = False
frame["dlc"] = 8
frame["data"] = [1, 2, 3, 4, 5, 6, 7, 8]
frame["channel"] = 0
return frame
else:
# simulate timeout when timeout = 0
return None
class MockInterface:
"""
Mock interface to replace real interface when testing.
This allows for tests to run without actual hardware.
"""
start = Mock()
set_bitrate = Mock()
set_bit_timing = Mock()
set_enabled = Mock()
set_monitor = Mock()
start = Mock()
stop = Mock()
send = Mock()
channel_count = Mock(return_value=1)
recv = Mock(side_effect=mock_recv)
|
{
"pile_set_name": "Github"
}
|
# SPDX-License-Identifier: GPL-2.0
#
# Makefile for the USB serial device drivers.
#
# Object file lists.
obj-$(CONFIG_USB_SERIAL) += usbserial.o
usbserial-y := usb-serial.o generic.o bus.o
usbserial-$(CONFIG_USB_SERIAL_CONSOLE) += console.o
obj-$(CONFIG_USB_SERIAL_AIRCABLE) += aircable.o
obj-$(CONFIG_USB_SERIAL_ARK3116) += ark3116.o
obj-$(CONFIG_USB_SERIAL_BELKIN) += belkin_sa.o
obj-$(CONFIG_USB_SERIAL_CH341) += ch341.o
obj-$(CONFIG_USB_SERIAL_CP210X) += cp210x.o
obj-$(CONFIG_USB_SERIAL_CYBERJACK) += cyberjack.o
obj-$(CONFIG_USB_SERIAL_CYPRESS_M8) += cypress_m8.o
obj-$(CONFIG_USB_SERIAL_DEBUG) += usb_debug.o
obj-$(CONFIG_USB_SERIAL_DIGI_ACCELEPORT) += digi_acceleport.o
obj-$(CONFIG_USB_SERIAL_EDGEPORT) += io_edgeport.o
obj-$(CONFIG_USB_SERIAL_EDGEPORT_TI) += io_ti.o
obj-$(CONFIG_USB_SERIAL_EMPEG) += empeg.o
obj-$(CONFIG_USB_SERIAL_F81232) += f81232.o
obj-$(CONFIG_USB_SERIAL_F8153X) += f81534.o
obj-$(CONFIG_USB_SERIAL_FTDI_SIO) += ftdi_sio.o
obj-$(CONFIG_USB_SERIAL_GARMIN) += garmin_gps.o
obj-$(CONFIG_USB_SERIAL_IPAQ) += ipaq.o
obj-$(CONFIG_USB_SERIAL_IPW) += ipw.o
obj-$(CONFIG_USB_SERIAL_IR) += ir-usb.o
obj-$(CONFIG_USB_SERIAL_IUU) += iuu_phoenix.o
obj-$(CONFIG_USB_SERIAL_KEYSPAN) += keyspan.o
obj-$(CONFIG_USB_SERIAL_KEYSPAN_PDA) += keyspan_pda.o
obj-$(CONFIG_USB_SERIAL_KLSI) += kl5kusb105.o
obj-$(CONFIG_USB_SERIAL_KOBIL_SCT) += kobil_sct.o
obj-$(CONFIG_USB_SERIAL_MCT_U232) += mct_u232.o
obj-$(CONFIG_USB_SERIAL_METRO) += metro-usb.o
obj-$(CONFIG_USB_SERIAL_MOS7720) += mos7720.o
obj-$(CONFIG_USB_SERIAL_MOS7840) += mos7840.o
obj-$(CONFIG_USB_SERIAL_MXUPORT) += mxuport.o
obj-$(CONFIG_USB_SERIAL_NAVMAN) += navman.o
obj-$(CONFIG_USB_SERIAL_OMNINET) += omninet.o
obj-$(CONFIG_USB_SERIAL_OPTICON) += opticon.o
obj-$(CONFIG_USB_SERIAL_OPTION) += option.o
obj-$(CONFIG_USB_SERIAL_OTI6858) += oti6858.o
obj-$(CONFIG_USB_SERIAL_PL2303) += pl2303.o
obj-$(CONFIG_USB_SERIAL_QCAUX) += qcaux.o
obj-$(CONFIG_USB_SERIAL_QUALCOMM) += qcserial.o
obj-$(CONFIG_USB_SERIAL_QT2) += quatech2.o
obj-$(CONFIG_USB_SERIAL_SAFE) += safe_serial.o
obj-$(CONFIG_USB_SERIAL_SIERRAWIRELESS) += sierra.o
obj-$(CONFIG_USB_SERIAL_SIMPLE) += usb-serial-simple.o
obj-$(CONFIG_USB_SERIAL_SPCP8X5) += spcp8x5.o
obj-$(CONFIG_USB_SERIAL_SSU100) += ssu100.o
obj-$(CONFIG_USB_SERIAL_SYMBOL) += symbolserial.o
obj-$(CONFIG_USB_SERIAL_WWAN) += usb_wwan.o
obj-$(CONFIG_USB_SERIAL_TI) += ti_usb_3410_5052.o
obj-$(CONFIG_USB_SERIAL_UPD78F0730) += upd78f0730.o
obj-$(CONFIG_USB_SERIAL_VISOR) += visor.o
obj-$(CONFIG_USB_SERIAL_WISHBONE) += wishbone-serial.o
obj-$(CONFIG_USB_SERIAL_WHITEHEAT) += whiteheat.o
obj-$(CONFIG_USB_SERIAL_XIRCOM) += keyspan_pda.o
obj-$(CONFIG_USB_SERIAL_XSENS_MT) += xsens_mt.o
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (c) 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import copy
from enum import Enum
from typing import Union
import numpy as np
from rl_coach.agents.agent import Agent
from rl_coach.architectures.head_parameters import MeasurementsPredictionHeadParameters
from rl_coach.architectures.embedder_parameters import InputEmbedderParameters
from rl_coach.architectures.middleware_parameters import FCMiddlewareParameters
from rl_coach.architectures.tensorflow_components.layers import Conv2d, Dense
from rl_coach.base_parameters import AlgorithmParameters, AgentParameters, NetworkParameters, \
MiddlewareScheme
from rl_coach.core_types import ActionInfo, EnvironmentSteps, RunPhase
from rl_coach.exploration_policies.e_greedy import EGreedyParameters
from rl_coach.memories.episodic.episodic_experience_replay import EpisodicExperienceReplayParameters
from rl_coach.memories.memory import MemoryGranularity
from rl_coach.spaces import SpacesDefinition, VectorObservationSpace
class HandlingTargetsAfterEpisodeEnd(Enum):
LastStep = 0
NAN = 1
class DFPNetworkParameters(NetworkParameters):
def __init__(self):
super().__init__()
self.input_embedders_parameters = {'observation': InputEmbedderParameters(activation_function='leaky_relu'),
'measurements': InputEmbedderParameters(activation_function='leaky_relu'),
'goal': InputEmbedderParameters(activation_function='leaky_relu')}
self.input_embedders_parameters['observation'].scheme = [
Conv2d(32, 8, 4),
Conv2d(64, 4, 2),
Conv2d(64, 3, 1),
Dense(512),
]
self.input_embedders_parameters['measurements'].scheme = [
Dense(128),
Dense(128),
Dense(128),
]
self.input_embedders_parameters['goal'].scheme = [
Dense(128),
Dense(128),
Dense(128),
]
self.middleware_parameters = FCMiddlewareParameters(activation_function='leaky_relu',
scheme=MiddlewareScheme.Empty)
self.heads_parameters = [MeasurementsPredictionHeadParameters(activation_function='leaky_relu')]
self.async_training = False
self.batch_size = 64
self.adam_optimizer_beta1 = 0.95
class DFPMemoryParameters(EpisodicExperienceReplayParameters):
def __init__(self):
self.max_size = (MemoryGranularity.Transitions, 20000)
self.shared_memory = True
super().__init__()
class DFPAlgorithmParameters(AlgorithmParameters):
"""
:param num_predicted_steps_ahead: (int)
Number of future steps to predict measurements for. The future steps won't be sequential, but rather jump
in multiples of 2. For example, if num_predicted_steps_ahead = 3, then the steps will be: t+1, t+2, t+4.
The predicted steps will be [t + 2**i for i in range(num_predicted_steps_ahead)]
:param goal_vector: (List[float])
The goal vector will weight each of the measurements to form an optimization goal. The vector should have
the same length as the number of measurements, and it will be vector multiplied by the measurements.
Positive values correspond to trying to maximize the particular measurement, and negative values
correspond to trying to minimize the particular measurement.
:param future_measurements_weights: (List[float])
The future_measurements_weights weight the contribution of each of the predicted timesteps to the optimization
goal. For example, if there are 6 steps predicted ahead, and a future_measurements_weights vector with 3 values,
then only the 3 last timesteps will be taken into account, according to the weights in the
future_measurements_weights vector.
:param use_accumulated_reward_as_measurement: (bool)
If set to True, the accumulated reward from the beginning of the episode will be added as a measurement to
the measurements vector in the state. This van be useful in environments where the given measurements don't
include enough information for the particular goal the agent should achieve.
:param handling_targets_after_episode_end: (HandlingTargetsAfterEpisodeEnd)
Dictates how to handle measurements that are outside the episode length.
:param scale_measurements_targets: (Dict[str, float])
Allows rescaling the values of each of the measurements available. This van be useful when the measurements
have a different scale and you want to normalize them to the same scale.
"""
def __init__(self):
super().__init__()
self.num_predicted_steps_ahead = 6
self.goal_vector = [1.0, 1.0]
self.future_measurements_weights = [0.5, 0.5, 1.0]
self.use_accumulated_reward_as_measurement = False
self.handling_targets_after_episode_end = HandlingTargetsAfterEpisodeEnd.NAN
self.scale_measurements_targets = {}
self.num_consecutive_playing_steps = EnvironmentSteps(8)
class DFPAgentParameters(AgentParameters):
def __init__(self):
super().__init__(algorithm=DFPAlgorithmParameters(),
exploration=EGreedyParameters(),
memory=DFPMemoryParameters(),
networks={"main": DFPNetworkParameters()})
@property
def path(self):
return 'rl_coach.agents.dfp_agent:DFPAgent'
# Direct Future Prediction Agent - http://vladlen.info/papers/learning-to-act.pdf
class DFPAgent(Agent):
def __init__(self, agent_parameters, parent: Union['LevelManager', 'CompositeAgent']=None):
super().__init__(agent_parameters, parent)
self.current_goal = self.ap.algorithm.goal_vector
self.target_measurements_scale_factors = None
def learn_from_batch(self, batch):
network_keys = self.ap.network_wrappers['main'].input_embedders_parameters.keys()
network_inputs = batch.states(network_keys)
network_inputs['goal'] = np.repeat(np.expand_dims(self.current_goal, 0),
batch.size, axis=0)
# get the current outputs of the network
targets = self.networks['main'].online_network.predict(network_inputs)
# change the targets for the taken actions
for i in range(batch.size):
targets[i, batch.actions()[i]] = batch[i].info['future_measurements'].flatten()
result = self.networks['main'].train_and_sync_networks(network_inputs, targets)
total_loss, losses, unclipped_grads = result[:3]
return total_loss, losses, unclipped_grads
def choose_action(self, curr_state):
if self.exploration_policy.requires_action_values():
# predict the future measurements
tf_input_state = self.prepare_batch_for_inference(curr_state, 'main')
tf_input_state['goal'] = np.expand_dims(self.current_goal, 0)
measurements_future_prediction = self.networks['main'].online_network.predict(tf_input_state)[0]
action_values = np.zeros(len(self.spaces.action.actions))
num_steps_used_for_objective = len(self.ap.algorithm.future_measurements_weights)
# calculate the score of each action by multiplying it's future measurements with the goal vector
for action_idx in range(len(self.spaces.action.actions)):
action_measurements = measurements_future_prediction[action_idx]
action_measurements = np.reshape(action_measurements,
(self.ap.algorithm.num_predicted_steps_ahead,
self.spaces.state['measurements'].shape[0]))
future_steps_values = np.dot(action_measurements, self.current_goal)
action_values[action_idx] = np.dot(future_steps_values[-num_steps_used_for_objective:],
self.ap.algorithm.future_measurements_weights)
else:
action_values = None
# choose action according to the exploration policy and the current phase (evaluating or training the agent)
action, _ = self.exploration_policy.get_action(action_values)
if action_values is not None:
action_values = action_values.squeeze()
action_info = ActionInfo(action=action, action_value=action_values[action])
else:
action_info = ActionInfo(action=action)
return action_info
def set_environment_parameters(self, spaces: SpacesDefinition):
self.spaces = copy.deepcopy(spaces)
self.spaces.goal = VectorObservationSpace(shape=self.spaces.state['measurements'].shape,
measurements_names=
self.spaces.state['measurements'].measurements_names)
# if the user has filled some scale values, check that he got the names right
if set(self.spaces.state['measurements'].measurements_names).intersection(
self.ap.algorithm.scale_measurements_targets.keys()) !=\
set(self.ap.algorithm.scale_measurements_targets.keys()):
raise ValueError("Some of the keys in parameter scale_measurements_targets ({}) are not defined in "
"the measurements space {}".format(self.ap.algorithm.scale_measurements_targets.keys(),
self.spaces.state['measurements'].measurements_names))
super().set_environment_parameters(self.spaces)
# the below is done after calling the base class method, as it might add accumulated reward as a measurement
# fill out the missing measurements scale factors
for measurement_name in self.spaces.state['measurements'].measurements_names:
if measurement_name not in self.ap.algorithm.scale_measurements_targets:
self.ap.algorithm.scale_measurements_targets[measurement_name] = 1
self.target_measurements_scale_factors = \
np.array([self.ap.algorithm.scale_measurements_targets[measurement_name] for measurement_name in
self.spaces.state['measurements'].measurements_names])
def handle_episode_ended(self):
last_episode = self.current_episode_buffer
if self.phase in [RunPhase.TRAIN, RunPhase.HEATUP] and last_episode:
self._update_measurements_targets(last_episode,
self.ap.algorithm.num_predicted_steps_ahead)
super().handle_episode_ended()
def _update_measurements_targets(self, episode, num_steps):
if 'measurements' not in episode.transitions[0].state or episode.transitions[0].state['measurements'] == []:
raise ValueError("Measurements are not present in the transitions of the last episode played. ")
measurements_size = self.spaces.state['measurements'].shape[0]
for transition_idx, transition in enumerate(episode.transitions):
transition.info['future_measurements'] = np.zeros((num_steps, measurements_size))
for step in range(num_steps):
offset_idx = transition_idx + 2 ** step
if offset_idx >= episode.length():
if self.ap.algorithm.handling_targets_after_episode_end == HandlingTargetsAfterEpisodeEnd.NAN:
# the special MSE loss will ignore those entries so that the gradient will be 0 for these
transition.info['future_measurements'][step] = np.nan
continue
elif self.ap.algorithm.handling_targets_after_episode_end == HandlingTargetsAfterEpisodeEnd.LastStep:
offset_idx = - 1
transition.info['future_measurements'][step] = \
self.target_measurements_scale_factors * \
(episode.transitions[offset_idx].state['measurements'] - transition.state['measurements'])
|
{
"pile_set_name": "Github"
}
|
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
"""Command-line parsing library
This module is an optparse-inspired command-line parsing library that:
- handles both optional and positional arguments
- produces highly informative usage messages
- supports parsers that dispatch to sub-parsers
The following is a simple usage example that sums integers from the
command-line and writes the result to a file::
parser = argparse.ArgumentParser(
description='sum the integers at the command line')
parser.add_argument(
'integers', metavar='int', nargs='+', type=int,
help='an integer to be summed')
parser.add_argument(
'--log', default=sys.stdout, type=argparse.FileType('w'),
help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()
The module contains the following public classes:
- ArgumentParser -- The main entry point for command-line parsing. As the
example above shows, the add_argument() method is used to populate
the parser with actions for optional and positional arguments. Then
the parse_args() method is invoked to convert the args at the
command-line into an object with attributes.
- ArgumentError -- The exception raised by ArgumentParser objects when
there are errors with the parser's actions. Errors raised while
parsing the command-line are caught by ArgumentParser and emitted
as command-line messages.
- FileType -- A factory for defining types of files to be created. As the
example above shows, instances of FileType are typically passed as
the type= argument of add_argument() calls.
- Action -- The base class for parser actions. Typically actions are
selected by passing strings like 'store_true' or 'append_const' to
the action= argument of add_argument(). However, for greater
customization of ArgumentParser actions, subclasses of Action may
be defined and passed as the action= argument.
- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
ArgumentDefaultsHelpFormatter -- Formatter classes which
may be passed as the formatter_class= argument to the
ArgumentParser constructor. HelpFormatter is the default,
RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
not to change the formatting for help text, and
ArgumentDefaultsHelpFormatter adds information about argument defaults
to the help.
All other classes in this module are considered implementation details.
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
considered public as object names -- the API of the formatter objects is
still considered an implementation detail.)
"""
__version__ = '1.1'
__all__ = [
'ArgumentParser',
'ArgumentError',
'ArgumentTypeError',
'FileType',
'HelpFormatter',
'ArgumentDefaultsHelpFormatter',
'RawDescriptionHelpFormatter',
'RawTextHelpFormatter',
'Namespace',
'Action',
'ONE_OR_MORE',
'OPTIONAL',
'PARSER',
'REMAINDER',
'SUPPRESS',
'ZERO_OR_MORE',
]
import collections as _collections
import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap
from gettext import gettext as _
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
ZERO_OR_MORE = '*'
ONE_OR_MORE = '+'
PARSER = 'A...'
REMAINDER = '...'
_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
# =============================
# Utility functions and classes
# =============================
class _AttributeHolder(object):
"""Abstract base class that provides __repr__.
The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, ...)
The attributes are determined either by a class-level attribute,
'_kwarg_names', or by inspecting the instance __dict__.
"""
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
arg_strings.append('%s=%r' % (name, value))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
return sorted(self.__dict__.items())
def _get_args(self):
return []
def _ensure_value(namespace, name, value):
if getattr(namespace, name, None) is None:
setattr(namespace, name, value)
return getattr(namespace, name)
# ===============
# Formatting Help
# ===============
class HelpFormatter(object):
"""Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def __init__(self,
prog,
indent_increment=2,
max_help_position=24,
width=None):
# default setting for width
if width is None:
try:
width = int(_os.environ['COLUMNS'])
except (KeyError, ValueError):
width = 80
width -= 2
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = max_help_position
self._max_help_position = min(max_help_position,
max(width - 20, indent_increment * 2))
self._width = width
self._current_indent = 0
self._level = 0
self._action_max_length = 0
self._root_section = self._Section(self, None)
self._current_section = self._root_section
self._whitespace_matcher = _re.compile(r'\s+')
self._long_break_matcher = _re.compile(r'\n\n\n+')
# ===============================
# Section and indentation methods
# ===============================
def _indent(self):
self._current_indent += self._indent_increment
self._level += 1
def _dedent(self):
self._current_indent -= self._indent_increment
assert self._current_indent >= 0, 'Indent decreased below 0.'
self._level -= 1
class _Section(object):
def __init__(self, formatter, parent, heading=None):
self.formatter = formatter
self.parent = parent
self.heading = heading
self.items = []
def format_help(self):
# format the indented section
if self.parent is not None:
self.formatter._indent()
join = self.formatter._join_parts
for func, args in self.items:
func(*args)
item_help = join([func(*args) for func, args in self.items])
if self.parent is not None:
self.formatter._dedent()
# return nothing if the section was empty
if not item_help:
return ''
# add the heading if the section was non-empty
if self.heading is not SUPPRESS and self.heading is not None:
current_indent = self.formatter._current_indent
heading = '%*s%s:\n' % (current_indent, '', self.heading)
else:
heading = ''
# join the section-initial newline, the heading and the help
return join(['\n', heading, item_help, '\n'])
def _add_item(self, func, args):
self._current_section.items.append((func, args))
# ========================
# Message building methods
# ========================
def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section, heading)
self._add_item(section.format_help, [])
self._current_section = section
def end_section(self):
self._current_section = self._current_section.parent
self._dedent()
def add_text(self, text):
if text is not SUPPRESS and text is not None:
self._add_item(self._format_text, [text])
def add_usage(self, usage, actions, groups, prefix=None):
if usage is not SUPPRESS:
args = usage, actions, groups, prefix
self._add_item(self._format_usage, args)
def add_argument(self, action):
if action.help is not SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
def add_arguments(self, actions):
for action in actions:
self.add_argument(action)
# =======================
# Help-formatting methods
# =======================
def format_help(self):
help = self._root_section.format_help()
if help:
help = self._long_break_matcher.sub('\n\n', help)
help = help.strip('\n') + '\n'
return help
def _join_parts(self, part_strings):
return ''.join([part
for part in part_strings
if part and part is not SUPPRESS])
def _format_usage(self, usage, actions, groups, prefix):
if prefix is None:
prefix = _('usage: ')
# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = '%(prog)s' % dict(prog=self._prog)
# if optionals and positionals are available, calculate usage
elif usage is None:
prog = '%(prog)s' % dict(prog=self._prog)
# split optionals from positionals
optionals = []
positionals = []
for action in actions:
if action.option_strings:
optionals.append(action)
else:
positionals.append(action)
# build full usage string
format = self._format_actions_usage
action_usage = format(optionals + positionals, groups)
usage = ' '.join([s for s in [prog, action_usage] if s])
# wrap the usage parts if it's too long
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
# break usage into wrappable parts
part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
opt_usage = format(optionals, groups)
pos_usage = format(positionals, groups)
opt_parts = _re.findall(part_regexp, opt_usage)
pos_parts = _re.findall(part_regexp, pos_usage)
assert ' '.join(opt_parts) == opt_usage
assert ' '.join(pos_parts) == pos_usage
# helper for wrapping lines
def get_lines(parts, indent, prefix=None):
lines = []
line = []
if prefix is not None:
line_len = len(prefix) - 1
else:
line_len = len(indent) - 1
for part in parts:
if line_len + 1 + len(part) > text_width and line:
lines.append(indent + ' '.join(line))
line = []
line_len = len(indent) - 1
line.append(part)
line_len += len(part) + 1
if line:
lines.append(indent + ' '.join(line))
if prefix is not None:
lines[0] = lines[0][len(indent):]
return lines
# if prog is short, follow it with optionals or positionals
if len(prefix) + len(prog) <= 0.75 * text_width:
indent = ' ' * (len(prefix) + len(prog) + 1)
if opt_parts:
lines = get_lines([prog] + opt_parts, indent, prefix)
lines.extend(get_lines(pos_parts, indent))
elif pos_parts:
lines = get_lines([prog] + pos_parts, indent, prefix)
else:
lines = [prog]
# if prog is long, put it on its own line
else:
indent = ' ' * len(prefix)
parts = opt_parts + pos_parts
lines = get_lines(parts, indent)
if len(lines) > 1:
lines = []
lines.extend(get_lines(opt_parts, indent))
lines.extend(get_lines(pos_parts, indent))
lines = [prog] + lines
# join lines into usage
usage = '\n'.join(lines)
# prefix with 'usage:'
return '%s%s\n\n' % (prefix, usage)
def _format_actions_usage(self, actions, groups):
# find group indices and identify actions in groups
group_actions = set()
inserts = {}
for group in groups:
try:
start = actions.index(group._group_actions[0])
except ValueError:
continue
else:
end = start + len(group._group_actions)
if actions[start:end] == group._group_actions:
for action in group._group_actions:
group_actions.add(action)
if not group.required:
if start in inserts:
inserts[start] += ' ['
else:
inserts[start] = '['
inserts[end] = ']'
else:
if start in inserts:
inserts[start] += ' ('
else:
inserts[start] = '('
inserts[end] = ')'
for i in range(start + 1, end):
inserts[i] = '|'
# collect all actions format strings
parts = []
for i, action in enumerate(actions):
# suppressed arguments are marked with None
# remove | separators for suppressed arguments
if action.help is SUPPRESS:
parts.append(None)
if inserts.get(i) == '|':
inserts.pop(i)
elif inserts.get(i + 1) == '|':
inserts.pop(i + 1)
# produce all arg strings
elif not action.option_strings:
part = self._format_args(action, action.dest)
# if it's in a group, strip the outer []
if action in group_actions:
if part[0] == '[' and part[-1] == ']':
part = part[1:-1]
# add the action string to the list
parts.append(part)
# produce the first way to invoke the option in brackets
else:
option_string = action.option_strings[0]
# if the Optional doesn't take a value, format is:
# -s or --long
if action.nargs == 0:
part = '%s' % option_string
# if the Optional takes a value, format is:
# -s ARGS or --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
part = '%s %s' % (option_string, args_string)
# make it look optional if it's not required or in a group
if not action.required and action not in group_actions:
part = '[%s]' % part
# add the action string to the list
parts.append(part)
# insert things at the necessary indices
for i in sorted(inserts, reverse=True):
parts[i:i] = [inserts[i]]
# join all the action items with spaces
text = ' '.join([item for item in parts if item is not None])
# clean up separators for mutually exclusive groups
open = r'[\[(]'
close = r'[\])]'
text = _re.sub(r'(%s) ' % open, r'\1', text)
text = _re.sub(r' (%s)' % close, r'\1', text)
text = _re.sub(r'%s *%s' % (open, close), r'', text)
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
text = text.strip()
# return the text
return text
def _format_text(self, text):
if '%(prog)' in text:
text = text % dict(prog=self._prog)
text_width = max(self._width - self._current_indent, 11)
indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n'
def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = max(self._width - help_position, 11)
action_width = help_position - self._current_indent - 2
action_header = self._format_action_invocation(action)
# ho nelp; start on same line and add a final newline
if not action.help:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
tup = self._current_indent, '', action_width, action_header
action_header = '%*s%-*s ' % tup
indent_first = 0
# long action name; start on the next line
else:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
indent_first = help_position
# collect the pieces of the action help
parts = [action_header]
# if there was help for the action, add lines of help text
if action.help:
help_text = self._expand_help(action)
help_lines = self._split_lines(help_text, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
# or add a newline if the description doesn't end with one
elif not action_header.endswith('\n'):
parts.append('\n')
# if there are any sub-actions, add their help as well
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
# return a single string
return self._join_parts(parts)
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (option_string, args_string))
return ', '.join(parts)
def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is None:
result = '%s' % get_metavar(1)
elif action.nargs == OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs == ZERO_OR_MORE:
result = '[%s [%s ...]]' % get_metavar(2)
elif action.nargs == ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
elif action.nargs == REMAINDER:
result = '...'
elif action.nargs == PARSER:
result = '%s ...' % get_metavar(1)
else:
formats = ['%s' for _ in range(action.nargs)]
result = ' '.join(formats) % get_metavar(action.nargs)
return result
def _expand_help(self, action):
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], '__name__'):
params[name] = params[name].__name__
if params.get('choices') is not None:
choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str
return self._get_help_string(action) % params
def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
for subaction in get_subactions():
yield subaction
self._dedent()
def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.wrap(text, width)
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.fill(text, width, initial_indent=indent,
subsequent_indent=indent)
def _get_help_string(self, action):
return action.help
class RawDescriptionHelpFormatter(HelpFormatter):
"""Help message formatter which retains any formatting in descriptions.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _fill_text(self, text, width, indent):
return ''.join([indent + line for line in text.splitlines(True)])
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
"""Help message formatter which retains formatting of all help text.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _split_lines(self, text, width):
return text.splitlines()
class ArgumentDefaultsHelpFormatter(HelpFormatter):
"""Help message formatter which adds default values to argument help.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _get_help_string(self, action):
help = action.help
if '%(default)' not in action.help:
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
return help
# =====================
# Options and Arguments
# =====================
def _get_action_name(argument):
if argument is None:
return None
elif argument.option_strings:
return '/'.join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS):
return argument.metavar
elif argument.dest not in (None, SUPPRESS):
return argument.dest
else:
return None
class ArgumentError(Exception):
"""An error from creating or using an argument (optional or positional).
The string value of this exception is the message, augmented with
information about the argument that caused it.
"""
def __init__(self, argument, message):
self.argument_name = _get_action_name(argument)
self.message = message
def __str__(self):
if self.argument_name is None:
format = '%(message)s'
else:
format = 'argument %(argument_name)s: %(message)s'
return format % dict(message=self.message,
argument_name=self.argument_name)
class ArgumentTypeError(Exception):
"""An error from trying to convert a command line string to a type."""
pass
# ==============
# Action classes
# ==============
class Action(_AttributeHolder):
"""Information about how to convert command line strings to Python objects.
Action objects are used by an ArgumentParser to represent the information
needed to parse a single argument from one or more strings from the
command line. The keyword arguments to the Action constructor are also
all attributes of Action instances.
Keyword Arguments:
- option_strings -- A list of command-line option strings which
should be associated with this action.
- dest -- The name of the attribute to hold the created object(s)
- nargs -- The number of command-line arguments that should be
consumed. By default, one argument will be consumed and a single
value will be produced. Other values include:
- N (an integer) consumes N arguments (and produces a list)
- '?' consumes zero or one arguments
- '*' consumes zero or more arguments (and produces a list)
- '+' consumes one or more arguments (and produces a list)
Note that the difference between the default and nargs=1 is that
with the default, a single value will be produced, while with
nargs=1, a list containing a single value will be produced.
- const -- The value to be produced if the option is specified and the
option uses an action that takes no values.
- default -- The value to be produced if the option is not specified.
- type -- A callable that accepts a single string argument, and
returns the converted value. The standard Python types str, int,
float, and complex are useful examples of such callables. If None,
str is used.
- choices -- A container of values that should be allowed. If not None,
after a command-line argument has been converted to the appropriate
type, an exception will be raised if it is not a member of this
collection.
- required -- True if the action must always be specified at the
command line. This is only meaningful for optional command-line
arguments.
- help -- The help string describing the argument.
- metavar -- The name to be used for the option's argument with the
help string. If None, the 'dest' value will be used as the name.
"""
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
self.option_strings = option_strings
self.dest = dest
self.nargs = nargs
self.const = const
self.default = default
self.type = type
self.choices = choices
self.required = required
self.help = help
self.metavar = metavar
def _get_kwargs(self):
names = [
'option_strings',
'dest',
'nargs',
'const',
'default',
'type',
'choices',
'help',
'metavar',
]
return [(name, getattr(self, name)) for name in names]
def __call__(self, parser, namespace, values, option_string=None):
raise NotImplementedError(_('.__call__() not defined'))
class _StoreAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for store actions must be > 0; if you '
'have nothing to store, actions such as store '
'true or store const may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_StoreAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
class _StoreConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_StoreConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, self.const)
class _StoreTrueAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=False,
required=False,
help=None):
super(_StoreTrueAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=True,
default=default,
required=required,
help=help)
class _StoreFalseAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=True,
required=False,
help=None):
super(_StoreFalseAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=False,
default=default,
required=required,
help=help)
class _AppendAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for append actions must be > 0; if arg '
'strings are not supplying the value to append, '
'the append const action may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_AppendAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(values)
setattr(namespace, self.dest, items)
class _AppendConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_AppendConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(self.const)
setattr(namespace, self.dest, items)
class _CountAction(Action):
def __init__(self,
option_strings,
dest,
default=None,
required=False,
help=None):
super(_CountAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
new_count = _ensure_value(namespace, self.dest, 0) + 1
setattr(namespace, self.dest, new_count)
class _HelpAction(Action):
def __init__(self,
option_strings,
dest=SUPPRESS,
default=SUPPRESS,
help=None):
super(_HelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
parser.exit()
class _VersionAction(Action):
def __init__(self,
option_strings,
version=None,
dest=SUPPRESS,
default=SUPPRESS,
help="show program's version number and exit"):
super(_VersionAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
self.version = version
def __call__(self, parser, namespace, values, option_string=None):
version = self.version
if version is None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser.exit(message=formatter.format_help())
class _SubParsersAction(Action):
class _ChoicesPseudoAction(Action):
def __init__(self, name, help):
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sup.__init__(option_strings=[], dest=name, help=help)
def __init__(self,
option_strings,
prog,
parser_class,
dest=SUPPRESS,
help=None,
metavar=None):
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = _collections.OrderedDict()
self._choices_actions = []
super(_SubParsersAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
help=help,
metavar=metavar)
def add_parser(self, name, **kwargs):
# set prog from the existing prefix
if kwargs.get('prog') is None:
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, help)
self._choices_actions.append(choice_action)
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
self._name_parser_map[name] = parser
return parser
def _get_subactions(self):
return self._choices_actions
def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
except KeyError:
tup = parser_name, ', '.join(self._name_parser_map)
msg = _('unknown parser %r (choices: %s)') % tup
raise ArgumentError(self, msg)
# parse all the remaining options into the namespace
# store any unrecognized options on the object, so that the top
# level parser can decide what to do with them
# In case this subparser defines new defaults, we parse them
# in a new namespace object and then update the original
# namespace for the relevant parts.
subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
for key, value in vars(subnamespace).items():
setattr(namespace, key, value)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
# ==============
# Type classes
# ==============
class FileType(object):
"""Factory for creating file object types
Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function.
"""
def __init__(self, mode='r', bufsize=-1):
self._mode = mode
self._bufsize = bufsize
def __call__(self, string):
# the special argument "-" means sys.std{in,out}
if string == '-':
if 'r' in self._mode:
return _sys.stdin
elif 'w' in self._mode:
return _sys.stdout
else:
msg = _('argument "-" with mode %r') % self._mode
raise ValueError(msg)
# all other arguments are used as file names
try:
return open(string, self._mode, self._bufsize)
except IOError as e:
message = _("can't open '%s': %s")
raise ArgumentTypeError(message % (string, e))
def __repr__(self):
args = self._mode, self._bufsize
args_str = ', '.join(repr(arg) for arg in args if arg != -1)
return '%s(%s)' % (type(self).__name__, args_str)
# ===========================
# Optional and Positional Parsing
# ===========================
class Namespace(_AttributeHolder):
"""Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple
string representation.
"""
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
__hash__ = None
def __eq__(self, other):
if not isinstance(other, Namespace):
return NotImplemented
return vars(self) == vars(other)
def __ne__(self, other):
if not isinstance(other, Namespace):
return NotImplemented
return not (self == other)
def __contains__(self, key):
return key in self.__dict__
class _ActionsContainer(object):
def __init__(self,
description,
prefix_chars,
argument_default,
conflict_handler):
super(_ActionsContainer, self).__init__()
self.description = description
self.argument_default = argument_default
self.prefix_chars = prefix_chars
self.conflict_handler = conflict_handler
# set up registries
self._registries = {}
# register actions
self.register('action', None, _StoreAction)
self.register('action', 'store', _StoreAction)
self.register('action', 'store_const', _StoreConstAction)
self.register('action', 'store_true', _StoreTrueAction)
self.register('action', 'store_false', _StoreFalseAction)
self.register('action', 'append', _AppendAction)
self.register('action', 'append_const', _AppendConstAction)
self.register('action', 'count', _CountAction)
self.register('action', 'help', _HelpAction)
self.register('action', 'version', _VersionAction)
self.register('action', 'parsers', _SubParsersAction)
# raise an exception if the conflict handler is invalid
self._get_handler()
# action storage
self._actions = []
self._option_string_actions = {}
# groups
self._action_groups = []
self._mutually_exclusive_groups = []
# defaults storage
self._defaults = {}
# determines whether an "option" looks like a negative number
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
# whether or not there are any optionals that look like negative
# numbers -- uses a list so it can be shared and edited
self._has_negative_number_optionals = []
# ====================
# Registration methods
# ====================
def register(self, registry_name, value, object):
registry = self._registries.setdefault(registry_name, {})
registry[value] = object
def _registry_get(self, registry_name, value, default=None):
return self._registries[registry_name].get(value, default)
# ==================================
# Namespace default accessor methods
# ==================================
def set_defaults(self, **kwargs):
self._defaults.update(kwargs)
# if these defaults match any existing arguments, replace
# the previous default on the object with the new one
for action in self._actions:
if action.dest in kwargs:
action.default = kwargs[action.dest]
def get_default(self, dest):
for action in self._actions:
if action.dest == dest and action.default is not None:
return action.default
return self._defaults.get(dest, None)
# =======================
# Adding argument actions
# =======================
def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, parse a positional
# argument
chars = self.prefix_chars
if not args or len(args) == 1 and args[0][0] not in chars:
if args and 'dest' in kwargs:
raise ValueError('dest supplied twice for positional argument')
kwargs = self._get_positional_kwargs(*args, **kwargs)
# otherwise, we're adding an optional argument
else:
kwargs = self._get_optional_kwargs(*args, **kwargs)
# if no default was supplied, use the parser-level default
if 'default' not in kwargs:
dest = kwargs['dest']
if dest in self._defaults:
kwargs['default'] = self._defaults[dest]
elif self.argument_default is not None:
kwargs['default'] = self.argument_default
# create the action object, and add it to the parser
action_class = self._pop_action_class(kwargs)
if not _callable(action_class):
raise ValueError('unknown action "%s"' % (action_class,))
action = action_class(**kwargs)
# raise an error if the action type is not callable
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
raise ValueError('%r is not callable' % (type_func,))
# raise an error if the metavar does not match the type
if hasattr(self, "_get_formatter"):
try:
self._get_formatter()._format_args(action, None)
except TypeError:
raise ValueError("length of metavar tuple does not match nargs")
return self._add_action(action)
def add_argument_group(self, *args, **kwargs):
group = _ArgumentGroup(self, *args, **kwargs)
self._action_groups.append(group)
return group
def add_mutually_exclusive_group(self, **kwargs):
group = _MutuallyExclusiveGroup(self, **kwargs)
self._mutually_exclusive_groups.append(group)
return group
def _add_action(self, action):
# resolve any conflicts
self._check_conflict(action)
# add to actions list
self._actions.append(action)
action.container = self
# index the action by any option strings it has
for option_string in action.option_strings:
self._option_string_actions[option_string] = action
# set the flag if any option strings look like negative numbers
for option_string in action.option_strings:
if self._negative_number_matcher.match(option_string):
if not self._has_negative_number_optionals:
self._has_negative_number_optionals.append(True)
# return the created action
return action
def _remove_action(self, action):
self._actions.remove(action)
def _add_container_actions(self, container):
# collect groups by titles
title_group_map = {}
for group in self._action_groups:
if group.title in title_group_map:
msg = _('cannot merge actions - two groups are named %r')
raise ValueError(msg % (group.title))
title_group_map[group.title] = group
# map each action to its group
group_map = {}
for group in container._action_groups:
# if a group with the title exists, use that, otherwise
# create a new group matching the container's group
if group.title not in title_group_map:
title_group_map[group.title] = self.add_argument_group(
title=group.title,
description=group.description,
conflict_handler=group.conflict_handler)
# map the actions to their new group
for action in group._group_actions:
group_map[action] = title_group_map[group.title]
# add container's mutually exclusive groups
# NOTE: if add_mutually_exclusive_group ever gains title= and
# description= then this code will need to be expanded as above
for group in container._mutually_exclusive_groups:
mutex_group = self.add_mutually_exclusive_group(
required=group.required)
# map the actions to their new mutex group
for action in group._group_actions:
group_map[action] = mutex_group
# add all actions to this container or their group
for action in container._actions:
group_map.get(action, self)._add_action(action)
def _get_positional_kwargs(self, dest, **kwargs):
# make sure required is not specified
if 'required' in kwargs:
msg = _("'required' is an invalid argument for positionals")
raise TypeError(msg)
# mark positional arguments as required if at least one is
# always required
if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
kwargs['required'] = True
if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
kwargs['required'] = True
# return the keyword arguments with no option strings
return dict(kwargs, dest=dest, option_strings=[])
def _get_optional_kwargs(self, *args, **kwargs):
# determine short and long option strings
option_strings = []
long_option_strings = []
for option_string in args:
# error on strings that don't start with an appropriate prefix
if not option_string[0] in self.prefix_chars:
msg = _('invalid option string %r: '
'must start with a character %r')
tup = option_string, self.prefix_chars
raise ValueError(msg % tup)
# strings starting with two prefix characters are long options
option_strings.append(option_string)
if option_string[0] in self.prefix_chars:
if len(option_string) > 1:
if option_string[1] in self.prefix_chars:
long_option_strings.append(option_string)
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
dest = kwargs.pop('dest', None)
if dest is None:
if long_option_strings:
dest_option_string = long_option_strings[0]
else:
dest_option_string = option_strings[0]
dest = dest_option_string.lstrip(self.prefix_chars)
if not dest:
msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string)
dest = dest.replace('-', '_')
# return the updated keyword arguments
return dict(kwargs, dest=dest, option_strings=option_strings)
def _pop_action_class(self, kwargs, default=None):
action = kwargs.pop('action', default)
return self._registry_get('action', action, action)
def _get_handler(self):
# determine function from conflict handler string
handler_func_name = '_handle_conflict_%s' % self.conflict_handler
try:
return getattr(self, handler_func_name)
except AttributeError:
msg = _('invalid conflict_resolution value: %r')
raise ValueError(msg % self.conflict_handler)
def _check_conflict(self, action):
# find all options that conflict with this option
confl_optionals = []
for option_string in action.option_strings:
if option_string in self._option_string_actions:
confl_optional = self._option_string_actions[option_string]
confl_optionals.append((option_string, confl_optional))
# resolve any conflicts
if confl_optionals:
conflict_handler = self._get_handler()
conflict_handler(action, confl_optionals)
def _handle_conflict_error(self, action, conflicting_actions):
message = _('conflicting option string(s): %s')
conflict_string = ', '.join([option_string
for option_string, action
in conflicting_actions])
raise ArgumentError(action, message % conflict_string)
def _handle_conflict_resolve(self, action, conflicting_actions):
# remove all conflicting options
for option_string, action in conflicting_actions:
# remove the conflicting option
action.option_strings.remove(option_string)
self._option_string_actions.pop(option_string, None)
# if the option now has no option string, remove it from the
# container holding it
if not action.option_strings:
action.container._remove_action(action)
class _ArgumentGroup(_ActionsContainer):
def __init__(self, container, title=None, description=None, **kwargs):
# add any missing keyword arguments by checking the container
update = kwargs.setdefault
update('conflict_handler', container.conflict_handler)
update('prefix_chars', container.prefix_chars)
update('argument_default', container.argument_default)
super_init = super(_ArgumentGroup, self).__init__
super_init(description=description, **kwargs)
# group attributes
self.title = title
self._group_actions = []
# share most attributes with the container
self._registries = container._registries
self._actions = container._actions
self._option_string_actions = container._option_string_actions
self._defaults = container._defaults
self._has_negative_number_optionals = \
container._has_negative_number_optionals
self._mutually_exclusive_groups = container._mutually_exclusive_groups
def _add_action(self, action):
action = super(_ArgumentGroup, self)._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action)
class _MutuallyExclusiveGroup(_ArgumentGroup):
def __init__(self, container, required=False):
super(_MutuallyExclusiveGroup, self).__init__(container)
self.required = required
self._container = container
def _add_action(self, action):
if action.required:
msg = _('mutually exclusive arguments must be optional')
raise ValueError(msg)
action = self._container._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
self._container._remove_action(action)
self._group_actions.remove(action)
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
version=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True):
if version is not None:
import warnings
warnings.warn(
"""The "version" argument to ArgumentParser is deprecated. """
"""Please use """
""""add_argument(..., action='version', version="N", ...)" """
"""instead""", DeprecationWarning)
superinit = super(ArgumentParser, self).__init__
superinit(description=description,
prefix_chars=prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler)
# default setting for prog
if prog is None:
prog = _os.path.basename(_sys.argv[0])
self.prog = prog
self.usage = usage
self.epilog = epilog
self.version = version
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('optional arguments'))
self._subparsers = None
# register types
def identity(string):
return string
self.register('type', None, identity)
# add help and version arguments if necessary
# (using explicit default to override global argument_default)
default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
if self.add_help:
self.add_argument(
default_prefix+'h', default_prefix*2+'help',
action='help', default=SUPPRESS,
help=_('show this help message and exit'))
if self.version:
self.add_argument(
default_prefix+'v', default_prefix*2+'version',
action='version', default=SUPPRESS,
version=self.version,
help=_("show program's version number and exit"))
# add parent arguments and defaults
for parent in parents:
self._add_container_actions(parent)
try:
defaults = parent._defaults
except AttributeError:
pass
else:
self._defaults.update(defaults)
# =======================
# Pretty __repr__ methods
# =======================
def _get_kwargs(self):
names = [
'prog',
'usage',
'description',
'version',
'formatter_class',
'conflict_handler',
'add_help',
]
return [(name, getattr(self, name)) for name in names]
# ==================================
# Optional/Positional adding methods
# ==================================
def add_subparsers(self, **kwargs):
if self._subparsers is not None:
self.error(_('cannot have multiple subparser arguments'))
# add the parser class to the arguments if it's not present
kwargs.setdefault('parser_class', type(self))
if 'title' in kwargs or 'description' in kwargs:
title = _(kwargs.pop('title', 'subcommands'))
description = _(kwargs.pop('description', None))
self._subparsers = self.add_argument_group(title, description)
else:
self._subparsers = self._positionals
# prog defaults to the usage message of this parser, skipping
# optional arguments and with no "usage:" prefix
if kwargs.get('prog') is None:
formatter = self._get_formatter()
positionals = self._get_positional_actions()
groups = self._mutually_exclusive_groups
formatter.add_usage(self.usage, positionals, groups, '')
kwargs['prog'] = formatter.format_help().strip()
# create the parsers action and add it to the positionals list
parsers_class = self._pop_action_class(kwargs, 'parsers')
action = parsers_class(option_strings=[], **kwargs)
self._subparsers._add_action(action)
# return the created parsers action
return action
def _add_action(self, action):
if action.option_strings:
self._optionals._add_action(action)
else:
self._positionals._add_action(action)
return action
def _get_optional_actions(self):
return [action
for action in self._actions
if action.option_strings]
def _get_positional_actions(self):
return [action
for action in self._actions
if not action.option_strings]
# =====================================
# Command line argument parsing methods
# =====================================
def parse_args(self, args=None, namespace=None):
args, argv = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_args(self, args=None, namespace=None):
if args is None:
# args default to the system args
args = _sys.argv[1:]
else:
# make sure that args are mutable
args = list(args)
# default Namespace built from parser defaults
if namespace is None:
namespace = Namespace()
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
setattr(namespace, action.dest, action.default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
try:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
def _parse_known_args(self, arg_strings, namespace):
# replace arg strings that are file references
if self.fromfile_prefix_chars is not None:
arg_strings = self._read_args_from_files(arg_strings)
# map all mutually exclusive arguments to the other arguments
# they can't occur with
action_conflicts = {}
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern
# which has an 'O' if there is an option at an index,
# an 'A' if there is an argument, or a '-' if there is a '--'
option_string_indices = {}
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
# all args after -- are non-options
if arg_string == '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
# otherwise, add the arg to the arg strings
# and note the index if it was an option
else:
option_tuple = self._parse_optional(arg_string)
if option_tuple is None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
# join the pieces together to form the pattern
arg_strings_pattern = ''.join(arg_string_pattern_parts)
# converts arg strings to the appropriate and then takes the action
seen_actions = set()
seen_non_default_actions = set()
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen arguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
# take the action if we didn't receive a SUPPRESS value
# (e.g. from a default)
if argument_values is not SUPPRESS:
action(self, namespace, argument_values, option_string)
# function to convert arg_strings into an optional action
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
action, option_string, explicit_arg = option_tuple
# identify additional optionals in the same arg string
# (e.g. -xyz is the same as -x -y -z if no args are required)
match_argument = self._match_argument
action_tuples = []
while True:
# if we found no optional action, skip it
if action is None:
extras.append(arg_strings[start_index])
return start_index + 1
# if there is an explicit argument, try to match the
# optional's string arguments to only this
if explicit_arg is not None:
arg_count = match_argument(action, 'A')
# if the action is a single-dash option and takes no
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
new_explicit_arg = explicit_arg[1:] or None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
explicit_arg = new_explicit_arg
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
elif arg_count == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if there is no explicit argument, try to match the
# optional's string arguments with the following strings
# if successful, exit the loop
else:
start = start_index + 1
selected_patterns = arg_strings_pattern[start:]
arg_count = match_argument(action, selected_patterns)
stop = start + arg_count
args = arg_strings[start:stop]
action_tuples.append((action, args, option_string))
break
# add the Optional to the list and return the index at which
# the Optional's string args stopped
assert action_tuples
for action, args, option_string in action_tuples:
take_action(action, args, option_string)
return stop
# the list of Positionals left to be parsed; this is modified
# by consume_positionals()
positionals = self._get_positional_actions()
# function to convert arg_strings into positional actions
def consume_positionals(start_index):
# match as many Positionals as possible
match_partial = self._match_arguments_partial
selected_pattern = arg_strings_pattern[start_index:]
arg_counts = match_partial(positionals, selected_pattern)
# slice off the appropriate arg strings for each Positional
# and add the Positional and its args to the list
for action, arg_count in zip(positionals, arg_counts):
args = arg_strings[start_index: start_index + arg_count]
start_index += arg_count
take_action(action, args)
# slice off the Positionals that we just parsed and return the
# index at which the Positionals' string args stopped
positionals[:] = positionals[len(arg_counts):]
return start_index
# consume Positionals and Optionals alternately, until we have
# passed the last option string
extras = []
start_index = 0
if option_string_indices:
max_option_string_index = max(option_string_indices)
else:
max_option_string_index = -1
while start_index <= max_option_string_index:
# consume any Positionals preceding the next option
next_option_string_index = min([
index
for index in option_string_indices
if index >= start_index])
if start_index != next_option_string_index:
positionals_end_index = consume_positionals(start_index)
# only try to parse the next optional if we didn't consume
# the option string during the positionals parsing
if positionals_end_index > start_index:
start_index = positionals_end_index
continue
else:
start_index = positionals_end_index
# if we consumed all the positionals we could and we're not
# at the index of an option string, there were extra arguments
if start_index not in option_string_indices:
strings = arg_strings[start_index:next_option_string_index]
extras.extend(strings)
start_index = next_option_string_index
# consume the next optional and any arguments for it
start_index = consume_optional(start_index)
# consume any positionals following the last Optional
stop_index = consume_positionals(start_index)
# if we didn't consume all the argument strings, there were extras
extras.extend(arg_strings[stop_index:])
# if we didn't use all the Positional objects, there were too few
# arg strings supplied.
if positionals:
self.error(_('too few arguments'))
# make sure all required actions were present, and convert defaults.
for action in self._actions:
if action not in seen_actions:
if action.required:
name = _get_action_name(action)
self.error(_('argument %s is required') % name)
else:
# Convert action default now instead of doing it before
# parsing arguments to avoid calling convert functions
# twice (which may fail) if the argument was given, but
# only if it was defined already in the namespace
if (action.default is not None and
isinstance(action.default, basestring) and
hasattr(namespace, action.dest) and
action.default is getattr(namespace, action.dest)):
setattr(namespace, action.dest,
self._get_value(action, action.default))
# make sure all required groups had one option present
for group in self._mutually_exclusive_groups:
if group.required:
for action in group._group_actions:
if action in seen_non_default_actions:
break
# if no actions were used, report the error
else:
names = [_get_action_name(action)
for action in group._group_actions
if action.help is not SUPPRESS]
msg = _('one of the arguments %s is required')
self.error(msg % ' '.join(names))
# return the updated namespace and the extra arguments
return namespace, extras
def _read_args_from_files(self, arg_strings):
# expand arguments referencing files
new_arg_strings = []
for arg_string in arg_strings:
# for regular arguments, just add them back into the list
if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
new_arg_strings.append(arg_string)
# replace arguments referencing files with the file content
else:
try:
args_file = open(arg_string[1:])
try:
arg_strings = []
for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
finally:
args_file.close()
except IOError:
err = _sys.exc_info()[1]
self.error(str(err))
# return the modified argument list
return new_arg_strings
def convert_arg_line_to_args(self, arg_line):
return [arg_line]
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = _('expected %s argument(s)') % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_arguments_partial(self, actions, arg_strings_pattern):
# progressively shorten the actions list by slicing off the
# final actions until we find a match
result = []
for i in range(len(actions), 0, -1):
actions_slice = actions[:i]
pattern = ''.join([self._get_nargs_pattern(action)
for action in actions_slice])
match = _re.match(pattern, arg_strings_pattern)
if match is not None:
result.extend([len(string) for string in match.groups()])
break
# return the list of arg string counts
return result
def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
return None
# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
return None
# if the option string is present in the parser, return the action
if arg_string in self._option_string_actions:
action = self._option_string_actions[arg_string]
return action, arg_string, None
# if it's just a single character, it was meant to be positional
if len(arg_string) == 1:
return None
# if the option string before the "=" is present, return the action
if '=' in arg_string:
option_string, explicit_arg = arg_string.split('=', 1)
if option_string in self._option_string_actions:
action = self._option_string_actions[option_string]
return action, option_string, explicit_arg
# search through all possible prefixes of the option string
# and all actions in the parser for possible interpretations
option_tuples = self._get_option_tuples(arg_string)
# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
for action, option_string, explicit_arg in option_tuples])
tup = arg_string, options
self.error(_('ambiguous option: %s could match %s') % tup)
# if exactly one action matched, this segmentation is good,
# so return the parsed action
elif len(option_tuples) == 1:
option_tuple, = option_tuples
return option_tuple
# if it was not found as an option, but it looks like a negative
# number, it was meant to be positional
# unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string):
if not self._has_negative_number_optionals:
return None
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
# it was meant to be an optional but there is no such option
# in this parser (though it might be a valid option in a subparser)
return None, arg_string, None
def _get_option_tuples(self, option_string):
result = []
# option strings starting with two prefix characters are only
# split at the '='
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
if '=' in option_string:
option_prefix, explicit_arg = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
for option_string in self._option_string_actions:
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# single character options can be concatenated with their arguments
# but multiple character options always have to have their argument
# separate
elif option_string[0] in chars and option_string[1] not in chars:
option_prefix = option_string
explicit_arg = None
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
for option_string in self._option_string_actions:
if option_string == short_option_prefix:
action = self._option_string_actions[option_string]
tup = action, option_string, short_explicit_arg
result.append(tup)
elif option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# shouldn't ever get here
else:
self.error(_('unexpected option string: %s') % option_string)
# return the collected option tuples
return result
def _get_nargs_pattern(self, action):
# in all examples below, we have to allow for '--' args
# which are represented as '-' in the pattern
nargs = action.nargs
# the default (None) is assumed to be a single argument
if nargs is None:
nargs_pattern = '(-*A-*)'
# allow zero or one arguments
elif nargs == OPTIONAL:
nargs_pattern = '(-*A?-*)'
# allow zero or more arguments
elif nargs == ZERO_OR_MORE:
nargs_pattern = '(-*[A-]*)'
# allow one or more arguments
elif nargs == ONE_OR_MORE:
nargs_pattern = '(-*A[A-]*)'
# allow any number of options or arguments
elif nargs == REMAINDER:
nargs_pattern = '([-AO]*)'
# allow one argument followed by any number of options or arguments
elif nargs == PARSER:
nargs_pattern = '(-*A[-AO]*)'
# all others should be integers
else:
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
# if this is an optional action, -- is not allowed
if action.option_strings:
nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = nargs_pattern.replace('-', '')
# return the pattern
return nargs_pattern
# ========================
# Value conversion methods
# ========================
def _get_values(self, action, arg_strings):
# for everything but PARSER, REMAINDER args, strip out first '--'
if action.nargs not in [PARSER, REMAINDER]:
try:
arg_strings.remove('--')
except ValueError:
pass
# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
if action.option_strings:
value = action.const
else:
value = action.default
if isinstance(value, basestring):
value = self._get_value(action, value)
self._check_value(action, value)
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
# single argument or optional argument produces a single value
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
arg_string, = arg_strings
value = self._get_value(action, arg_string)
self._check_value(action, value)
# REMAINDER arguments convert all values, checking none
elif action.nargs == REMAINDER:
value = [self._get_value(action, v) for v in arg_strings]
# PARSER arguments convert all values, but check only the first
elif action.nargs == PARSER:
value = [self._get_value(action, v) for v in arg_strings]
self._check_value(action, value[0])
# all other types of nargs produce a list
else:
value = [self._get_value(action, v) for v in arg_strings]
for v in value:
self._check_value(action, v)
# return the converted value
return value
def _get_value(self, action, arg_string):
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
msg = _('%r is not callable')
raise ArgumentError(action, msg % type_func)
# convert the value to the appropriate type
try:
result = type_func(arg_string)
# ArgumentTypeErrors indicate errors
except ArgumentTypeError:
name = getattr(action.type, '__name__', repr(action.type))
msg = str(_sys.exc_info()[1])
raise ArgumentError(action, msg)
# TypeErrors or ValueErrors also indicate errors
except (TypeError, ValueError):
name = getattr(action.type, '__name__', repr(action.type))
msg = _('invalid %s value: %r')
raise ArgumentError(action, msg % (name, arg_string))
# return the converted value
return result
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
tup = value, ', '.join(map(repr, action.choices))
msg = _('invalid choice: %r (choose from %s)') % tup
raise ArgumentError(action, msg)
# =======================
# Help-formatting methods
# =======================
def format_usage(self):
formatter = self._get_formatter()
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
return formatter.format_help()
def format_help(self):
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
def format_version(self):
import warnings
warnings.warn(
'The format_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
formatter = self._get_formatter()
formatter.add_text(self.version)
return formatter.format_help()
def _get_formatter(self):
return self.formatter_class(prog=self.prog)
# =====================
# Help-printing methods
# =====================
def print_usage(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_usage(), file)
def print_help(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_help(), file)
def print_version(self, file=None):
import warnings
warnings.warn(
'The print_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
self._print_message(self.format_version(), file)
def _print_message(self, message, file=None):
if message:
if file is None:
file = _sys.stderr
file.write(message)
# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
if message:
self._print_message(message, _sys.stderr)
_sys.exit(status)
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
self.exit(2, _('%s: error: %s\n') % (self.prog, message))
|
{
"pile_set_name": "Github"
}
|
import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum += val * n
self.cnt += n
self.avg = self.sum / self.cnt
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res
class Cutout(object):
def __init__(self, length):
self.length = length
def __call__(self, img):
h, w = img.size(1), img.size(2)
mask = np.ones((h, w), np.float32)
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length // 2, 0, h)
y2 = np.clip(y + self.length // 2, 0, h)
x1 = np.clip(x - self.length // 2, 0, w)
x2 = np.clip(x + self.length // 2, 0, w)
mask[y1: y2, x1: x2] = 0.
mask = torch.from_numpy(mask)
mask = mask.expand_as(img)
img *= mask
return img
def _data_transforms_cifar10(args):
CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124]
CIFAR_STD = [0.24703233, 0.24348505, 0.26158768]
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(CIFAR_MEAN, CIFAR_STD),
])
if args.cutout:
train_transform.transforms.append(Cutout(args.cutout_length))
valid_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(CIFAR_MEAN, CIFAR_STD),
])
return train_transform, valid_transform
def count_parameters_in_MB(model):
return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if "auxiliary" not in name)/1e6
def save_checkpoint(state, is_best, save):
filename = os.path.join(save, 'checkpoint.pth.tar')
torch.save(state, filename)
if is_best:
best_filename = os.path.join(save, 'model_best.pth.tar')
shutil.copyfile(filename, best_filename)
def save(model, model_path):
torch.save(model.state_dict(), model_path)
def load(model, model_path):
model.load_state_dict(torch.load(model_path))
def drop_path(x, drop_prob):
if drop_prob > 0.:
keep_prob = 1.-drop_prob
mask = Variable(torch.cuda.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob))
x.div_(keep_prob)
x.mul_(mask)
return x
def create_exp_dir(path, scripts_to_save=None):
if not os.path.exists(path):
os.mkdir(path)
print('Experiment dir : {}'.format(path))
if scripts_to_save is not None:
os.mkdir(os.path.join(path, 'scripts'))
for script in scripts_to_save:
dst_file = os.path.join(path, 'scripts', os.path.basename(script))
shutil.copyfile(script, dst_file)
|
{
"pile_set_name": "Github"
}
|
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const Modem = require("docker-modem");
const container_1 = require("./container");
const image_1 = require("./image");
const volume_1 = require("./volume");
const network_1 = require("./network");
const node_1 = require("./node");
const plugin_1 = require("./plugin");
const secret_1 = require("./secret");
const service_1 = require("./service");
const swarm_1 = require("./swarm");
const task_1 = require("./task");
/**
* Docker class with all methods
*/
class Docker {
/**
* Creates the Docker Object
* @param {Object} opts Docker options
*/
constructor(opts) {
this.modem = new Modem(opts);
this.container = new container_1.default(this.modem);
this.image = new image_1.default(this.modem);
this.volume = new volume_1.default(this.modem);
this.network = new network_1.default(this.modem);
this.node = new node_1.default(this.modem);
this.plugin = new plugin_1.default(this.modem);
this.secret = new secret_1.default(this.modem);
this.service = new service_1.default(this.modem);
this.swarm = new swarm_1.default(this.modem);
this.task = new task_1.default(this.modem);
}
/**
* Validate credentials for a registry and get identity token,
* if available, for accessing the registry without password
* https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/check-auth-configuration
* @param {Object} opts Auth options
* @return {Promise} Promise returning the result
*/
auth(opts) {
const call = {
path: '/auth?',
method: 'POST',
options: opts,
statusCodes: {
200: true,
204: true,
500: 'server error'
}
};
return new Promise((resolve, reject) => {
this.modem.dial(call, (err, data) => {
if (err)
return reject(err);
resolve(data);
});
});
}
/**
* Get system wide information about docker
* https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/display-system-wide-information
* @return {Promise} Promise returning the result
*/
info() {
const call = {
path: '/info?',
method: 'GET',
statusCodes: {
200: true,
500: 'server error'
}
};
return new Promise((resolve, reject) => {
this.modem.dial(call, (err, data) => {
if (err)
return reject(err);
resolve(data);
});
});
}
/**
* Get docker version information of server
* https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/show-the-docker-version-information
* @return {Promise} Promise returning the result
*/
version() {
const call = {
path: '/version?',
method: 'GET',
statusCodes: {
200: true,
500: 'server error'
}
};
return new Promise((resolve, reject) => {
this.modem.dial(call, (err, data) => {
if (err)
return reject(err);
resolve(data);
});
});
}
/**
* Ping the docker server
* https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/ping-the-docker-server
* @return {Promise} Promise returning the result
*/
ping() {
const call = {
path: '/_ping?',
method: 'GET',
statusCodes: {
200: true,
500: 'server error'
}
};
return new Promise((resolve, reject) => {
this.modem.dial(call, (err, data) => {
if (err)
return reject(err);
resolve(data);
});
});
}
/**
* Get container events from docker, can be in real time via streaming or via polling (with since)
* https://docs.docker.com/engine/reference/api/docker_remote_api_v1.24/#/monitor-docker-s-events
* @param {Object} opts Options to send with the request (optional)
* @return {Promise} Promise returning the result
*/
events(opts = {}) {
const call = {
path: '/events?',
method: 'GET',
options: opts,
isStream: true,
statusCodes: {
200: true,
500: 'server error'
}
};
return new Promise((resolve, reject) => {
this.modem.dial(call, (err, data) => {
if (err)
return reject(err);
resolve(data);
});
});
}
}
exports.Docker = Docker;
//# sourceMappingURL=docker.js.map
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>HTMLDocument (Java SE 12 & JDK 12 )</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords" content="org.w3c.dom.html.HTMLDocument interface">
<meta name="keywords" content="getTitle()">
<meta name="keywords" content="setTitle()">
<meta name="keywords" content="getReferrer()">
<meta name="keywords" content="getDomain()">
<meta name="keywords" content="getURL()">
<meta name="keywords" content="getBody()">
<meta name="keywords" content="setBody()">
<meta name="keywords" content="getImages()">
<meta name="keywords" content="getApplets()">
<meta name="keywords" content="getLinks()">
<meta name="keywords" content="getForms()">
<meta name="keywords" content="getAnchors()">
<meta name="keywords" content="getCookie()">
<meta name="keywords" content="setCookie()">
<meta name="keywords" content="open()">
<meta name="keywords" content="close()">
<meta name="keywords" content="write()">
<meta name="keywords" content="writeln()">
<meta name="keywords" content="getElementsByName()">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../jquery/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-migrate-3.0.1.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="HTMLDocument (Java SE 12 & JDK 12 )";
}
}
catch(err) {
}
//-->
var data = {"i0":6,"i1":6,"i2":6,"i3":6,"i4":6,"i5":6,"i6":6,"i7":6,"i8":6,"i9":6,"i10":6,"i11":6,"i12":6,"i13":6,"i14":6,"i15":6,"i16":6,"i17":6,"i18":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../index.html">Overview</a></li>
<li><a href="../../../../module-summary.html">Module</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/HTMLDocument.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 & JDK 12</strong> </div></div>
</div>
<div class="subNav">
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
</div>
<a id="skip.navbar.top">
<!-- -->
</a>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<!-- ======== START OF CLASS DATA ======== -->
<main role="main">
<div class="header">
<div class="subTitle"><span class="moduleLabelInType">Module</span> <a href="../../../../module-summary.html">jdk.xml.dom</a></div>
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="package-summary.html">org.w3c.dom.html</a></div>
<h2 title="Interface HTMLDocument" class="title">Interface HTMLDocument</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><code><a href="../../../../../java.xml/org/w3c/dom/Document.html" title="interface in org.w3c.dom">Document</a></code>, <code><a href="../../../../../java.xml/org/w3c/dom/Node.html" title="interface in org.w3c.dom">Node</a></code></dd>
</dl>
<hr>
<pre>public interface <span class="typeNameLabel">HTMLDocument</span>
extends <a href="../../../../../java.xml/org/w3c/dom/Document.html" title="interface in org.w3c.dom">Document</a></pre>
<div class="block">An <code>HTMLDocument</code> is the root of the HTML hierarchy and holds
the entire content. Besides providing access to the hierarchy, it also
provides some convenience methods for accessing certain sets of
information from the document.
<p> The following properties have been deprecated in favor of the
corresponding ones for the <code>BODY</code> element: alinkColor background
bgColor fgColor linkColor vlinkColor In DOM Level 2, the method
<code>getElementById</code> is inherited from the <code>Document</code>
interface where it was moved.
<p>See also the <a href='http://www.w3.org/TR/2000/CR-DOM-Level-2-20000510'>Document Object Model (DOM) Level 2 Specification</a>.</div>
<dl>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>1.4, DOM Level 2</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a id="fields.inherited.from.class.org.w3c.dom.Node">
<!-- -->
</a>
<h3>Fields declared in interface org.w3c.dom.<a href="../../../../../java.xml/org/w3c/dom/Node.html" title="interface in org.w3c.dom">Node</a></h3>
<code><a href="../../../../../java.xml/org/w3c/dom/Node.html#ATTRIBUTE_NODE">ATTRIBUTE_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#CDATA_SECTION_NODE">CDATA_SECTION_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#COMMENT_NODE">COMMENT_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_FRAGMENT_NODE">DOCUMENT_FRAGMENT_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_NODE">DOCUMENT_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_POSITION_CONTAINED_BY">DOCUMENT_POSITION_CONTAINED_BY</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_POSITION_CONTAINS">DOCUMENT_POSITION_CONTAINS</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_POSITION_DISCONNECTED">DOCUMENT_POSITION_DISCONNECTED</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_POSITION_FOLLOWING">DOCUMENT_POSITION_FOLLOWING</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC">DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_POSITION_PRECEDING">DOCUMENT_POSITION_PRECEDING</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#DOCUMENT_TYPE_NODE">DOCUMENT_TYPE_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#ELEMENT_NODE">ELEMENT_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#ENTITY_NODE">ENTITY_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#ENTITY_REFERENCE_NODE">ENTITY_REFERENCE_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#NOTATION_NODE">NOTATION_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#PROCESSING_INSTRUCTION_NODE">PROCESSING_INSTRUCTION_NODE</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#TEXT_NODE">TEXT_NODE</a></code></li>
</ul>
</li>
</ul>
</section>
<!-- ========== METHOD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<div class="memberSummary">
<div role="tablist" aria-orientation="horizontal"><button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t3" class="tableTab" onclick="show(4);">Abstract Methods</button></div>
<div id="memberSummary_tabpanel" role="tabpanel">
<table aria-labelledby="t0">
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor" id="i0">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#close()">close</a></span>()</code></th>
<td class="colLast">
<div class="block">Closes a document stream opened by <code>open()</code> and forces
rendering.</div>
</td>
</tr>
<tr class="rowColor" id="i1">
<td class="colFirst"><code><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getAnchors()">getAnchors</a></span>()</code></th>
<td class="colLast">
<div class="block">A collection of all the anchor (<code>A</code> ) elements in a document
with a value for the <code>name</code> attribute.</div>
</td>
</tr>
<tr class="altColor" id="i2">
<td class="colFirst"><code><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getApplets()">getApplets</a></span>()</code></th>
<td class="colLast">
<div class="block">A collection of all the <code>OBJECT</code> elements that include
applets and <code>APPLET</code> ( deprecated ) elements in a document.</div>
</td>
</tr>
<tr class="rowColor" id="i3">
<td class="colFirst"><code><a href="HTMLElement.html" title="interface in org.w3c.dom.html">HTMLElement</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getBody()">getBody</a></span>()</code></th>
<td class="colLast">
<div class="block">The element that contains the content for the document.</div>
</td>
</tr>
<tr class="altColor" id="i4">
<td class="colFirst"><code><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getCookie()">getCookie</a></span>()</code></th>
<td class="colLast">
<div class="block">The cookies associated with this document.</div>
</td>
</tr>
<tr class="rowColor" id="i5">
<td class="colFirst"><code><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getDomain()">getDomain</a></span>()</code></th>
<td class="colLast">
<div class="block">The domain name of the server that served the document, or
<code>null</code> if the server cannot be identified by a domain name.</div>
</td>
</tr>
<tr class="altColor" id="i6">
<td class="colFirst"><code><a href="../../../../../java.xml/org/w3c/dom/NodeList.html" title="interface in org.w3c.dom">NodeList</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getElementsByName(java.lang.String)">getElementsByName</a></span>​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> elementName)</code></th>
<td class="colLast">
<div class="block">Returns the (possibly empty) collection of elements whose
<code>name</code> value is given by <code>elementName</code> .</div>
</td>
</tr>
<tr class="rowColor" id="i7">
<td class="colFirst"><code><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getForms()">getForms</a></span>()</code></th>
<td class="colLast">
<div class="block">A collection of all the forms of a document.</div>
</td>
</tr>
<tr class="altColor" id="i8">
<td class="colFirst"><code><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getImages()">getImages</a></span>()</code></th>
<td class="colLast">
<div class="block">A collection of all the <code>IMG</code> elements in a document.</div>
</td>
</tr>
<tr class="rowColor" id="i9">
<td class="colFirst"><code><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getLinks()">getLinks</a></span>()</code></th>
<td class="colLast">
<div class="block">A collection of all <code>AREA</code> elements and anchor (
<code>A</code> ) elements in a document with a value for the
<code>href</code> attribute.</div>
</td>
</tr>
<tr class="altColor" id="i10">
<td class="colFirst"><code><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getReferrer()">getReferrer</a></span>()</code></th>
<td class="colLast">
<div class="block">Returns the URI of the page that linked to this page.</div>
</td>
</tr>
<tr class="rowColor" id="i11">
<td class="colFirst"><code><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getTitle()">getTitle</a></span>()</code></th>
<td class="colLast">
<div class="block">The title of a document as specified by the <code>TITLE</code> element
in the head of the document.</div>
</td>
</tr>
<tr class="altColor" id="i12">
<td class="colFirst"><code><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#getURL()">getURL</a></span>()</code></th>
<td class="colLast">
<div class="block">The complete URI of the document.</div>
</td>
</tr>
<tr class="rowColor" id="i13">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#open()">open</a></span>()</code></th>
<td class="colLast">
<div class="block">Note.</div>
</td>
</tr>
<tr class="altColor" id="i14">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#setBody(org.w3c.dom.html.HTMLElement)">setBody</a></span>​(<a href="HTMLElement.html" title="interface in org.w3c.dom.html">HTMLElement</a> body)</code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor" id="i15">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#setCookie(java.lang.String)">setCookie</a></span>​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> cookie)</code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor" id="i16">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#setTitle(java.lang.String)">setTitle</a></span>​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> title)</code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor" id="i17">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#write(java.lang.String)">write</a></span>​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> text)</code></th>
<td class="colLast">
<div class="block">Write a string of text to a document stream opened by
<code>open()</code> .</div>
</td>
</tr>
<tr class="altColor" id="i18">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="#writeln(java.lang.String)">writeln</a></span>​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> text)</code></th>
<td class="colLast">
<div class="block">Write a string of text followed by a newline character to a document
stream opened by <code>open()</code> .</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<ul class="blockList">
<li class="blockList"><a id="methods.inherited.from.class.org.w3c.dom.Document">
<!-- -->
</a>
<h3>Methods declared in interface org.w3c.dom.<a href="../../../../../java.xml/org/w3c/dom/Document.html" title="interface in org.w3c.dom">Document</a></h3>
<code><a href="../../../../../java.xml/org/w3c/dom/Document.html#adoptNode(org.w3c.dom.Node)">adoptNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createAttribute(java.lang.String)">createAttribute</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createAttributeNS(java.lang.String,java.lang.String)">createAttributeNS</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createCDATASection(java.lang.String)">createCDATASection</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createComment(java.lang.String)">createComment</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createDocumentFragment()">createDocumentFragment</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createElement(java.lang.String)">createElement</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createElementNS(java.lang.String,java.lang.String)">createElementNS</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createEntityReference(java.lang.String)">createEntityReference</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createProcessingInstruction(java.lang.String,java.lang.String)">createProcessingInstruction</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#createTextNode(java.lang.String)">createTextNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getDoctype()">getDoctype</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getDocumentElement()">getDocumentElement</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getDocumentURI()">getDocumentURI</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getDomConfig()">getDomConfig</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getElementById(java.lang.String)">getElementById</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getElementsByTagName(java.lang.String)">getElementsByTagName</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getElementsByTagNameNS(java.lang.String,java.lang.String)">getElementsByTagNameNS</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getImplementation()">getImplementation</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getInputEncoding()">getInputEncoding</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getStrictErrorChecking()">getStrictErrorChecking</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getXmlEncoding()">getXmlEncoding</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getXmlStandalone()">getXmlStandalone</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#getXmlVersion()">getXmlVersion</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#importNode(org.w3c.dom.Node,boolean)">importNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#normalizeDocument()">normalizeDocument</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#renameNode(org.w3c.dom.Node,java.lang.String,java.lang.String)">renameNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#setDocumentURI(java.lang.String)">setDocumentURI</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#setStrictErrorChecking(boolean)">setStrictErrorChecking</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#setXmlStandalone(boolean)">setXmlStandalone</a>, <a href="../../../../../java.xml/org/w3c/dom/Document.html#setXmlVersion(java.lang.String)">setXmlVersion</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a id="methods.inherited.from.class.org.w3c.dom.Node">
<!-- -->
</a>
<h3>Methods declared in interface org.w3c.dom.<a href="../../../../../java.xml/org/w3c/dom/Node.html" title="interface in org.w3c.dom">Node</a></h3>
<code><a href="../../../../../java.xml/org/w3c/dom/Node.html#appendChild(org.w3c.dom.Node)">appendChild</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#cloneNode(boolean)">cloneNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#compareDocumentPosition(org.w3c.dom.Node)">compareDocumentPosition</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getAttributes()">getAttributes</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getBaseURI()">getBaseURI</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getChildNodes()">getChildNodes</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getFeature(java.lang.String,java.lang.String)">getFeature</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getFirstChild()">getFirstChild</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getLastChild()">getLastChild</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getLocalName()">getLocalName</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getNamespaceURI()">getNamespaceURI</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getNextSibling()">getNextSibling</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getNodeName()">getNodeName</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getNodeType()">getNodeType</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getNodeValue()">getNodeValue</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getOwnerDocument()">getOwnerDocument</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getParentNode()">getParentNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getPrefix()">getPrefix</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getPreviousSibling()">getPreviousSibling</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getTextContent()">getTextContent</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#getUserData(java.lang.String)">getUserData</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#hasAttributes()">hasAttributes</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#hasChildNodes()">hasChildNodes</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#insertBefore(org.w3c.dom.Node,org.w3c.dom.Node)">insertBefore</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#isDefaultNamespace(java.lang.String)">isDefaultNamespace</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#isEqualNode(org.w3c.dom.Node)">isEqualNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#isSameNode(org.w3c.dom.Node)">isSameNode</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#isSupported(java.lang.String,java.lang.String)">isSupported</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#lookupNamespaceURI(java.lang.String)">lookupNamespaceURI</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#lookupPrefix(java.lang.String)">lookupPrefix</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#normalize()">normalize</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#removeChild(org.w3c.dom.Node)">removeChild</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#replaceChild(org.w3c.dom.Node,org.w3c.dom.Node)">replaceChild</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#setNodeValue(java.lang.String)">setNodeValue</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#setPrefix(java.lang.String)">setPrefix</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#setTextContent(java.lang.String)">setTextContent</a>, <a href="../../../../../java.xml/org/w3c/dom/Node.html#setUserData(java.lang.String,java.lang.Object,org.w3c.dom.UserDataHandler)">setUserData</a></code></li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a id="getTitle()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTitle</h4>
<pre class="methodSignature"><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> getTitle()</pre>
<div class="block">The title of a document as specified by the <code>TITLE</code> element
in the head of the document.</div>
</li>
</ul>
<a id="setTitle(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTitle</h4>
<pre class="methodSignature">void setTitle​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> title)</pre>
</li>
</ul>
<a id="getReferrer()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getReferrer</h4>
<pre class="methodSignature"><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> getReferrer()</pre>
<div class="block">Returns the URI of the page that linked to this page. The value is an
empty string if the user navigated to the page directly (not through a
link, but, for example, via a bookmark).</div>
</li>
</ul>
<a id="getDomain()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDomain</h4>
<pre class="methodSignature"><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> getDomain()</pre>
<div class="block">The domain name of the server that served the document, or
<code>null</code> if the server cannot be identified by a domain name.</div>
</li>
</ul>
<a id="getURL()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getURL</h4>
<pre class="methodSignature"><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> getURL()</pre>
<div class="block">The complete URI of the document.</div>
</li>
</ul>
<a id="getBody()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getBody</h4>
<pre class="methodSignature"><a href="HTMLElement.html" title="interface in org.w3c.dom.html">HTMLElement</a> getBody()</pre>
<div class="block">The element that contains the content for the document. In documents
with <code>BODY</code> contents, returns the <code>BODY</code>
element. In frameset documents, this returns the outermost
<code>FRAMESET</code> element.</div>
</li>
</ul>
<a id="setBody(org.w3c.dom.html.HTMLElement)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setBody</h4>
<pre class="methodSignature">void setBody​(<a href="HTMLElement.html" title="interface in org.w3c.dom.html">HTMLElement</a> body)</pre>
</li>
</ul>
<a id="getImages()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getImages</h4>
<pre class="methodSignature"><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a> getImages()</pre>
<div class="block">A collection of all the <code>IMG</code> elements in a document. The
behavior is limited to <code>IMG</code> elements for backwards
compatibility.</div>
</li>
</ul>
<a id="getApplets()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getApplets</h4>
<pre class="methodSignature"><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a> getApplets()</pre>
<div class="block">A collection of all the <code>OBJECT</code> elements that include
applets and <code>APPLET</code> ( deprecated ) elements in a document.</div>
</li>
</ul>
<a id="getLinks()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getLinks</h4>
<pre class="methodSignature"><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a> getLinks()</pre>
<div class="block">A collection of all <code>AREA</code> elements and anchor (
<code>A</code> ) elements in a document with a value for the
<code>href</code> attribute.</div>
</li>
</ul>
<a id="getForms()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getForms</h4>
<pre class="methodSignature"><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a> getForms()</pre>
<div class="block">A collection of all the forms of a document.</div>
</li>
</ul>
<a id="getAnchors()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getAnchors</h4>
<pre class="methodSignature"><a href="HTMLCollection.html" title="interface in org.w3c.dom.html">HTMLCollection</a> getAnchors()</pre>
<div class="block">A collection of all the anchor (<code>A</code> ) elements in a document
with a value for the <code>name</code> attribute. Note. For reasons
of backwards compatibility, the returned set of anchors only contains
those anchors created with the <code>name</code> attribute, not those
created with the <code>id</code> attribute.</div>
</li>
</ul>
<a id="getCookie()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCookie</h4>
<pre class="methodSignature"><a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> getCookie()</pre>
<div class="block">The cookies associated with this document. If there are none, the
value is an empty string. Otherwise, the value is a string: a
semicolon-delimited list of "name, value" pairs for all the cookies
associated with the page. For example,
<code>name=value;expires=date</code> .</div>
</li>
</ul>
<a id="setCookie(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setCookie</h4>
<pre class="methodSignature">void setCookie​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> cookie)</pre>
</li>
</ul>
<a id="open()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>open</h4>
<pre class="methodSignature">void open()</pre>
<div class="block">Note. This method and the ones following allow a user to add to or
replace the structure model of a document using strings of unparsed
HTML. At the time of writing alternate methods for providing similar
functionality for both HTML and XML documents were being considered.
The following methods may be deprecated at some point in the future in
favor of a more general-purpose mechanism.
<br> Open a document stream for writing. If a document exists in the
target, this method clears it.</div>
</li>
</ul>
<a id="close()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>close</h4>
<pre class="methodSignature">void close()</pre>
<div class="block">Closes a document stream opened by <code>open()</code> and forces
rendering.</div>
</li>
</ul>
<a id="write(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>write</h4>
<pre class="methodSignature">void write​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> text)</pre>
<div class="block">Write a string of text to a document stream opened by
<code>open()</code> . The text is parsed into the document's structure
model.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>text</code> - The string to be parsed into some structure in the
document structure model.</dd>
</dl>
</li>
</ul>
<a id="writeln(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>writeln</h4>
<pre class="methodSignature">void writeln​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> text)</pre>
<div class="block">Write a string of text followed by a newline character to a document
stream opened by <code>open()</code> . The text is parsed into the
document's structure model.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>text</code> - The string to be parsed into some structure in the
document structure model.</dd>
</dl>
</li>
</ul>
<a id="getElementsByName(java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getElementsByName</h4>
<pre class="methodSignature"><a href="../../../../../java.xml/org/w3c/dom/NodeList.html" title="interface in org.w3c.dom">NodeList</a> getElementsByName​(<a href="../../../../../java.base/java/lang/String.html" title="class in java.lang">String</a> elementName)</pre>
<div class="block">Returns the (possibly empty) collection of elements whose
<code>name</code> value is given by <code>elementName</code> .</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>elementName</code> - The <code>name</code> attribute value for an
element.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The matching elements.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
</div>
</main>
<!-- ========= END OF CLASS DATA ========= -->
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../index.html">Overview</a></li>
<li><a href="../../../../module-summary.html">Module</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/HTMLDocument.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 & JDK 12</strong> </div></div>
</div>
<div class="subNav">
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small><a href="https://bugreport.java.com/bugreport/">Report a bug or suggest an enhancement</a><br> For further API reference and developer documentation see the <a href="https://docs.oracle.com/pls/topic/lookup?ctx=javase12.0.2&id=homepage" target="_blank">Java SE Documentation</a>, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.<br> <a href="../../../../../../legal/copyright.html">Copyright</a> © 1993, 2019, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.<br>All rights reserved. Use is subject to <a href="https://www.oracle.com/technetwork/java/javase/terms/license/java12.0.2speclicense.html">license terms</a> and the <a href="https://www.oracle.com/technetwork/java/redist-137594.html">documentation redistribution policy</a>. <!-- Version 12.0.2+10 --></small></p>
</footer>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : {"default": mod};
};
Object.defineProperty(exports, "__esModule", {value: true});
var fork_1 = __importDefault(require("./fork"));
var core_1 = __importDefault(require("./def/core"));
var es6_1 = __importDefault(require("./def/es6"));
var es7_1 = __importDefault(require("./def/es7"));
var jsx_1 = __importDefault(require("./def/jsx"));
var flow_1 = __importDefault(require("./def/flow"));
var esprima_1 = __importDefault(require("./def/esprima"));
var babel_1 = __importDefault(require("./def/babel"));
var typescript_1 = __importDefault(require("./def/typescript"));
var es_proposals_1 = __importDefault(require("./def/es-proposals"));
var namedTypes_1 = require("./gen/namedTypes");
exports.namedTypes = namedTypes_1.namedTypes;
var _a = fork_1.default([
// This core module of AST types captures ES5 as it is parsed today by
// git://github.com/ariya/esprima.git#master.
core_1.default,
// Feel free to add to or remove from this list of extension modules to
// configure the precise type hierarchy that you need.
es6_1.default,
es7_1.default,
jsx_1.default,
flow_1.default,
esprima_1.default,
babel_1.default,
typescript_1.default,
es_proposals_1.default,
]), astNodesAreEquivalent = _a.astNodesAreEquivalent, builders = _a.builders,
builtInTypes = _a.builtInTypes, defineMethod = _a.defineMethod, eachField = _a.eachField,
finalize = _a.finalize, getBuilderName = _a.getBuilderName, getFieldNames = _a.getFieldNames,
getFieldValue = _a.getFieldValue, getSupertypeNames = _a.getSupertypeNames, n = _a.namedTypes,
NodePath = _a.NodePath, Path = _a.Path, PathVisitor = _a.PathVisitor, someField = _a.someField,
Type = _a.Type, use = _a.use, visit = _a.visit;
exports.astNodesAreEquivalent = astNodesAreEquivalent;
exports.builders = builders;
exports.builtInTypes = builtInTypes;
exports.defineMethod = defineMethod;
exports.eachField = eachField;
exports.finalize = finalize;
exports.getBuilderName = getBuilderName;
exports.getFieldNames = getFieldNames;
exports.getFieldValue = getFieldValue;
exports.getSupertypeNames = getSupertypeNames;
exports.NodePath = NodePath;
exports.Path = Path;
exports.PathVisitor = PathVisitor;
exports.someField = someField;
exports.Type = Type;
exports.use = use;
exports.visit = visit;
// Populate the exported fields of the namedTypes namespace, while still
// retaining its member types.
Object.assign(namedTypes_1.namedTypes, n);
|
{
"pile_set_name": "Github"
}
|
<?php
final class PhabricatorFileDropUploadController
extends PhabricatorFileController {
public function shouldAllowRestrictedParameter($parameter_name) {
// Prevent false positives from file content when it is submitted via
// drag-and-drop upload.
return true;
}
/**
* @phutil-external-symbol class PhabricatorStartup
*/
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
// NOTE: Throws if valid CSRF token is not present in the request.
$request->validateCSRF();
$name = $request->getStr('name');
$file_phid = $request->getStr('phid');
// If there's no explicit view policy, make it very restrictive by default.
// This is the correct policy for files dropped onto objects during
// creation, comment and edit flows.
$view_policy = $request->getStr('viewPolicy');
if (!$view_policy) {
$view_policy = $viewer->getPHID();
}
$is_chunks = $request->getBool('querychunks');
if ($is_chunks) {
$params = array(
'filePHID' => $file_phid,
);
$result = id(new ConduitCall('file.querychunks', $params))
->setUser($viewer)
->execute();
return id(new AphrontAjaxResponse())->setContent($result);
}
$is_allocate = $request->getBool('allocate');
if ($is_allocate) {
$params = array(
'name' => $name,
'contentLength' => $request->getInt('length'),
'viewPolicy' => $view_policy,
);
$result = id(new ConduitCall('file.allocate', $params))
->setUser($viewer)
->execute();
$file_phid = $result['filePHID'];
if ($file_phid) {
$file = $this->loadFile($file_phid);
$result += $file->getDragAndDropDictionary();
}
return id(new AphrontAjaxResponse())->setContent($result);
}
// Read the raw request data. We're either doing a chunk upload or a
// vanilla upload, so we need it.
$data = PhabricatorStartup::getRawInput();
$is_chunk_upload = $request->getBool('uploadchunk');
if ($is_chunk_upload) {
$params = array(
'filePHID' => $file_phid,
'byteStart' => $request->getInt('byteStart'),
'data' => $data,
);
$result = id(new ConduitCall('file.uploadchunk', $params))
->setUser($viewer)
->execute();
$file = $this->loadFile($file_phid);
if ($file->getIsPartial()) {
$result = array();
} else {
$result = array(
'complete' => true,
) + $file->getDragAndDropDictionary();
}
return id(new AphrontAjaxResponse())->setContent($result);
}
$file = PhabricatorFile::newFromXHRUpload(
$data,
array(
'name' => $request->getStr('name'),
'authorPHID' => $viewer->getPHID(),
'viewPolicy' => $view_policy,
'isExplicitUpload' => true,
));
$result = $file->getDragAndDropDictionary();
return id(new AphrontAjaxResponse())->setContent($result);
}
private function loadFile($file_phid) {
$viewer = $this->getViewer();
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$file) {
throw new Exception(pht('Failed to load file.'));
}
return $file;
}
}
|
{
"pile_set_name": "Github"
}
|
package org.incode.platform.dom.document.integtests.demo.dom.order;
import java.math.BigDecimal;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.VersionStrategy;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.google.common.collect.Ordering;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.DomainObjectLayout;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.Title;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@javax.jdo.annotations.PersistenceCapable(
identityType=IdentityType.DATASTORE,
schema = "exampleDemoDocument"
)
@javax.jdo.annotations.DatastoreIdentity(
strategy=javax.jdo.annotations.IdGeneratorStrategy.IDENTITY,
column="id")
@javax.jdo.annotations.Version(
strategy=VersionStrategy.VERSION_NUMBER,
column="version")
@DomainObject()
@DomainObjectLayout(
bookmarking = BookmarkPolicy.AS_CHILD
)
@AllArgsConstructor
@Builder
@XmlJavaTypeAdapter(PersistentEntityAdapter.class)
public class DemoOrderLine implements Comparable<DemoOrderLine> {
@javax.jdo.annotations.Column(allowsNull="false")
@Property(hidden = Where.REFERENCES_PARENT)
@MemberOrder(sequence = "1")
@Getter @Setter
private DemoOrder order;
@javax.jdo.annotations.Column(allowsNull="false")
@Title(sequence="1")
@MemberOrder(sequence="2")
@Getter @Setter
private String description;
@Getter @Setter
@MemberOrder(sequence = "3")
private int quantity;
@javax.jdo.annotations.Column(allowsNull="true", scale=2)
@javax.validation.constraints.Digits(integer=10, fraction=2)
@MemberOrder(sequence = "4")
@Getter @Setter
private BigDecimal cost;
@Override
public int compareTo(DemoOrderLine other) {
return Ordering.natural().onResultOf(DemoOrderLine::getDescription).compare(this, other);
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Locale data for 'bem'.
*
* This file is automatically generated by yiic cldr command.
*
* Copyright © 1991-2013 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
*
* @copyright 2008-2014 Yii Software LLC (http://www.yiiframework.com/license/)
*/
return array (
'version' => '8245',
'numberSymbols' =>
array (
'decimal' => '.',
'group' => ',',
'list' => ';',
'percentSign' => '%',
'plusSign' => '+',
'minusSign' => '-',
'exponential' => 'E',
'perMille' => '‰',
'infinity' => '∞',
'nan' => 'NaN',
),
'decimalFormat' => '#,##0.###',
'scientificFormat' => '#E0',
'percentFormat' => '#,##0%',
'currencyFormat' => '¤#,##0.00;(¤#,##0.00)',
'currencySymbols' =>
array (
'AUD' => 'A$',
'BRL' => 'R$',
'CAD' => 'CA$',
'CNY' => 'CN¥',
'EUR' => '€',
'GBP' => '£',
'HKD' => 'HK$',
'ILS' => '₪',
'INR' => '₹',
'JPY' => 'JP¥',
'KRW' => '₩',
'MXN' => 'MX$',
'NZD' => 'NZ$',
'THB' => '฿',
'TWD' => 'NT$',
'USD' => 'US$',
'VND' => '₫',
'XAF' => 'FCFA',
'XCD' => 'EC$',
'XOF' => 'CFA',
'XPF' => 'CFPF',
'ZMK' => 'K',
'ZMW' => 'KR',
),
'monthNames' =>
array (
'wide' =>
array (
1 => 'Januari',
2 => 'Februari',
3 => 'Machi',
4 => 'Epreo',
5 => 'Mei',
6 => 'Juni',
7 => 'Julai',
8 => 'Ogasti',
9 => 'Septemba',
10 => 'Oktoba',
11 => 'Novemba',
12 => 'Disemba',
),
'abbreviated' =>
array (
1 => 'Jan',
2 => 'Feb',
3 => 'Mac',
4 => 'Epr',
5 => 'Mei',
6 => 'Jun',
7 => 'Jul',
8 => 'Oga',
9 => 'Sep',
10 => 'Okt',
11 => 'Nov',
12 => 'Dis',
),
),
'monthNamesSA' =>
array (
'narrow' =>
array (
1 => 'J',
2 => 'F',
3 => 'M',
4 => 'E',
5 => 'M',
6 => 'J',
7 => 'J',
8 => 'O',
9 => 'S',
10 => 'O',
11 => 'N',
12 => 'D',
),
),
'weekDayNames' =>
array (
'wide' =>
array (
0 => 'Pa Mulungu',
1 => 'Palichimo',
2 => 'Palichibuli',
3 => 'Palichitatu',
4 => 'Palichine',
5 => 'Palichisano',
6 => 'Pachibelushi',
),
'abbreviated' =>
array (
0 => 'Sun',
1 => 'Mon',
2 => 'Tue',
3 => 'Wed',
4 => 'Thu',
5 => 'Fri',
6 => 'Sat',
),
),
'weekDayNamesSA' =>
array (
'narrow' =>
array (
0 => 'S',
1 => 'M',
2 => 'T',
3 => 'W',
4 => 'T',
5 => 'F',
6 => 'S',
),
),
'eraNames' =>
array (
'abbreviated' =>
array (
0 => 'BC',
1 => 'AD',
),
'wide' =>
array (
0 => 'Before Yesu',
1 => 'After Yesu',
),
'narrow' =>
array (
0 => 'BC',
1 => 'AD',
),
),
'dateFormats' =>
array (
'full' => 'EEEE, d MMMM y',
'long' => 'd MMMM y',
'medium' => 'd MMM y',
'short' => 'dd/MM/y',
),
'timeFormats' =>
array (
'full' => 'h:mm:ss a zzzz',
'long' => 'h:mm:ss a z',
'medium' => 'h:mm:ss a',
'short' => 'h:mm a',
),
'dateTimeFormat' => '{1} {0}',
'amName' => 'uluchelo',
'pmName' => 'akasuba',
'orientation' => 'ltr',
'languages' =>
array (
'ak' => 'Ichi Akan',
'am' => 'Ichi Amhari',
'ar' => 'Ichi Arab',
'be' => 'Ichi Belarus',
'bem' => 'Ichibemba',
'bg' => 'Ichi Bulgariani',
'bn' => 'Ichi Bengali',
'cs' => 'Ichi Cheki',
'de' => 'Ichi Jemani',
'el' => 'Ichi Griki',
'en' => 'Ichi Sungu',
'es' => 'Ichi Spanishi',
'fa' => 'Ichi Pesia',
'fr' => 'Ichi Frenchi',
'ha' => 'Ichi Hausa',
'hi' => 'Ichi Hindu',
'hu' => 'Ichi Hangarian',
'id' => 'Ichi Indonesiani',
'ig' => 'Ichi Ibo',
'it' => 'Ichi Italiani',
'ja' => 'Ichi Japanisi',
'jv' => 'Ichi Javanisi',
'km' => 'Ichi Khmer',
'ko' => 'Ichi Koriani',
'ms' => 'Ichi Maleshani',
'my' => 'Ichi Burma',
'ne' => 'Ichi Nepali',
'nl' => 'Ichi Dachi',
'pa' => 'Ichi Punjabi',
'pl' => 'Ichi Polishi',
'pt' => 'Ichi Potogisi',
'ro' => 'Ichi Romaniani',
'ru' => 'Ichi Rusiani',
'rw' => 'Ichi Rwanda',
'so' => 'Ichi Somalia',
'sv' => 'Ichi Swideni',
'ta' => 'Ichi Tamil',
'th' => 'Ichi Thai',
'tr' => 'Ichi Takishi',
'uk' => 'Ichi Ukraniani',
'ur' => 'Ichi Urudu',
'vi' => 'Ichi Vietinamu',
'yo' => 'Ichi Yoruba',
'zh' => 'Ichi Chainisi',
'zu' => 'Ichi Zulu',
),
'territories' =>
array (
'zm' => 'Zambia',
),
'pluralRules' =>
array (
0 => 'n==1',
1 => 'true',
),
);
|
{
"pile_set_name": "Github"
}
|
import argparse
import glob
import json
import os
import shutil
import subprocess
import uuid
from collections import OrderedDict
from joblib import delayed
from joblib import Parallel
import pandas as pd
def create_video_folders(dataset, output_dir, tmp_dir):
"""Creates a directory for each label name in the dataset."""
if 'label-name' not in dataset.columns:
this_dir = os.path.join(output_dir, 'test')
if not os.path.exists(this_dir):
os.makedirs(this_dir)
# I should return a dict but ...
return this_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
label_to_dir = {}
for label_name in dataset['label-name'].unique():
this_dir = os.path.join(output_dir, label_name)
if not os.path.exists(this_dir):
os.makedirs(this_dir)
label_to_dir[label_name] = this_dir
return label_to_dir
def construct_video_filename(row, label_to_dir, trim_format='%06d'):
"""Given a dataset row, this function constructs the
output filename for a given video.
"""
basename = '%s_%s_%s.mp4' % (row['video-id'],
trim_format % row['start-time'],
trim_format % row['end-time'])
if not isinstance(label_to_dir, dict):
dirname = label_to_dir
else:
dirname = label_to_dir[row['label-name']]
output_filename = os.path.join(dirname, basename)
return output_filename
def download_clip(video_identifier, output_filename,
start_time, end_time,
tmp_dir='/tmp/kinetics',
num_attempts=5,
url_base='https://www.youtube.com/watch?v='):
"""Download a video from youtube if exists and is not blocked.
arguments:
---------
video_identifier: str
Unique YouTube video identifier (11 characters)
output_filename: str
File path where the video will be stored.
start_time: float
Indicates the begining time in seconds from where the video
will be trimmed.
end_time: float
Indicates the ending time in seconds of the trimmed video.
"""
# Defensive argument checking.
assert isinstance(video_identifier, str), 'video_identifier must be string'
assert isinstance(output_filename, str), 'output_filename must be string'
assert len(video_identifier) == 11, 'video_identifier must have length 11'
status = False
# Construct command line for getting the direct video link.
tmp_filename = os.path.join(tmp_dir,
'%s.%%(ext)s' % uuid.uuid4())
command = ['youtube-dl',
'--quiet', '--no-warnings',
'-f', 'mp4',
'-o', '"%s"' % tmp_filename,
'"%s"' % (url_base + video_identifier)]
command = ' '.join(command)
attempts = 0
while True:
try:
output = subprocess.check_output(command, shell=True,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
attempts += 1
if attempts == num_attempts:
return status, err.output
else:
break
tmp_filename = glob.glob('%s*' % tmp_filename.split('.')[0])[0]
# Construct command to trim the videos (ffmpeg required).
command = ['ffmpeg',
'-i', '"%s"' % tmp_filename,
'-ss', str(start_time),
'-t', str(end_time - start_time),
'-c:v', 'libx264', '-c:a', 'copy',
'-threads', '1',
'-loglevel', 'panic',
'"%s"' % output_filename]
command = ' '.join(command)
try:
output = subprocess.check_output(command, shell=True,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
return status, err.output
# Check if the video was successfully saved.
status = os.path.exists(output_filename)
os.remove(tmp_filename)
return status, 'Downloaded'
def download_clip_wrapper(row, label_to_dir, trim_format, tmp_dir):
"""Wrapper for parallel processing purposes."""
output_filename = construct_video_filename(row, label_to_dir,
trim_format)
clip_id = os.path.basename(output_filename).split('.mp4')[0]
if os.path.exists(output_filename):
status = tuple([clip_id, True, 'Exists'])
return status
downloaded, log = download_clip(row['video-id'], output_filename,
row['start-time'], row['end-time'],
tmp_dir=tmp_dir)
status = tuple([clip_id, downloaded, log])
return status
def parse_kinetics_annotations(input_csv, ignore_is_cc=False):
"""Returns a parsed DataFrame.
arguments:
---------
input_csv: str
Path to CSV file containing the following columns:
'YouTube Identifier,Start time,End time,Class label'
returns:
-------
dataset: DataFrame
Pandas with the following columns:
'video-id', 'start-time', 'end-time', 'label-name'
"""
df = pd.read_csv(input_csv)
if 'youtube_id' in df.columns:
columns = OrderedDict([
('youtube_id', 'video-id'),
('time_start', 'start-time'),
('time_end', 'end-time'),
('label', 'label-name')])
df.rename(columns=columns, inplace=True)
if ignore_is_cc:
df = df.loc[:, df.columns.tolist()[:-1]]
return df
def main(input_csv, output_dir,
trim_format='%06d', num_jobs=24, tmp_dir='/tmp/kinetics',
drop_duplicates=False):
# Reading and parsing Kinetics.
dataset = parse_kinetics_annotations(input_csv)
# if os.path.isfile(drop_duplicates):
# print('Attempt to remove duplicates')
# old_dataset = parse_kinetics_annotations(drop_duplicates,
# ignore_is_cc=True)
# df = pd.concat([dataset, old_dataset], axis=0, ignore_index=True)
# df.drop_duplicates(inplace=True, keep=False)
# print(dataset.shape, old_dataset.shape)
# dataset = df
# print(dataset.shape)
# Creates folders where videos will be saved later.
label_to_dir = create_video_folders(dataset, output_dir, tmp_dir)
# Download all clips.
if num_jobs == 1:
status_lst = []
for i, row in dataset.iterrows():
status_lst.append(download_clip_wrapper(row, label_to_dir,
trim_format, tmp_dir))
else:
status_lst = Parallel(n_jobs=num_jobs)(delayed(download_clip_wrapper)(
row, label_to_dir,
trim_format, tmp_dir) for i, row in dataset.iterrows())
# Clean tmp dir.
shutil.rmtree(tmp_dir)
# Save download report.
with open('download_report.json', 'w') as fobj:
fobj.write(json.dumps(status_lst))
if __name__ == '__main__':
description = 'Helper script for downloading and trimming kinetics videos.'
p = argparse.ArgumentParser(description=description)
p.add_argument('input_csv', type=str,
help=('CSV file containing the following format: '
'YouTube Identifier,Start time,End time,Class label'))
p.add_argument('output_dir', type=str,
help='Output directory where videos will be saved.')
p.add_argument('-f', '--trim-format', type=str, default='%06d',
help=('This will be the format for the '
'filename of trimmed videos: '
'videoid_%0xd(start_time)_%0xd(end_time).mp4'))
p.add_argument('-n', '--num-jobs', type=int, default=24)
p.add_argument('-t', '--tmp-dir', type=str, default='/tmp/kinetics')
p.add_argument('--drop-duplicates', type=str, default='non-existent',
help='Unavailable at the moment')
# help='CSV file of the previous version of Kinetics.')
main(**vars(p.parse_args()))
|
{
"pile_set_name": "Github"
}
|
using AuthorizeNet.Utility;
namespace AuthorizeNet.Api.Controllers.Test
{
using System;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Controllers.Bases;
using AuthorizeNet.Api.Controllers.Test;
using AuthorizeNet.Util;
using NUnit.Framework;
using System.Linq;
[TestFixture]
public class ArbSubscriptionTest : ApiCoreTestBase {
[TestFixtureSetUp]
public new static void SetUpBeforeClass()
{
ApiCoreTestBase.SetUpBeforeClass();
}
[TestFixtureTearDown]
public new static void TearDownAfterClass()
{
ApiCoreTestBase.TearDownAfterClass();
}
[SetUp]
public new void SetUp() {
base.SetUp();
}
[TearDown]
public new void TearDown() {
base.TearDown();
}
[Test]
public void TestGetSubscriptionList()
{
//create a transaction
var transactionRequestType = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
amount = SetValidTransactionAmount(Counter),
payment = PaymentOne,
order = OrderType,
customer = CustomerDataOne,
billTo = CustomerAddressOne,
};
var createRequest = new createTransactionRequest
{
refId = RefId,
transactionRequest = transactionRequestType,
merchantAuthentication = CustomMerchantAuthenticationType,
};
var createResponse = ExecuteTestRequestWithSuccess<createTransactionRequest, createTransactionResponse, createTransactionController >(createRequest, TestEnvironment);
var referenceTxnId = createResponse.transactionResponse.transId;
var subscriptionId = CreateSubscription( CustomMerchantAuthenticationType, referenceTxnId);
var newStatus = GetSubscription( CustomMerchantAuthenticationType, subscriptionId);
Assert.AreEqual(ARBSubscriptionStatusEnum.active, newStatus);
LogHelper.info(Logger, "Getting Subscription List for SubscriptionId: {0}", subscriptionId);
int subsId;
var found = false;
Int32.TryParse(subscriptionId, out subsId);
//setup retry loop to allow for delays in replication
for (int counter = 0; counter < 5; counter++)
{
var listRequest = SetupSubscriptionListRequest(CustomMerchantAuthenticationType);
var listResponse = ExecuteTestRequestWithSuccess<ARBGetSubscriptionListRequest, ARBGetSubscriptionListResponse, ARBGetSubscriptionListController>(listRequest, TestEnvironment);
if (listResponse.subscriptionDetails.Any<SubscriptionDetail>(a => a.id == subsId))
{
found = true;
break;
}
else
{
System.Threading.Thread.Sleep(10000);
}
}
Assert.IsTrue(found);
CancelSubscription(CustomMerchantAuthenticationType, subscriptionId);
//validate the status of subscription to make sure it is canceled
var cancelStatus = GetSubscription(CustomMerchantAuthenticationType, subscriptionId);
Assert.AreEqual(ARBSubscriptionStatusEnum.canceled, cancelStatus);
}
[Test]
public void TestSubscription() {
var rnd = new AnetRandom(DateTime.Now.Millisecond);
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;
//create a subscription
var subscriptionDef = new ARBSubscriptionType
{
paymentSchedule = new paymentScheduleType
{
interval = new paymentScheduleTypeInterval
{
length = 1,
unit = ARBSubscriptionUnitEnum.months,
},
startDate = DateTime.UtcNow,
totalOccurrences = 12,
},
amount = 9.99M,
billTo = new nameAndAddressType{ firstName = "first", lastName = "last", address="123 elm st ne", city = "Bellevue", state = "Wa", zip = "98007"},
payment = PaymentOne,
customer = CustomerOne,
order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) },
};
var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionDef };
var arbController = new ARBCreateSubscriptionController(arbRequest);
arbController.Execute();
var arbCreateResponse = arbController.GetApiResponse();
Assert.AreEqual(messageTypeEnum.Ok,arbController.GetResultCode());
}
[Test]
public void TestSubscription_ExpiredCC()
{
var rnd = new AnetRandom(DateTime.Now.Millisecond);
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;
//create a subscription
var subscriptionDef = new ARBSubscriptionType
{
paymentSchedule = new paymentScheduleType
{
interval = new paymentScheduleTypeInterval
{
length = 7,
unit = ARBSubscriptionUnitEnum.days
},
startDate = DateTime.UtcNow,
totalOccurrences = 2,
},
amount = 9.99M,
billTo = new nameAndAddressType
{
address = "1234 Elm St NE",
city = "Bellevue",
state = "WA",
zip = "98007",
firstName = "First",
lastName = "Last"
},
payment = new paymentType
{
Item = new creditCardType
{
cardCode = "655",
//cardNumber = "4007000",
cardNumber = "4111111111111111",
expirationDate = "122013",
}
},
customer = new customerType { email = "somecustomer@test.org", id = "5", },
order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) },
};
var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionDef };
var arbController = new ARBCreateSubscriptionController(arbRequest);
arbController.Execute();
var arbCreateResponse = arbController.GetApiResponse();
//If request responds with an error, walk the messages and get code and text for each message.
if (arbController.GetResultCode() == messageTypeEnum.Error)
{
foreach(var msg in arbCreateResponse.messages.message)
{
Console.WriteLine("Error Num = {0}, Message = {1}", msg.code, msg.text);
}
}
}
/// <summary>
/// Repro issue ARBSubscriptionList SearchType of "cardExpiringThisMonth" doesn't work
/// commenting the test attribute because issue is fixed.
/// @Zalak
/// </summary>
// [Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "SearchType cannot be null")]
public void GetSubscriptionSearchCardExpiringThisMonthIssueTest()
{
var getSubscriptionList = new ARBGetSubscriptionListRequest()
{
searchType = ARBGetSubscriptionListSearchTypeEnum.cardExpiringThisMonth,
};
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;
var nullController = new ARBGetSubscriptionListController(getSubscriptionList);
Assert.IsNull( nullController, "Controller should not be instantiated.");
}
/// <summary>
/// Fix the issue ARBSubscriptionList SearchType of "cardExpiringThisMonth" doesn't work
/// @Zalak
/// </summary>
[Test]
public void GetSubscriptionSearchCardExpiringThisMonthFixTest()
{
var rnd = new AnetRandom(DateTime.Now.Millisecond);
var createSubscription = new ARBSubscriptionType()
{
paymentSchedule = new paymentScheduleType
{
interval = new paymentScheduleTypeInterval
{
length = 8,
unit = ARBSubscriptionUnitEnum.months
},
startDate = DateTime.UtcNow,
totalOccurrences = 3,
},
amount = 19.29M,
billTo = new nameAndAddressType
{
address = "1234 Elm St NE",
city = "Bellevue",
state = "WA",
zip = "98007",
firstName = "First",
lastName = "Last"
},
payment = new paymentType
{
Item = new creditCardType
{
cardCode = "123",
cardNumber = "5105105105105100",
// cardNumber = "4111111111111111",
expirationDate = "102015",
}
},
customer = new customerType { email = "somecustomer@test.org", id = "5", },
order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) },
};
var arbCreateSubscriptionController = CreateSubscriptionRequestTest(createSubscription);
var arbCreateSubscriptionResponse = arbCreateSubscriptionController.ExecuteWithApiResponse();
if (null == arbCreateSubscriptionResponse)
{
throw new ArgumentNullException("arbCreateSubscriptionResponse");
}
var getSubscriptionList = new ARBGetSubscriptionListRequest()
{
searchType = ARBGetSubscriptionListSearchTypeEnum.cardExpiringThisMonth,
};
var arbGetSubscriptionListController = new ARBGetSubscriptionListController(getSubscriptionList);
var arbGetSubscriptionListResponse = arbGetSubscriptionListController.ExecuteWithApiResponse();
Assert.IsNotNull(arbGetSubscriptionListResponse);
}
private ARBGetSubscriptionListResponse GetSubscriptionListResponse(int limitNo, int offSetNo)
{
var getSubscriptionList = new ARBGetSubscriptionListRequest()
{
searchType = ARBGetSubscriptionListSearchTypeEnum.subscriptionActive,
paging = new Paging()
{
limit = limitNo,
offset = offSetNo
},
};
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;
var arbGetSubscriptionListController = new ARBGetSubscriptionListController(getSubscriptionList);
var arbGetSubscriptionListResponse = arbGetSubscriptionListController.ExecuteWithApiResponse();
return arbGetSubscriptionListResponse;
}
/// <summary>
/// @Zalak
/// Test case for Pagination issue reported in Jira:
/// C# - ARBSubscriptionList SearchType of "cardExpiringThisMonth" doesn't work
/// </summary>
[Test]
public void ARBGetSubscriptionListCheckPagination()
{
var arbGetSubscriptionListResponse = GetSubscriptionListResponse(1, 1);
ARBGetSubscriptionListResponse response = null;
int limitNo = 3;
int offSetNo = 2;
if (arbGetSubscriptionListResponse != null)
{
int subcriptionNumber = arbGetSubscriptionListResponse.totalNumInResultSet;
int expectedSubscriptionNo = 0;
int nPages = subcriptionNumber/limitNo;
int subscriptionDetailsOnLastPage = subcriptionNumber%limitNo;
if (offSetNo <= nPages)
expectedSubscriptionNo = limitNo;
else if (offSetNo > (nPages + 1))
expectedSubscriptionNo = 0;
else
{
expectedSubscriptionNo = subscriptionDetailsOnLastPage;
}
response = GetSubscriptionListResponse(limitNo, offSetNo);
Assert.AreEqual(expectedSubscriptionNo, response.subscriptionDetails.Count());
}
else
{
Assert.Null(arbGetSubscriptionListResponse);
}
}
private ARBCreateSubscriptionController CreateSubscriptionRequestTest(ARBSubscriptionType subscriptionRequestParameter)
{
if (subscriptionRequestParameter == null)
{
throw new ArgumentNullException("subscriptionRequestParameter");
}
LogHelper.info(Logger, "CreateSubscriptionRequestTest");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;
var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionRequestParameter };
var arbController = new ARBCreateSubscriptionController(arbRequest);
return arbController;
}
private ARBGetSubscriptionListRequest SetupSubscriptionListRequest(merchantAuthenticationType merchantAuthentication) {
var sorting = new ARBGetSubscriptionListSorting
{
orderDescending = true,
orderBy = ARBGetSubscriptionListOrderFieldEnum.createTimeStampUTC,
};
var paging = new Paging
{
limit = 500,
offset = 1,
};
var listRequest = new ARBGetSubscriptionListRequest
{
merchantAuthentication = merchantAuthentication,
refId = RefId,
searchType = ARBGetSubscriptionListSearchTypeEnum.subscriptionActive,
sorting = sorting,
paging = paging,
};
return listRequest;
}
private void CancelSubscription(merchantAuthenticationType merchantAuthentication, String subscriptionId) {
//cancel the subscription
var cancelRequest = new ARBCancelSubscriptionRequest
{
merchantAuthentication = merchantAuthentication,
refId = RefId,
subscriptionId = subscriptionId
};
var cancelResponse = ExecuteTestRequestWithSuccess<ARBCancelSubscriptionRequest, ARBCancelSubscriptionResponse, ARBCancelSubscriptionController>(cancelRequest, TestEnvironment);
Assert.IsNotNull(cancelResponse.messages);
Logger.info(String.Format("Subscription Cancelled: {0}", subscriptionId));
}
private ARBSubscriptionStatusEnum GetSubscription(merchantAuthenticationType merchantAuthentication, String subscriptionId) {
//get a subscription
var getRequest = new ARBGetSubscriptionStatusRequest
{
merchantAuthentication = merchantAuthentication,
refId = RefId,
subscriptionId = subscriptionId
};
var getResponse = ExecuteTestRequestWithSuccess<ARBGetSubscriptionStatusRequest, ARBGetSubscriptionStatusResponse, ARBGetSubscriptionStatusController>(getRequest, TestEnvironment);
Assert.IsNotNull(getResponse.status);
Logger.info(String.Format("Subscription Status: {0}", getResponse.status));
return getResponse.status;
}
private string CreateSubscription( merchantAuthenticationType merchantAuthentication, string RefId)
{
//create a new subscription
//RequestFactoryWithSpecified.paymentType(ArbSubscriptionOne.payment);
//RequestFactoryWithSpecified.paymentScheduleType(ArbSubscriptionOne.paymentSchedule);
//RequestFactoryWithSpecified.ARBSubscriptionType(ArbSubscriptionOne);
var createRequest = new ARBCreateSubscriptionRequest
{
merchantAuthentication = merchantAuthentication,
refId = RefId,
subscription = ArbSubscriptionOne,
};
var createResponse = ExecuteTestRequestWithSuccess<ARBCreateSubscriptionRequest, ARBCreateSubscriptionResponse, ARBCreateSubscriptionController>(createRequest, TestEnvironment);
Assert.IsNotNull(createResponse.subscriptionId);
LogHelper.info( Logger, "Created Subscription: {0}", createResponse.subscriptionId);
return createResponse.subscriptionId;
}
[Test]
public void TestSubscription_serialization_error()
{
var rnd = new AnetRandom(DateTime.Now.Millisecond);
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;
//create a subscription
var subscriptionDef = new ARBSubscriptionType
{
paymentSchedule = new paymentScheduleType
{
interval = new paymentScheduleTypeInterval
{
length = 1,
unit = ARBSubscriptionUnitEnum.months,
},
startDate = DateTime.UtcNow,
totalOccurrences = 12,
},
amount = 9.99M,
billTo = new customerAddressType { firstName = "first", lastName = "last" },
payment = PaymentOne,
customer = CustomerOne,
order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) },
};
var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionDef };
var arbController = new ARBCreateSubscriptionController(arbRequest);
arbController.Execute();
if (arbController.GetResultCode() == messageTypeEnum.Error)
{
var errorResp = arbController.GetErrorResponse();
Console.WriteLine("{0}: {1}", errorResp.messages.message[0].code, errorResp.messages.message[0].text);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/chromeos/login/user_flow.h"
#include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
#include "components/signin/core/account_id/account_id.h"
namespace chromeos {
UserFlow::UserFlow() : host_(NULL) {}
UserFlow::~UserFlow() {}
void UserFlow::SetHost(LoginDisplayHost* host) {
VLOG(1) << "Flow " << this << " got host " << host;
host_ = host;
}
DefaultUserFlow::~DefaultUserFlow() {}
void DefaultUserFlow::AppendAdditionalCommandLineSwitches() {
}
bool DefaultUserFlow::CanLockScreen() {
return true;
}
bool DefaultUserFlow::ShouldShowSettings() {
return true;
}
bool DefaultUserFlow::ShouldLaunchBrowser() {
return true;
}
bool DefaultUserFlow::ShouldSkipPostLoginScreens() {
return false;
}
bool DefaultUserFlow::SupportsEarlyRestartToApplyFlags() {
return true;
}
bool DefaultUserFlow::HandleLoginFailure(const AuthFailure& failure) {
return false;
}
void DefaultUserFlow::HandleLoginSuccess(const UserContext& context) {}
bool DefaultUserFlow::HandlePasswordChangeDetected() {
return false;
}
void DefaultUserFlow::HandleOAuthTokenStatusChange(
user_manager::User::OAuthTokenStatus status) {
}
void DefaultUserFlow::LaunchExtraSteps(Profile* profile) {
}
ExtendedUserFlow::ExtendedUserFlow(const AccountId& account_id)
: account_id_(account_id) {}
ExtendedUserFlow::~ExtendedUserFlow() {
}
void ExtendedUserFlow::AppendAdditionalCommandLineSwitches() {
}
bool ExtendedUserFlow::ShouldShowSettings() {
return true;
}
void ExtendedUserFlow::HandleOAuthTokenStatusChange(
user_manager::User::OAuthTokenStatus status) {
}
void ExtendedUserFlow::UnregisterFlowSoon() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&ChromeUserManager::ResetUserFlow,
base::Unretained(ChromeUserManager::Get()), account_id()));
}
} // namespace chromeos
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RCTView.h"
#import "RCTAutoInsetsProtocol.h"
#import "RCTBorderDrawing.h"
#import "RCTConvert.h"
#import "RCTI18nUtil.h"
#import "RCTLog.h"
#import "RCTUtils.h"
#import "UIView+React.h"
UIAccessibilityTraits const SwitchAccessibilityTrait = 0x20000000000001;
@implementation UIView (RCTViewUnmounting)
- (void)react_remountAllSubviews
{
// Normal views don't support unmounting, so all
// this does is forward message to our subviews,
// in case any of those do support it
for (UIView *subview in self.subviews) {
[subview react_remountAllSubviews];
}
}
- (void)react_updateClippedSubviewsWithClipRect:(CGRect)clipRect relativeToView:(UIView *)clipView
{
// Even though we don't support subview unmounting
// we do support clipsToBounds, so if that's enabled
// we'll update the clipping
if (self.clipsToBounds && self.subviews.count > 0) {
clipRect = [clipView convertRect:clipRect toView:self];
clipRect = CGRectIntersection(clipRect, self.bounds);
clipView = self;
}
// Normal views don't support unmounting, so all
// this does is forward message to our subviews,
// in case any of those do support it
for (UIView *subview in self.subviews) {
[subview react_updateClippedSubviewsWithClipRect:clipRect relativeToView:clipView];
}
}
- (UIView *)react_findClipView
{
UIView *testView = self;
UIView *clipView = nil;
CGRect clipRect = self.bounds;
// We will only look for a clipping view up the view hierarchy until we hit the root view.
while (testView) {
if (testView.clipsToBounds) {
if (clipView) {
CGRect testRect = [clipView convertRect:clipRect toView:testView];
if (!CGRectContainsRect(testView.bounds, testRect)) {
clipView = testView;
clipRect = CGRectIntersection(testView.bounds, testRect);
}
} else {
clipView = testView;
clipRect = [self convertRect:self.bounds toView:clipView];
}
}
if ([testView isReactRootView]) {
break;
}
testView = testView.superview;
}
return clipView ?: self.window;
}
@end
static NSString *RCTRecursiveAccessibilityLabel(UIView *view)
{
NSMutableString *str = [NSMutableString stringWithString:@""];
for (UIView *subview in view.subviews) {
NSString *label = subview.accessibilityLabel;
if (!label) {
label = RCTRecursiveAccessibilityLabel(subview);
}
if (label && label.length > 0) {
if (str.length > 0) {
[str appendString:@" "];
}
[str appendString:label];
}
}
return str.length == 0 ? nil : str;
}
@implementation RCTView {
UIColor *_backgroundColor;
NSMutableDictionary<NSString *, NSDictionary *> *accessibilityActionsNameMap;
NSMutableDictionary<NSString *, NSDictionary *> *accessibilityActionsLabelMap;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
_borderWidth = -1;
_borderTopWidth = -1;
_borderRightWidth = -1;
_borderBottomWidth = -1;
_borderLeftWidth = -1;
_borderStartWidth = -1;
_borderEndWidth = -1;
_borderTopLeftRadius = -1;
_borderTopRightRadius = -1;
_borderTopStartRadius = -1;
_borderTopEndRadius = -1;
_borderBottomLeftRadius = -1;
_borderBottomRightRadius = -1;
_borderBottomStartRadius = -1;
_borderBottomEndRadius = -1;
_borderStyle = RCTBorderStyleSolid;
_hitTestEdgeInsets = UIEdgeInsetsZero;
_backgroundColor = super.backgroundColor;
}
return self;
}
RCT_NOT_IMPLEMENTED(-(instancetype)initWithCoder : unused)
- (void)setReactLayoutDirection:(UIUserInterfaceLayoutDirection)layoutDirection
{
if (_reactLayoutDirection != layoutDirection) {
_reactLayoutDirection = layoutDirection;
[self.layer setNeedsDisplay];
}
if ([self respondsToSelector:@selector(setSemanticContentAttribute:)]) {
self.semanticContentAttribute = layoutDirection == UIUserInterfaceLayoutDirectionLeftToRight
? UISemanticContentAttributeForceLeftToRight
: UISemanticContentAttributeForceRightToLeft;
}
}
#pragma mark - Hit Testing
- (void)setPointerEvents:(RCTPointerEvents)pointerEvents
{
_pointerEvents = pointerEvents;
self.userInteractionEnabled = (pointerEvents != RCTPointerEventsNone);
if (pointerEvents == RCTPointerEventsBoxNone) {
self.accessibilityViewIsModal = NO;
}
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
BOOL canReceiveTouchEvents = ([self isUserInteractionEnabled] && ![self isHidden]);
if (!canReceiveTouchEvents) {
return nil;
}
// `hitSubview` is the topmost subview which was hit. The hit point can
// be outside the bounds of `view` (e.g., if -clipsToBounds is NO).
UIView *hitSubview = nil;
BOOL isPointInside = [self pointInside:point withEvent:event];
BOOL needsHitSubview = !(_pointerEvents == RCTPointerEventsNone || _pointerEvents == RCTPointerEventsBoxOnly);
if (needsHitSubview && (![self clipsToBounds] || isPointInside)) {
// Take z-index into account when calculating the touch target.
NSArray<UIView *> *sortedSubviews = [self reactZIndexSortedSubviews];
// The default behaviour of UIKit is that if a view does not contain a point,
// then no subviews will be returned from hit testing, even if they contain
// the hit point. By doing hit testing directly on the subviews, we bypass
// the strict containment policy (i.e., UIKit guarantees that every ancestor
// of the hit view will return YES from -pointInside:withEvent:). See:
// - https://developer.apple.com/library/ios/qa/qa2013/qa1812.html
for (UIView *subview in [sortedSubviews reverseObjectEnumerator]) {
CGPoint convertedPoint = [subview convertPoint:point fromView:self];
hitSubview = [subview hitTest:convertedPoint withEvent:event];
if (hitSubview != nil) {
break;
}
}
}
UIView *hitView = (isPointInside ? self : nil);
switch (_pointerEvents) {
case RCTPointerEventsNone:
return nil;
case RCTPointerEventsUnspecified:
return hitSubview ?: hitView;
case RCTPointerEventsBoxOnly:
return hitView;
case RCTPointerEventsBoxNone:
return hitSubview;
default:
RCTLogError(@"Invalid pointer-events specified %lld on %@", (long long)_pointerEvents, self);
return hitSubview ?: hitView;
}
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if (UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero)) {
return [super pointInside:point withEvent:event];
}
CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.hitTestEdgeInsets);
return CGRectContainsPoint(hitFrame, point);
}
#pragma mark - Accessibility
- (NSString *)accessibilityLabel
{
NSString *label = super.accessibilityLabel;
if (label) {
return label;
}
return RCTRecursiveAccessibilityLabel(self);
}
- (NSArray<UIAccessibilityCustomAction *> *)accessibilityCustomActions
{
if (!self.accessibilityActions.count) {
return nil;
}
accessibilityActionsNameMap = [[NSMutableDictionary alloc] init];
accessibilityActionsLabelMap = [[NSMutableDictionary alloc] init];
NSMutableArray *actions = [NSMutableArray array];
for (NSDictionary *action in self.accessibilityActions) {
if (action[@"name"]) {
accessibilityActionsNameMap[action[@"name"]] = action;
}
if (action[@"label"]) {
accessibilityActionsLabelMap[action[@"label"]] = action;
[actions addObject:[[UIAccessibilityCustomAction alloc]
initWithName:action[@"label"]
target:self
selector:@selector(didActivateAccessibilityCustomAction:)]];
}
}
return [actions copy];
}
- (BOOL)didActivateAccessibilityCustomAction:(UIAccessibilityCustomAction *)action
{
if (!_onAccessibilityAction || !accessibilityActionsLabelMap) {
return NO;
}
// iOS defines the name as the localized label, so use our map to convert this back to the non-localized action name
// when passing to JS. This allows for standard action names across platforms.
NSDictionary *actionObject = accessibilityActionsLabelMap[action.name];
if (actionObject) {
_onAccessibilityAction(@{@"actionName" : actionObject[@"name"], @"actionTarget" : self.reactTag});
}
return YES;
}
- (NSString *)accessibilityValue
{
static dispatch_once_t onceToken;
static NSDictionary<NSString *, NSString *> *rolesAndStatesDescription = nil;
dispatch_once(&onceToken, ^{
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"AccessibilityResources" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
if (bundle) {
NSURL *url = [bundle URLForResource:@"Localizable" withExtension:@"strings"];
if (@available(iOS 11.0, *)) {
rolesAndStatesDescription = [NSDictionary dictionaryWithContentsOfURL:url error:nil];
} else {
// Fallback on earlier versions
rolesAndStatesDescription = [NSDictionary dictionaryWithContentsOfURL:url];
}
}
if (rolesAndStatesDescription == nil) {
// Falling back to hardcoded English list.
NSLog(@"Cannot load localized accessibility strings.");
rolesAndStatesDescription = @{
@"alert" : @"alert",
@"checkbox" : @"checkbox",
@"combobox" : @"combo box",
@"menu" : @"menu",
@"menubar" : @"menu bar",
@"menuitem" : @"menu item",
@"progressbar" : @"progress bar",
@"radio" : @"radio button",
@"radiogroup" : @"radio group",
@"scrollbar" : @"scroll bar",
@"spinbutton" : @"spin button",
@"switch" : @"switch",
@"tab" : @"tab",
@"tablist" : @"tab list",
@"timer" : @"timer",
@"toolbar" : @"tool bar",
@"checked" : @"checked",
@"unchecked" : @"not checked",
@"busy" : @"busy",
@"expanded" : @"expanded",
@"collapsed" : @"collapsed",
@"mixed" : @"mixed",
};
}
});
// Handle Switch.
if ((self.accessibilityTraits & SwitchAccessibilityTrait) == SwitchAccessibilityTrait) {
for (NSString *state in self.accessibilityState) {
id val = self.accessibilityState[state];
if (!val) {
continue;
}
if ([state isEqualToString:@"checked"] && [val isKindOfClass:[NSNumber class]]) {
return [val boolValue] ? @"1" : @"0";
}
}
}
NSMutableArray *valueComponents = [NSMutableArray new];
NSString *roleDescription = self.accessibilityRole ? rolesAndStatesDescription[self.accessibilityRole] : nil;
if (roleDescription) {
[valueComponents addObject:roleDescription];
}
// Handle states which haven't already been handled in RCTViewManager.
for (NSString *state in self.accessibilityState) {
id val = self.accessibilityState[state];
if (!val) {
continue;
}
if ([state isEqualToString:@"checked"]) {
if ([val isKindOfClass:[NSNumber class]]) {
[valueComponents addObject:rolesAndStatesDescription[[val boolValue] ? @"checked" : @"unchecked"]];
} else if ([val isKindOfClass:[NSString class]] && [val isEqualToString:@"mixed"]) {
[valueComponents addObject:rolesAndStatesDescription[@"mixed"]];
}
}
if ([state isEqualToString:@"expanded"] && [val isKindOfClass:[NSNumber class]]) {
[valueComponents addObject:rolesAndStatesDescription[[val boolValue] ? @"expanded" : @"collapsed"]];
}
if ([state isEqualToString:@"busy"] && [val isKindOfClass:[NSNumber class]] && [val boolValue]) {
[valueComponents addObject:rolesAndStatesDescription[@"busy"]];
}
}
// Handle accessibilityValue.
if (self.accessibilityValueInternal) {
id min = self.accessibilityValueInternal[@"min"];
id now = self.accessibilityValueInternal[@"now"];
id max = self.accessibilityValueInternal[@"max"];
id text = self.accessibilityValueInternal[@"text"];
if (text && [text isKindOfClass:[NSString class]]) {
[valueComponents addObject:text];
} else if (
[min isKindOfClass:[NSNumber class]] && [now isKindOfClass:[NSNumber class]] &&
[max isKindOfClass:[NSNumber class]] && ([min intValue] < [max intValue]) &&
([min intValue] <= [now intValue] && [now intValue] <= [max intValue])) {
int val = ([now intValue] * 100) / ([max intValue] - [min intValue]);
[valueComponents addObject:[NSString stringWithFormat:@"%d percent", val]];
}
}
if (valueComponents.count > 0) {
return [valueComponents componentsJoinedByString:@", "];
}
return nil;
}
- (UIView *)reactAccessibilityElement
{
return self;
}
- (BOOL)isAccessibilityElement
{
if (self.reactAccessibilityElement == self) {
return [super isAccessibilityElement];
}
return NO;
}
- (BOOL)performAccessibilityAction:(NSString *)name
{
if (_onAccessibilityAction && accessibilityActionsNameMap[name]) {
_onAccessibilityAction(@{@"actionName" : name, @"actionTarget" : self.reactTag});
return YES;
}
return NO;
}
- (BOOL)accessibilityActivate
{
if ([self performAccessibilityAction:@"activate"]) {
return YES;
} else if (_onAccessibilityTap) {
_onAccessibilityTap(nil);
return YES;
} else {
return NO;
}
}
- (BOOL)accessibilityPerformMagicTap
{
if ([self performAccessibilityAction:@"magicTap"]) {
return YES;
} else if (_onMagicTap) {
_onMagicTap(nil);
return YES;
} else {
return NO;
}
}
- (BOOL)accessibilityPerformEscape
{
if ([self performAccessibilityAction:@"escape"]) {
return YES;
} else if (_onAccessibilityEscape) {
_onAccessibilityEscape(nil);
return YES;
} else {
return NO;
}
}
- (void)accessibilityIncrement
{
[self performAccessibilityAction:@"increment"];
}
- (void)accessibilityDecrement
{
[self performAccessibilityAction:@"decrement"];
}
- (NSString *)description
{
NSString *superDescription = super.description;
NSRange semicolonRange = [superDescription rangeOfString:@";"];
NSString *replacement = [NSString stringWithFormat:@"; reactTag: %@;", self.reactTag];
return [superDescription stringByReplacingCharactersInRange:semicolonRange withString:replacement];
}
#pragma mark - Statics for dealing with layoutGuides
+ (void)autoAdjustInsetsForView:(UIView<RCTAutoInsetsProtocol> *)parentView
withScrollView:(UIScrollView *)scrollView
updateOffset:(BOOL)updateOffset
{
UIEdgeInsets baseInset = parentView.contentInset;
CGFloat previousInsetTop = scrollView.contentInset.top;
CGPoint contentOffset = scrollView.contentOffset;
if (parentView.automaticallyAdjustContentInsets) {
UIEdgeInsets autoInset = [self contentInsetsForView:parentView];
baseInset.top += autoInset.top;
baseInset.bottom += autoInset.bottom;
baseInset.left += autoInset.left;
baseInset.right += autoInset.right;
}
scrollView.contentInset = baseInset;
scrollView.scrollIndicatorInsets = baseInset;
if (updateOffset) {
// If we're adjusting the top inset, then let's also adjust the contentOffset so that the view
// elements above the top guide do not cover the content.
// This is generally only needed when your views are initially laid out, for
// manual changes to contentOffset, you can optionally disable this step
CGFloat currentInsetTop = scrollView.contentInset.top;
if (currentInsetTop != previousInsetTop) {
contentOffset.y -= (currentInsetTop - previousInsetTop);
scrollView.contentOffset = contentOffset;
}
}
}
+ (UIEdgeInsets)contentInsetsForView:(UIView *)view
{
while (view) {
UIViewController *controller = view.reactViewController;
if (controller) {
return (UIEdgeInsets){controller.topLayoutGuide.length, 0, controller.bottomLayoutGuide.length, 0};
}
view = view.superview;
}
return UIEdgeInsetsZero;
}
#pragma mark - View Unmounting
- (void)react_remountAllSubviews
{
if (_removeClippedSubviews) {
for (UIView *view in self.reactSubviews) {
if (view.superview != self) {
[self addSubview:view];
[view react_remountAllSubviews];
}
}
} else {
// If _removeClippedSubviews is false, we must already be showing all subviews
[super react_remountAllSubviews];
}
}
- (void)react_updateClippedSubviewsWithClipRect:(CGRect)clipRect relativeToView:(UIView *)clipView
{
// TODO (#5906496): for scrollviews (the primary use-case) we could
// optimize this by only doing a range check along the scroll axis,
// instead of comparing the whole frame
if (!_removeClippedSubviews) {
// Use default behavior if unmounting is disabled
return [super react_updateClippedSubviewsWithClipRect:clipRect relativeToView:clipView];
}
if (self.reactSubviews.count == 0) {
// Do nothing if we have no subviews
return;
}
if (CGSizeEqualToSize(self.bounds.size, CGSizeZero)) {
// Do nothing if layout hasn't happened yet
return;
}
// Convert clipping rect to local coordinates
clipRect = [clipView convertRect:clipRect toView:self];
clipRect = CGRectIntersection(clipRect, self.bounds);
clipView = self;
// Mount / unmount views
for (UIView *view in self.reactSubviews) {
if (!CGSizeEqualToSize(CGRectIntersection(clipRect, view.frame).size, CGSizeZero)) {
// View is at least partially visible, so remount it if unmounted
[self addSubview:view];
// Then test its subviews
if (CGRectContainsRect(clipRect, view.frame)) {
// View is fully visible, so remount all subviews
[view react_remountAllSubviews];
} else {
// View is partially visible, so update clipped subviews
[view react_updateClippedSubviewsWithClipRect:clipRect relativeToView:clipView];
}
} else if (view.superview) {
// View is completely outside the clipRect, so unmount it
[view removeFromSuperview];
}
}
}
- (void)setRemoveClippedSubviews:(BOOL)removeClippedSubviews
{
if (!removeClippedSubviews && _removeClippedSubviews) {
[self react_remountAllSubviews];
}
_removeClippedSubviews = removeClippedSubviews;
}
- (void)didUpdateReactSubviews
{
if (_removeClippedSubviews) {
[self updateClippedSubviews];
} else {
[super didUpdateReactSubviews];
}
}
- (void)updateClippedSubviews
{
// Find a suitable view to use for clipping
UIView *clipView = [self react_findClipView];
if (clipView) {
[self react_updateClippedSubviewsWithClipRect:clipView.bounds relativeToView:clipView];
}
}
- (void)layoutSubviews
{
// TODO (#5906496): this a nasty performance drain, but necessary
// to prevent gaps appearing when the loading spinner disappears.
// We might be able to fix this another way by triggering a call
// to updateClippedSubviews manually after loading
[super layoutSubviews];
if (_removeClippedSubviews) {
[self updateClippedSubviews];
}
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
{
[super traitCollectionDidChange:previousTraitCollection];
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13.0, *)) {
if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
[self.layer setNeedsDisplay];
}
}
#endif
}
#pragma mark - Borders
- (UIColor *)backgroundColor
{
return _backgroundColor;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
if ([_backgroundColor isEqual:backgroundColor]) {
return;
}
_backgroundColor = backgroundColor;
[self.layer setNeedsDisplay];
}
static CGFloat RCTDefaultIfNegativeTo(CGFloat defaultValue, CGFloat x)
{
return x >= 0 ? x : defaultValue;
};
- (UIEdgeInsets)bordersAsInsets
{
const CGFloat borderWidth = MAX(0, _borderWidth);
const BOOL isRTL = _reactLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
if ([[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) {
const CGFloat borderStartWidth = RCTDefaultIfNegativeTo(_borderLeftWidth, _borderStartWidth);
const CGFloat borderEndWidth = RCTDefaultIfNegativeTo(_borderRightWidth, _borderEndWidth);
const CGFloat directionAwareBorderLeftWidth = isRTL ? borderEndWidth : borderStartWidth;
const CGFloat directionAwareBorderRightWidth = isRTL ? borderStartWidth : borderEndWidth;
return (UIEdgeInsets){
RCTDefaultIfNegativeTo(borderWidth, _borderTopWidth),
RCTDefaultIfNegativeTo(borderWidth, directionAwareBorderLeftWidth),
RCTDefaultIfNegativeTo(borderWidth, _borderBottomWidth),
RCTDefaultIfNegativeTo(borderWidth, directionAwareBorderRightWidth),
};
}
const CGFloat directionAwareBorderLeftWidth = isRTL ? _borderEndWidth : _borderStartWidth;
const CGFloat directionAwareBorderRightWidth = isRTL ? _borderStartWidth : _borderEndWidth;
return (UIEdgeInsets){
RCTDefaultIfNegativeTo(borderWidth, _borderTopWidth),
RCTDefaultIfNegativeTo(borderWidth, RCTDefaultIfNegativeTo(_borderLeftWidth, directionAwareBorderLeftWidth)),
RCTDefaultIfNegativeTo(borderWidth, _borderBottomWidth),
RCTDefaultIfNegativeTo(borderWidth, RCTDefaultIfNegativeTo(_borderRightWidth, directionAwareBorderRightWidth)),
};
}
- (RCTCornerRadii)cornerRadii
{
const BOOL isRTL = _reactLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
const CGFloat radius = MAX(0, _borderRadius);
CGFloat topLeftRadius;
CGFloat topRightRadius;
CGFloat bottomLeftRadius;
CGFloat bottomRightRadius;
if ([[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) {
const CGFloat topStartRadius = RCTDefaultIfNegativeTo(_borderTopLeftRadius, _borderTopStartRadius);
const CGFloat topEndRadius = RCTDefaultIfNegativeTo(_borderTopRightRadius, _borderTopEndRadius);
const CGFloat bottomStartRadius = RCTDefaultIfNegativeTo(_borderBottomLeftRadius, _borderBottomStartRadius);
const CGFloat bottomEndRadius = RCTDefaultIfNegativeTo(_borderBottomRightRadius, _borderBottomEndRadius);
const CGFloat directionAwareTopLeftRadius = isRTL ? topEndRadius : topStartRadius;
const CGFloat directionAwareTopRightRadius = isRTL ? topStartRadius : topEndRadius;
const CGFloat directionAwareBottomLeftRadius = isRTL ? bottomEndRadius : bottomStartRadius;
const CGFloat directionAwareBottomRightRadius = isRTL ? bottomStartRadius : bottomEndRadius;
topLeftRadius = RCTDefaultIfNegativeTo(radius, directionAwareTopLeftRadius);
topRightRadius = RCTDefaultIfNegativeTo(radius, directionAwareTopRightRadius);
bottomLeftRadius = RCTDefaultIfNegativeTo(radius, directionAwareBottomLeftRadius);
bottomRightRadius = RCTDefaultIfNegativeTo(radius, directionAwareBottomRightRadius);
} else {
const CGFloat directionAwareTopLeftRadius = isRTL ? _borderTopEndRadius : _borderTopStartRadius;
const CGFloat directionAwareTopRightRadius = isRTL ? _borderTopStartRadius : _borderTopEndRadius;
const CGFloat directionAwareBottomLeftRadius = isRTL ? _borderBottomEndRadius : _borderBottomStartRadius;
const CGFloat directionAwareBottomRightRadius = isRTL ? _borderBottomStartRadius : _borderBottomEndRadius;
topLeftRadius =
RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderTopLeftRadius, directionAwareTopLeftRadius));
topRightRadius =
RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderTopRightRadius, directionAwareTopRightRadius));
bottomLeftRadius =
RCTDefaultIfNegativeTo(radius, RCTDefaultIfNegativeTo(_borderBottomLeftRadius, directionAwareBottomLeftRadius));
bottomRightRadius = RCTDefaultIfNegativeTo(
radius, RCTDefaultIfNegativeTo(_borderBottomRightRadius, directionAwareBottomRightRadius));
}
// Get scale factors required to prevent radii from overlapping
const CGSize size = self.bounds.size;
const CGFloat topScaleFactor = RCTZeroIfNaN(MIN(1, size.width / (topLeftRadius + topRightRadius)));
const CGFloat bottomScaleFactor = RCTZeroIfNaN(MIN(1, size.width / (bottomLeftRadius + bottomRightRadius)));
const CGFloat rightScaleFactor = RCTZeroIfNaN(MIN(1, size.height / (topRightRadius + bottomRightRadius)));
const CGFloat leftScaleFactor = RCTZeroIfNaN(MIN(1, size.height / (topLeftRadius + bottomLeftRadius)));
// Return scaled radii
return (RCTCornerRadii){
topLeftRadius * MIN(topScaleFactor, leftScaleFactor),
topRightRadius * MIN(topScaleFactor, rightScaleFactor),
bottomLeftRadius * MIN(bottomScaleFactor, leftScaleFactor),
bottomRightRadius * MIN(bottomScaleFactor, rightScaleFactor),
};
}
- (RCTBorderColors)borderColors
{
const BOOL isRTL = _reactLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
if ([[RCTI18nUtil sharedInstance] doLeftAndRightSwapInRTL]) {
const CGColorRef borderStartColor = _borderStartColor ?: _borderLeftColor;
const CGColorRef borderEndColor = _borderEndColor ?: _borderRightColor;
const CGColorRef directionAwareBorderLeftColor = isRTL ? borderEndColor : borderStartColor;
const CGColorRef directionAwareBorderRightColor = isRTL ? borderStartColor : borderEndColor;
return (RCTBorderColors){
_borderTopColor ?: _borderColor,
directionAwareBorderLeftColor ?: _borderColor,
_borderBottomColor ?: _borderColor,
directionAwareBorderRightColor ?: _borderColor,
};
}
const CGColorRef directionAwareBorderLeftColor = isRTL ? _borderEndColor : _borderStartColor;
const CGColorRef directionAwareBorderRightColor = isRTL ? _borderStartColor : _borderEndColor;
return (RCTBorderColors){
_borderTopColor ?: _borderColor,
directionAwareBorderLeftColor ?: _borderLeftColor ?: _borderColor,
_borderBottomColor ?: _borderColor,
directionAwareBorderRightColor ?: _borderRightColor ?: _borderColor,
};
}
- (void)reactSetFrame:(CGRect)frame
{
// If frame is zero, or below the threshold where the border radii can
// be rendered as a stretchable image, we'll need to re-render.
// TODO: detect up-front if re-rendering is necessary
CGSize oldSize = self.bounds.size;
[super reactSetFrame:frame];
if (!CGSizeEqualToSize(self.bounds.size, oldSize)) {
[self.layer setNeedsDisplay];
}
}
- (void)displayLayer:(CALayer *)layer
{
if (CGSizeEqualToSize(layer.bounds.size, CGSizeZero)) {
return;
}
RCTUpdateShadowPathForView(self);
const RCTCornerRadii cornerRadii = [self cornerRadii];
const UIEdgeInsets borderInsets = [self bordersAsInsets];
const RCTBorderColors borderColors = [self borderColors];
BOOL useIOSBorderRendering = RCTCornerRadiiAreEqual(cornerRadii) && RCTBorderInsetsAreEqual(borderInsets) &&
RCTBorderColorsAreEqual(borderColors) && _borderStyle == RCTBorderStyleSolid &&
// iOS draws borders in front of the content whereas CSS draws them behind
// the content. For this reason, only use iOS border drawing when clipping
// or when the border is hidden.
(borderInsets.top == 0 || (borderColors.top && CGColorGetAlpha(borderColors.top) == 0) || self.clipsToBounds);
// iOS clips to the outside of the border, but CSS clips to the inside. To
// solve this, we'll need to add a container view inside the main view to
// correctly clip the subviews.
CGColorRef backgroundColor;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13.0, *)) {
backgroundColor = [_backgroundColor resolvedColorWithTraitCollection:self.traitCollection].CGColor;
} else {
backgroundColor = _backgroundColor.CGColor;
}
#else
backgroundColor = _backgroundColor.CGColor;
#endif
if (useIOSBorderRendering) {
layer.cornerRadius = cornerRadii.topLeft;
layer.borderColor = borderColors.left;
layer.borderWidth = borderInsets.left;
layer.backgroundColor = backgroundColor;
layer.contents = nil;
layer.needsDisplayOnBoundsChange = NO;
layer.mask = nil;
return;
}
UIImage *image = RCTGetBorderImage(
_borderStyle, layer.bounds.size, cornerRadii, borderInsets, borderColors, backgroundColor, self.clipsToBounds);
layer.backgroundColor = NULL;
if (image == nil) {
layer.contents = nil;
layer.needsDisplayOnBoundsChange = NO;
return;
}
CGRect contentsCenter = ({
CGSize size = image.size;
UIEdgeInsets insets = image.capInsets;
CGRectMake(
insets.left / size.width, insets.top / size.height, (CGFloat)1.0 / size.width, (CGFloat)1.0 / size.height);
});
layer.contents = (id)image.CGImage;
layer.contentsScale = image.scale;
layer.needsDisplayOnBoundsChange = YES;
layer.magnificationFilter = kCAFilterNearest;
const BOOL isResizable = !UIEdgeInsetsEqualToEdgeInsets(image.capInsets, UIEdgeInsetsZero);
if (isResizable) {
layer.contentsCenter = contentsCenter;
} else {
layer.contentsCenter = CGRectMake(0.0, 0.0, 1.0, 1.0);
}
[self updateClippingForLayer:layer];
}
static BOOL RCTLayerHasShadow(CALayer *layer)
{
return layer.shadowOpacity * CGColorGetAlpha(layer.shadowColor) > 0;
}
static void RCTUpdateShadowPathForView(RCTView *view)
{
if (RCTLayerHasShadow(view.layer)) {
if (CGColorGetAlpha(view.backgroundColor.CGColor) > 0.999) {
// If view has a solid background color, calculate shadow path from border
const RCTCornerRadii cornerRadii = [view cornerRadii];
const RCTCornerInsets cornerInsets = RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero);
CGPathRef shadowPath = RCTPathCreateWithRoundedRect(view.bounds, cornerInsets, NULL);
view.layer.shadowPath = shadowPath;
CGPathRelease(shadowPath);
} else {
// Can't accurately calculate box shadow, so fall back to pixel-based shadow
view.layer.shadowPath = nil;
RCTLogAdvice(
@"View #%@ of type %@ has a shadow set but cannot calculate "
"shadow efficiently. Consider setting a background color to "
"fix this, or apply the shadow to a more specific component.",
view.reactTag,
[view class]);
}
}
}
- (void)updateClippingForLayer:(CALayer *)layer
{
CALayer *mask = nil;
CGFloat cornerRadius = 0;
if (self.clipsToBounds) {
const RCTCornerRadii cornerRadii = [self cornerRadii];
if (RCTCornerRadiiAreEqual(cornerRadii)) {
cornerRadius = cornerRadii.topLeft;
} else {
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGPathRef path =
RCTPathCreateWithRoundedRect(self.bounds, RCTGetCornerInsets(cornerRadii, UIEdgeInsetsZero), NULL);
shapeLayer.path = path;
CGPathRelease(path);
mask = shapeLayer;
}
}
layer.cornerRadius = cornerRadius;
layer.mask = mask;
}
#pragma mark Border Color
#define setBorderColor(side) \
-(void)setBorder##side##Color : (CGColorRef)color \
{ \
if (CGColorEqualToColor(_border##side##Color, color)) { \
return; \
} \
CGColorRelease(_border##side##Color); \
_border##side##Color = CGColorRetain(color); \
[self.layer setNeedsDisplay]; \
}
setBorderColor() setBorderColor(Top) setBorderColor(Right) setBorderColor(Bottom) setBorderColor(Left)
setBorderColor(Start) setBorderColor(End)
#pragma mark - Border Width
#define setBorderWidth(side) \
-(void)setBorder##side##Width : (CGFloat)width \
{ \
if (_border##side##Width == width) { \
return; \
} \
_border##side##Width = width; \
[self.layer setNeedsDisplay]; \
}
setBorderWidth() setBorderWidth(Top) setBorderWidth(Right) setBorderWidth(Bottom) setBorderWidth(Left)
setBorderWidth(Start) setBorderWidth(End)
#pragma mark - Border Radius
#define setBorderRadius(side) \
-(void)setBorder##side##Radius : (CGFloat)radius \
{ \
if (_border##side##Radius == radius) { \
return; \
} \
_border##side##Radius = radius; \
[self.layer setNeedsDisplay]; \
}
setBorderRadius() setBorderRadius(TopLeft) setBorderRadius(TopRight) setBorderRadius(TopStart)
setBorderRadius(TopEnd) setBorderRadius(BottomLeft) setBorderRadius(BottomRight)
setBorderRadius(BottomStart) setBorderRadius(BottomEnd)
#pragma mark - Border Style
#define setBorderStyle(side) \
-(void)setBorder##side##Style : (RCTBorderStyle)style \
{ \
if (_border##side##Style == style) { \
return; \
} \
_border##side##Style = style; \
[self.layer setNeedsDisplay]; \
}
setBorderStyle()
- (void)dealloc
{
CGColorRelease(_borderColor);
CGColorRelease(_borderTopColor);
CGColorRelease(_borderRightColor);
CGColorRelease(_borderBottomColor);
CGColorRelease(_borderLeftColor);
CGColorRelease(_borderStartColor);
CGColorRelease(_borderEndColor);
}
@end
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<spirit:design xmlns:xilinx="http://www.xilinx.com" xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<spirit:vendor>xilinx.com</spirit:vendor>
<spirit:library>xci</spirit:library>
<spirit:name>unknown</spirit:name>
<spirit:version>1.0</spirit:version>
<spirit:componentInstances>
<spirit:componentInstance>
<spirit:instanceName>PCIeGen2x8If128</spirit:instanceName>
<spirit:componentRef spirit:vendor="xilinx.com" spirit:library="ip" spirit:name="pcie3_7x" spirit:version="4.1"/>
<spirit:configurableElementValues>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.ARI_CAP_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_CC_ALIGNMENT_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_CQ_ALIGNMENT_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_ENABLE_CLIENT_TAG">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_ENABLE_MSG_ROUTE">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_ENABLE_RX_MSG_INTFC">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_RC_ALIGNMENT_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_RC_STRADDLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.AXISTEN_IF_RQ_ALIGNMENT_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.CFG_CTL_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.CFG_EXT_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.CFG_FC_IF">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.CFG_MGMT_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.CFG_STATUS_IF">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.CFG_TX_MSG_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.COMPLETION_SPACE">16KB</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.C_DATA_WIDTH">128</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.DEV_PORT_TYPE">00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.EXT_CH_GT_DRP">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.EXT_PIPE_INTERFACE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.EXT_STARTUP_PRIMITIVE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.MSIX_EN">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.MSI_EN">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PCIE_DRP">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PCIE_EXT_CLK">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PCIE_EXT_GT_COMMON">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PCIE_FAST_CONFIG">NONE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PCIE_LINK_SPEED">3</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PCIE_USE_MODE">2.1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PER_FUNC_STATUS_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_AER_CAP_ECRC_CHECK_CAPABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_AER_CAP_ECRC_GEN_CAPABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_AER_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_ARI_CAP_NEXT_FUNC">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR0_APERTURE_SIZE">0b00011</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR0_CONTROL">0b100</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR1_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR1_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR2_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR2_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR3_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR3_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR4_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR4_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR5_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_BAR5_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_CAPABILITY_POINTER">0x80</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_CLASS_CODE">0x058000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEVICE_ID">0x7028</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP2_128B_CAS_ATOMIC_COMPLETER_SUPPORT">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP2_32B_ATOMIC_COMPLETER_SUPPORT">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP2_64B_ATOMIC_COMPLETER_SUPPORT">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP2_LTR_SUPPORT">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP2_OBFF_SUPPORT">00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP2_TPH_COMPLETER_SUPPORT">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP_EXT_TAG_SUPPORTED">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP_FUNCTION_LEVEL_RESET_CAPABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DEV_CAP_MAX_PAYLOAD_SIZE">0b010</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION0">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION1">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION2">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION3">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION4">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION5">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION6">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DPA_CAP_SUB_STATE_POWER_ALLOCATION7">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_DSN_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_EXPANSION_ROM_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_EXPANSION_ROM_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_INTERRUPT_PIN">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_LINK_CAP_ASPM_SUPPORT">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_LINK_STATUS_SLOT_CLOCK_CONFIG">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_LTR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSIX_CAP_NEXTPTR">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_MSI_CAP_NEXTPTR">0xC0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_PB_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_PM_CAP_NEXTPTR">0x90</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_PM_CAP_PMESUPPORT_D0">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_PM_CAP_PMESUPPORT_D1">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_PM_CAP_PMESUPPORT_D3HOT">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_PM_CAP_SUPP_D1_STATE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_RBAR_CAP_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_RBAR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_RBAR_CAP_SIZE0">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_RBAR_CAP_SIZE1">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_RBAR_CAP_SIZE2">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_REVISION_ID">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR0_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR0_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR1_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR1_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR2_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR2_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR3_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR3_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR4_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR4_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR5_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_BAR5_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_CAP_INITIAL_VF">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_CAP_TOTAL_VF">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_CAP_VER">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_FIRST_VF_OFFSET">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_FUNC_DEP_LINK">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_SUPPORTED_PAGE_SIZE">0x00000553</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SRIOV_VF_DEVICE_ID">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SUBSYSTEM_ID">0x0007</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_SUBSYSTEM_VENDOR_ID">0x10EE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_VC_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF0_VENDOR_ID">0x10EE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_AER_CAP_ECRC_CHECK_CAPABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_AER_CAP_ECRC_GEN_CAPABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_AER_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR0_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR0_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR1_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR1_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR2_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR2_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR3_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR3_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR4_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR4_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR5_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_BAR5_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_CAPABILITY_POINTER">0x80</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_CLASS_CODE">0x058000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DEVICE_ID">0x7011</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DEV_CAP_MAX_PAYLOAD_SIZE">0b010</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION0">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION1">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION2">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION3">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION4">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION5">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION6">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DPA_CAP_SUB_STATE_POWER_ALLOCATION7">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_DSN_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_EXPANSION_ROM_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_EXPANSION_ROM_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_INTERRUPT_PIN">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSIX_CAP_NEXTPTR">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_MSI_CAP_NEXTPTR">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_PB_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_PM_CAP_NEXTPTR">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_RBAR_CAP_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_RBAR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_RBAR_CAP_SIZE0">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_RBAR_CAP_SIZE1">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_RBAR_CAP_SIZE2">0x00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_REVISION_ID">0x00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR0_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR0_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR1_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR1_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR2_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR2_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR3_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR3_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR4_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR4_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR5_APERTURE_SIZE">0b00000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_BAR5_CONTROL">0b000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_CAP_INITIAL_VF">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_CAP_TOTAL_VF">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_CAP_VER">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_FIRST_VF_OFFSET">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_FUNC_DEP_LINK">0x0001</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_SUPPORTED_PAGE_SIZE">0x00000553</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SRIOV_VF_DEVICE_ID">0x0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_SUBSYSTEM_ID">0x0007</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PF1_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PIPE_SIM">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PL_LINK_CAP_MAX_LINK_SPEED">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PL_LINK_CAP_MAX_LINK_WIDTH">8</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.PL_UPSTREAM_FACING">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.POWER_DOWN">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.RCV_MSG_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.REF_CLK_FREQ">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.SHARED_LOGIC_IN_CORE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.SPARE_WORD1">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.SRIOV_CAP_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_CREDITS_CD">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_CREDITS_CH">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_CREDITS_NPD">0x028</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_CREDITS_NPH">0x20</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_CREDITS_PD">0x198</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_CREDITS_PH">0x20</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_EXTENDED_CFG_EXTEND_INTERFACE_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_LEGACY_MODE_ENABLE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TL_PF_ENABLE_REG">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TRANSCEIVER_CTRL_STATUS_PORTS">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.TX_FC_IF">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.USER_CLK2_FREQ">4</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_CAPABILITY_POINTER">0x80</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_PM_CAP_NEXTPTR">"00000000"</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF0_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_PM_CAP_NEXTPTR">"00000000"</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF1_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_PM_CAP_NEXTPTR">"00000000"</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF2_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_PM_CAP_NEXTPTR">"00000000"</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF3_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_PM_CAP_NEXTPTR">"00000000"</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF4_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_ARI_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_MSIX_CAP_PBA_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_MSIX_CAP_PBA_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_MSIX_CAP_TABLE_BIR">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_MSIX_CAP_TABLE_OFFSET">0x00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_MSIX_CAP_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_MSI_CAP_MULTIMSGCAP">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_PM_CAP_NEXTPTR">"00000000"</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_DEV_SPECIFIC_MODE">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_INT_VEC_MODE">FALSE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_NEXTPTR">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_ST_MODE_SEL">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_ST_TABLE_LOC">0x0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_ST_TABLE_SIZE">0x000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.VF5_TPHR_CAP_VER">0x1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.gen_x0y0_ucf">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.gen_x0y1_ucf">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.gen_x0y2_ucf">1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.gen_x0y3_ucf">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.pcie_blk_locn">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.silicon_revision">Production</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="MODELPARAM_VALUE.xlnx_ref_board">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_ENABLEMENT.xlnx_ref_board">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.AXISTEN_IF_RC_STRADDLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.Component_Name">PCIeGen2x8If128</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_AER_CAP_ECRC_CHECK_CAPABLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_AER_CAP_ECRC_GEN_CAPABLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_CLASS_CODE">058000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEVICE_ID">7028</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEV_CAP2_128B_CAS_ATOMIC_COMPLETER_SUPPORT">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEV_CAP2_32B_ATOMIC_COMPLETER_SUPPORT">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEV_CAP2_64B_ATOMIC_COMPLETER_SUPPORT">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEV_CAP2_OBFF_SUPPORT">00_Not_Supported</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEV_CAP2_TPH_COMPLETER_SUPPORT">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_DEV_CAP_FUNCTION_LEVEL_RESET_CAPABLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_INTERRUPT_PIN">NONE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_LINK_STATUS_SLOT_CLOCK_CONFIG">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_PM_CAP_PMESUPPORT_D0">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_PM_CAP_PMESUPPORT_D1">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_PM_CAP_PMESUPPORT_D3HOT">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_PM_CAP_SUPP_D1_STATE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_REVISION_ID">00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SRIOV_CAP_INITIAL_VF">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SRIOV_FIRST_VF_OFFSET">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SRIOV_FUNC_DEP_LINK">0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SRIOV_SUPPORTED_PAGE_SIZE">00000553</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SRIOV_VF_DEVICE_ID">0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SUBSYSTEM_ID">0007</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_SUBSYSTEM_VENDOR_ID">10EE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF0_Use_Class_Code_Lookup_Assistant">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_AER_CAP_ECRC_CHECK_CAPABLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_AER_CAP_ECRC_GEN_CAPABLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_CLASS_CODE">058000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_DEVICE_ID">7011</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_INTERRUPT_PIN">NONE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_REVISION_ID">00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SRIOV_CAP_INITIAL_VF">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SRIOV_CAP_VER">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SRIOV_FIRST_VF_OFFSET">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SRIOV_FUNC_DEP_LINK">0001</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SRIOV_SUPPORTED_PAGE_SIZE">00000553</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SRIOV_VF_DEVICE_ID">0000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_SUBSYSTEM_ID">0007</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PF1_Use_Class_Code_Lookup_Assistant">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PL_LINK_CAP_MAX_LINK_SPEED">5.0_GT/s</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.PL_LINK_CAP_MAX_LINK_WIDTH">X8</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.REF_CLK_FREQ">100_MHz</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.RESET_BOARD_INTERFACE">Custom</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.SRIOV_CAP_ENABLE">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.SRIOV_CAP_ENABLE_EXT">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.TL_PF_ENABLE_REG">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.USE_BOARD_FLOW">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF0_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF0_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF0_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF0_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF0_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF0_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF1_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF1_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF1_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF1_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF1_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF1_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF2_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF2_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF2_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF2_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF2_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF2_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF3_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF3_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF3_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF3_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF3_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF3_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF4_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF4_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF4_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF4_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF4_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF4_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF5_MSIX_CAP_PBA_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF5_MSIX_CAP_PBA_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF5_MSIX_CAP_TABLE_BIR">BAR_0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF5_MSIX_CAP_TABLE_OFFSET">00000000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF5_MSIX_CAP_TABLE_SIZE">000</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.VF5_MSI_CAP_MULTIMSGCAP">1_vector</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.alignment_mode">DWORD_Aligned</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.aspm_support">No_ASPM</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.axisten_freq">250</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.axisten_if_enable_client_tag">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.axisten_if_enable_msg_route">2FFFF</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.axisten_if_enable_rx_msg_intfc">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.axisten_if_width">128_bit</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.cfg_ctl_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.cfg_ext_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.cfg_fc_if">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.cfg_mgmt_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.cfg_status_if">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.cfg_tx_msg_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.device_port_type">PCI_Express_Endpoint_device</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_ext_ch_gt_drp">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_ext_clk">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_ext_gt_common">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_ext_pipe_interface">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_ext_startup">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_msi_per_vec_masking">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_pcie_drp">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_powerdown">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.en_transceiver_status_ports">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.ext_pcie_cfg_space_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.extended_tag_field">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.gen_x0y0">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.gen_x0y1">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.gen_x0y2">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.gen_x0y3">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.mode_selection">Advanced</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pcie_blk_locn">X0Y2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.per_func_status_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.perf_level">Extreme</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.performance">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_aer_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_ari_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar0_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar0_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar0_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar0_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar0_size">1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar0_type">Memory</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar1_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar1_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar1_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar1_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar1_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar1_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar2_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar2_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar2_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar2_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar2_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar2_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar3_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar3_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar3_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar3_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar3_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar3_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar4_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar4_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar4_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar4_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar4_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar4_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar5_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar5_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar5_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar5_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_bar5_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_base_class_menu">Simple_communication_controllers</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_class_code_base">05</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_class_code_interface">00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_class_code_sub">80</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_dev_cap_max_payload">512_bytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_dpa_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_dsn_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_expansion_rom_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_expansion_rom_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_expansion_rom_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_ltr_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_msi_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_msix_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_pb_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_rbar_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar0_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar0_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar0_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar0_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar0_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar0_type">Memory</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar1_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar1_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar1_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar1_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar1_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar1_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar2_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar2_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar2_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar2_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar2_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar2_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar3_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar3_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar3_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar3_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar3_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar3_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar4_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar4_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar4_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar4_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar4_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar4_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar5_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar5_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar5_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar5_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_bar5_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sriov_cap_ver">0</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_sub_class_interface_menu">Generic_XT_compatible_serial_controller</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_tphr_enable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf0_vc_cap_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_aer_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_ari_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar0_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar0_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar0_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar0_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar0_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar0_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar1_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar1_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar1_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar1_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar1_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar1_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar2_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar2_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar2_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar2_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar2_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar2_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar3_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar3_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar3_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar3_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar3_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar3_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar4_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar4_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar4_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar4_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar4_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar4_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar5_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar5_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar5_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar5_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_bar5_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_base_class_menu">Simple_communication_controllers</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_class_code_base">05</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_class_code_interface">00</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_class_code_sub">80</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_dev_cap_max_payload">512_bytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_dpa_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_dsn_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_expansion_rom_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_expansion_rom_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_expansion_rom_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_msi_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_msix_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_pb_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_rbar_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar0_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar0_enabled">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar0_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar0_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar0_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar0_type">Memory</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar1_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar1_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar1_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar1_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar1_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar1_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar2_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar2_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar2_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar2_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar2_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar2_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar3_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar3_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar3_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar3_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar3_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar3_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar4_64bit">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar4_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar4_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar4_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar4_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar4_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar5_enabled">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar5_prefetchable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar5_scale">Kilobytes</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar5_size">2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sriov_bar5_type">N/A</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_sub_class_interface_menu">Generic_XT_compatible_serial_controller</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pf1_tphr_enable">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pipe_mode_sim">None</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.pipe_sim">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.rcv_msg_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.shared_logic_in_core">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.silicon_rev">Production</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.tandem_mode">None</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.tl_pf0_enable_reg">true</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.tx_fc_if">false</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.vendor_id">10EE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PARAM_VALUE.xlnx_ref_board">None</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.ARCHITECTURE">virtex7</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.BOARD"/>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.DEVICE">xc7vx690t</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.PACKAGE">ffg1157</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.PREFHDL">VERILOG</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.SILICON_REVISION"/>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.SIMULATOR_LANGUAGE">MIXED</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.SPEEDGRADE">-2</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.TEMPERATURE_GRADE">C</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.USE_RDI_CUSTOMIZATION">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="PROJECT_PARAM.USE_RDI_GENERATION">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.IPCONTEXT">IP_Flow</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.IPREVISION">1</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.MANAGED">TRUE</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.OUTPUTDIR">.</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SELECTEDSIMMODEL"/>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SHAREDDIR">.</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SWVERSION">2015.4</spirit:configurableElementValue>
<spirit:configurableElementValue spirit:referenceId="RUNTIME_PARAM.SYNTHESISFLOW">OUT_OF_CONTEXT</spirit:configurableElementValue>
</spirit:configurableElementValues>
</spirit:componentInstance>
</spirit:componentInstances>
</spirit:design>
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
def short_side_resize(img_tensor, gtboxes_and_label, target_shortside_len):
'''
:param img_tensor:[h, w, c], gtboxes_and_label:[-1, 9]
:param target_shortside_len:
:return:
'''
h, w = tf.shape(img_tensor)[0], tf.shape(img_tensor)[1]
new_h, new_w = tf.cond(tf.less(h, w),
true_fn=lambda: (target_shortside_len, target_shortside_len * w//h),
false_fn=lambda: (target_shortside_len * h//w, target_shortside_len))
img_tensor = tf.expand_dims(img_tensor, axis=0)
img_tensor = tf.image.resize_bilinear(img_tensor, [new_h, new_w])
x1, y1, x2, y2, x3, y3, x4, y4, label = tf.unstack(gtboxes_and_label, axis=1)
x1, x2, x3, x4 = x1 * new_w//w, x2 * new_w//w, x3 * new_w//w, x4 * new_w//w
y1, y2, y3, y4 = y1 * new_h//h, y2 * new_h//h, y3 * new_h//h, y4 * new_h//h
img_tensor = tf.squeeze(img_tensor, axis=0) # ensure image tensor rank is 3
return img_tensor, tf.transpose(tf.stack([x1, y1, x2, y2, x3, y3, x4, y4, label], axis=0))
def short_side_resize_for_inference_data(img_tensor, target_shortside_len, is_resize=True):
h, w, = tf.shape(img_tensor)[0], tf.shape(img_tensor)[1]
img_tensor = tf.expand_dims(img_tensor, axis=0)
if is_resize:
new_h, new_w = tf.cond(tf.less(h, w),
true_fn=lambda: (target_shortside_len, target_shortside_len*w//h),
false_fn=lambda: (target_shortside_len*h//w, target_shortside_len))
img_tensor = tf.image.resize_bilinear(img_tensor, [new_h, new_w])
return img_tensor # [1, h, w, c]
def flip_left_right(img_tensor, gtboxes_and_label):
h, w = tf.shape(img_tensor)[0], tf.shape(img_tensor)[1]
img_tensor = tf.image.flip_left_right(img_tensor)
x1, y1, x2, y2, x3, y3, x4, y4, label = tf.unstack(gtboxes_and_label, axis=1)
new_x1 = w - x1
new_x2 = w - x2
new_x3 = w - x3
new_x4 = w - x4
return img_tensor, tf.transpose(tf.stack([new_x1, y1, new_x2, y2, new_x3, y3, new_x4, y4, label], axis=0))
def random_flip_left_right(img_tensor, gtboxes_and_label):
img_tensor, gtboxes_and_label = tf.cond(tf.less(tf.random_uniform(shape=[], minval=0, maxval=1), 0.5),
lambda: flip_left_right(img_tensor, gtboxes_and_label),
lambda: (img_tensor, gtboxes_and_label))
return img_tensor, gtboxes_and_label
|
{
"pile_set_name": "Github"
}
|
import Foundation
/// A Nimble matcher that succeeds when the actual expression evaluates to an
/// error from the specified case.
///
/// Errors are tried to be compared by their implementation of Equatable,
/// otherwise they fallback to comparison by _domain and _code.
public func matchError<T: Error>(_ error: T) -> Predicate<Error> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
let actualError: Error? = try actualExpression.evaluate()
setFailureMessageForError(failureMessage, postfixMessageVerb: "match", actualError: actualError, error: error)
var matches = false
if let actualError = actualError, errorMatchesExpectedError(actualError, expectedError: error) {
matches = true
}
return matches
}.requireNonNil
}
/// A Nimble matcher that succeeds when the actual expression evaluates to an
/// error from the specified case.
///
/// Errors are tried to be compared by their implementation of Equatable,
/// otherwise they fallback to comparision by _domain and _code.
public func matchError<T: Error & Equatable>(_ error: T) -> Predicate<Error> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
let actualError: Error? = try actualExpression.evaluate()
setFailureMessageForError(failureMessage, postfixMessageVerb: "match", actualError: actualError, error: error)
var matches = false
if let actualError = actualError as? T, error == actualError {
matches = true
}
return matches
}.requireNonNil
}
/// A Nimble matcher that succeeds when the actual expression evaluates to an
/// error of the specified type
public func matchError<T: Error>(_ errorType: T.Type) -> Predicate<Error> {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
let actualError: Error? = try actualExpression.evaluate()
setFailureMessageForError(
failureMessage,
postfixMessageVerb: "match",
actualError: actualError,
errorType: errorType
)
var matches = false
if actualError as? T != nil {
matches = true
}
return matches
}.requireNonNil
}
|
{
"pile_set_name": "Github"
}
|
<?php
// Supermicro sensors
$oids = snmp_walk($device, '.1.3.6.1.4.1.10876.2.1.1.1.1.3', '-Osqn', 'SUPERMICRO-HEALTH-MIB');
$oids = trim($oids);
if ($oids) {
echo 'Supermicro ';
foreach (explode("\n", $oids) as $data) {
$data = trim($data);
if ($data) {
[$oid, $type] = explode(' ', $data);
$oid_ex = explode('.', $oid);
$index = $oid_ex[(count($oid_ex) - 1)];
if ($type == 2) {
$temperature_oid = ".1.3.6.1.4.1.10876.2.1.1.1.1.4.$index";
$descr_oid = ".1.3.6.1.4.1.10876.2.1.1.1.1.2.$index";
$limit_oid = ".1.3.6.1.4.1.10876.2.1.1.1.1.5.$index";
$divisor_oid = ".1.3.6.1.4.1.10876.2.1.1.1.1.9.$index";
$monitor_oid = ".1.3.6.1.4.1.10876.2.1.1.1.1.10.$index";
$descr = snmp_get($device, $descr_oid, '-Oqv', 'SUPERMICRO-HEALTH-MIB');
$temperature = snmp_get($device, $temperature_oid, '-Oqv', 'SUPERMICRO-HEALTH-MIB');
$limit = snmp_get($device, $limit_oid, '-Oqv', 'SUPERMICRO-HEALTH-MIB');
$divisor = snmp_get($device, $divisor_oid, '-Oqv', 'SUPERMICRO-HEALTH-MIB') || 1;
$monitor = snmp_get($device, $monitor_oid, '-Oqv', 'SUPERMICRO-HEALTH-MIB');
if ($monitor == 'true') {
$descr = trim(str_ireplace('temperature', '', $descr));
discover_sensor($valid['sensor'], 'temperature', $device, $temperature_oid, trim($index, '.'), 'supermicro', $descr, (int) $divisor, '1', null, null, null, $limit, $temperature);
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class WikiClient(Client):
"""Wiki
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(WikiClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = 'bf7d82a0-8aa5-4613-94ef-6172a5ea01f3'
def create_attachment(self, upload_stream, project, wiki_identifier, name, version_descriptor=None, **kwargs):
"""CreateAttachment.
Creates an attachment in the wiki.
:param object upload_stream: Stream to upload
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str name: Wiki attachment name.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. (Optional in case of ProjectWiki).
:rtype: :class:`<WikiAttachmentResponse> <azure.devops.v5_1.wiki.models.WikiAttachmentResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if name is not None:
query_parameters['name'] = self._serialize.query('name', name, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
content = self._client.stream_upload(upload_stream, callback=callback)
response = self._send(http_method='PUT',
location_id='c4382d8d-fefc-40e0-92c5-49852e9e17c0',
version='5.1',
route_values=route_values,
query_parameters=query_parameters,
content=content,
media_type='application/octet-stream')
response_object = models.WikiAttachmentResponse()
response_object.attachment = self._deserialize('WikiAttachment', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def create_page_move(self, page_move_parameters, project, wiki_identifier, comment=None, version_descriptor=None):
"""CreatePageMove.
Creates a page move operation that updates the path and order of the page as provided in the parameters.
:param :class:`<WikiPageMoveParameters> <azure.devops.v5_1.wiki.models.WikiPageMoveParameters>` page_move_parameters: Page more operation parameters.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str comment: Comment that is to be associated with this page move.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. (Optional in case of ProjectWiki).
:rtype: :class:`<WikiPageMoveResponse> <azure.devops.v5_1.wiki.models.WikiPageMoveResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if comment is not None:
query_parameters['comment'] = self._serialize.query('comment', comment, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
content = self._serialize.body(page_move_parameters, 'WikiPageMoveParameters')
response = self._send(http_method='POST',
location_id='e37bbe71-cbae-49e5-9a4e-949143b9d910',
version='5.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
response_object = models.WikiPageMoveResponse()
response_object.page_move = self._deserialize('WikiPageMove', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def delete_page_by_id(self, project, wiki_identifier, id, comment=None):
"""DeletePageById.
[Preview API] Deletes a wiki page.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param int id: Wiki page id.
:param str comment: Comment to be associated with this page delete.
:rtype: :class:`<WikiPageResponse> <azure.devops.v5_1.wiki.models.WikiPageResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if comment is not None:
query_parameters['comment'] = self._serialize.query('comment', comment, 'str')
response = self._send(http_method='DELETE',
location_id='ceddcf75-1068-452d-8b13-2d4d76e1f970',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
response_object = models.WikiPageResponse()
response_object.page = self._deserialize('WikiPage', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def get_page_by_id(self, project, wiki_identifier, id, recursion_level=None, include_content=None):
"""GetPageById.
[Preview API] Gets metadata or content of the wiki page for the provided page id. Content negotiation is done based on the `Accept` header sent in the request.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param int id: Wiki page id.
:param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
:param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
:rtype: :class:`<WikiPageResponse> <azure.devops.v5_1.wiki.models.WikiPageResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ceddcf75-1068-452d-8b13-2d4d76e1f970',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
response_object = models.WikiPageResponse()
response_object.page = self._deserialize('WikiPage', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def get_page_by_id_text(self, project, wiki_identifier, id, recursion_level=None, include_content=None, **kwargs):
"""GetPageByIdText.
[Preview API] Gets metadata or content of the wiki page for the provided page id. Content negotiation is done based on the `Accept` header sent in the request.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param int id: Wiki page id.
:param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
:param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ceddcf75-1068-452d-8b13-2d4d76e1f970',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='text/plain')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_page_by_id_zip(self, project, wiki_identifier, id, recursion_level=None, include_content=None, **kwargs):
"""GetPageByIdZip.
[Preview API] Gets metadata or content of the wiki page for the provided page id. Content negotiation is done based on the `Accept` header sent in the request.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param int id: Wiki page id.
:param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
:param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='ceddcf75-1068-452d-8b13-2d4d76e1f970',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def update_page_by_id(self, parameters, project, wiki_identifier, id, version, comment=None):
"""UpdatePageById.
[Preview API] Edits a wiki page.
:param :class:`<WikiPageCreateOrUpdateParameters> <azure.devops.v5_1.wiki.models.WikiPageCreateOrUpdateParameters>` parameters: Wiki update operation parameters.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param int id: Wiki page id.
:param String version: Version of the page on which the change is to be made. Mandatory for `Edit` scenario. To be populated in the If-Match header of the request.
:param str comment: Comment to be associated with the page operation.
:rtype: :class:`<WikiPageResponse> <azure.devops.v5_1.wiki.models.WikiPageResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'int')
query_parameters = {}
if comment is not None:
query_parameters['comment'] = self._serialize.query('comment', comment, 'str')
additional_headers = {}
if version is not None:
additional_headers['If-Match'] = version
content = self._serialize.body(parameters, 'WikiPageCreateOrUpdateParameters')
response = self._send(http_method='PATCH',
location_id='ceddcf75-1068-452d-8b13-2d4d76e1f970',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers,
content=content)
response_object = models.WikiPageResponse()
response_object.page = self._deserialize('WikiPage', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def create_or_update_page(self, parameters, project, wiki_identifier, path, version, comment=None, version_descriptor=None):
"""CreateOrUpdatePage.
Creates or edits a wiki page.
:param :class:`<WikiPageCreateOrUpdateParameters> <azure.devops.v5_1.wiki.models.WikiPageCreateOrUpdateParameters>` parameters: Wiki create or update operation parameters.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str path: Wiki page path.
:param String version: Version of the page on which the change is to be made. Mandatory for `Edit` scenario. To be populated in the If-Match header of the request.
:param str comment: Comment to be associated with the page operation.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. (Optional in case of ProjectWiki).
:rtype: :class:`<WikiPageResponse> <azure.devops.v5_1.wiki.models.WikiPageResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if comment is not None:
query_parameters['comment'] = self._serialize.query('comment', comment, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
additional_headers = {}
if version is not None:
additional_headers['If-Match'] = version
content = self._serialize.body(parameters, 'WikiPageCreateOrUpdateParameters')
response = self._send(http_method='PUT',
location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
version='5.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers,
content=content)
response_object = models.WikiPageResponse()
response_object.page = self._deserialize('WikiPage', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def delete_page(self, project, wiki_identifier, path, comment=None, version_descriptor=None):
"""DeletePage.
Deletes a wiki page.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str path: Wiki page path.
:param str comment: Comment to be associated with this page delete.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. (Optional in case of ProjectWiki).
:rtype: :class:`<WikiPageResponse> <azure.devops.v5_1.wiki.models.WikiPageResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if comment is not None:
query_parameters['comment'] = self._serialize.query('comment', comment, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
response = self._send(http_method='DELETE',
location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
version='5.1',
route_values=route_values,
query_parameters=query_parameters)
response_object = models.WikiPageResponse()
response_object.page = self._deserialize('WikiPage', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def get_page(self, project, wiki_identifier, path=None, recursion_level=None, version_descriptor=None, include_content=None):
"""GetPage.
Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str path: Wiki page path.
:param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. Defaults to the default branch (Optional).
:param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
:rtype: :class:`<WikiPageResponse> <azure.devops.v5_1.wiki.models.WikiPageResponse>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
version='5.1',
route_values=route_values,
query_parameters=query_parameters)
response_object = models.WikiPageResponse()
response_object.page = self._deserialize('WikiPage', response)
response_object.eTag = response.headers.get('ETag')
return response_object
def get_page_text(self, project, wiki_identifier, path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs):
"""GetPageText.
Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str path: Wiki page path.
:param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. Defaults to the default branch (Optional).
:param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
version='5.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='text/plain')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_page_zip(self, project, wiki_identifier, path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs):
"""GetPageZip.
Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str path: Wiki page path.
:param str recursion_level: Recursion level for subpages retrieval. Defaults to `None` (Optional).
:param :class:`<GitVersionDescriptor> <azure.devops.v5_1.wiki.models.GitVersionDescriptor>` version_descriptor: GitVersionDescriptor for the page. Defaults to the default branch (Optional).
:param bool include_content: True to include the content of the page in the response for Json content type. Defaults to false (Optional)
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
response = self._send(http_method='GET',
location_id='25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b',
version='5.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def create_wiki(self, wiki_create_params, project=None):
"""CreateWiki.
Creates the wiki resource.
:param :class:`<WikiCreateParametersV2> <azure.devops.v5_1.wiki.models.WikiCreateParametersV2>` wiki_create_params: Parameters for the wiki creation.
:param str project: Project ID or project name
:rtype: :class:`<WikiV2> <azure.devops.v5_1.wiki.models.WikiV2>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(wiki_create_params, 'WikiCreateParametersV2')
response = self._send(http_method='POST',
location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
version='5.1',
route_values=route_values,
content=content)
return self._deserialize('WikiV2', response)
def delete_wiki(self, wiki_identifier, project=None):
"""DeleteWiki.
Deletes the wiki corresponding to the wiki name or Id provided.
:param str wiki_identifier: Wiki name or Id.
:param str project: Project ID or project name
:rtype: :class:`<WikiV2> <azure.devops.v5_1.wiki.models.WikiV2>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
response = self._send(http_method='DELETE',
location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
version='5.1',
route_values=route_values)
return self._deserialize('WikiV2', response)
def get_all_wikis(self, project=None):
"""GetAllWikis.
Gets all wikis in a project or collection.
:param str project: Project ID or project name
:rtype: [WikiV2]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
response = self._send(http_method='GET',
location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
version='5.1',
route_values=route_values)
return self._deserialize('[WikiV2]', self._unwrap_collection(response))
def get_wiki(self, wiki_identifier, project=None):
"""GetWiki.
Gets the wiki corresponding to the wiki name or Id provided.
:param str wiki_identifier: Wiki name or id.
:param str project: Project ID or project name
:rtype: :class:`<WikiV2> <azure.devops.v5_1.wiki.models.WikiV2>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
response = self._send(http_method='GET',
location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
version='5.1',
route_values=route_values)
return self._deserialize('WikiV2', response)
def update_wiki(self, update_parameters, wiki_identifier, project=None):
"""UpdateWiki.
Updates the wiki corresponding to the wiki Id or name provided using the update parameters.
:param :class:`<WikiUpdateParameters> <azure.devops.v5_1.wiki.models.WikiUpdateParameters>` update_parameters: Update parameters.
:param str wiki_identifier: Wiki name or Id.
:param str project: Project ID or project name
:rtype: :class:`<WikiV2> <azure.devops.v5_1.wiki.models.WikiV2>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if wiki_identifier is not None:
route_values['wikiIdentifier'] = self._serialize.url('wiki_identifier', wiki_identifier, 'str')
content = self._serialize.body(update_parameters, 'WikiUpdateParameters')
response = self._send(http_method='PATCH',
location_id='288d122c-dbd4-451d-aa5f-7dbbba070728',
version='5.1',
route_values=route_values,
content=content)
return self._deserialize('WikiV2', response)
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="../../../stylesheets/page.xsl"?>
<element extends="markup:xul:XULElement" name="popupset">
<abstract>
<locale>
A container for <link type="element" href="reference://markup/xul/menupopup">menupopup</link>, <link type="element" href="reference://markup/xul/panel">panel</link> and <link type="element" href="reference://markup/xul/tooltip">tooltip</link> elements.
</locale>
<locale xml:lang="ru">
Контейнер для элементов <link type="element" href="reference://markup/xul/menupopup">menupopup</link>, <link type="element" href="reference://markup/xul/panel">panel</link> и <link type="element" href="reference://markup/xul/tooltip">tooltip</link>.
Все всплывающие элементы должны быть объявлены в нем. Этот элемент не отображается.
</locale>
</abstract>
<remarks />
<examples />
<members>
<attributes />
<methods />
<properties />
<events />
</members>
</element>
|
{
"pile_set_name": "Github"
}
|
---
id: 56533eb9ac21ba0edf2244a8
title: Storing Values with the Assignment Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cEanysE'
forumTopicId: 18310
localeTitle: 使用赋值运算符存储值
---
## Description
<section id='description'>
在 JavaScript 中,你可以使用赋值运算符将值存储在变量中。
<code>myVariable = 5;</code>
这条语句把<code>Number</code>类型的值<code>5</code>赋给变量<code>myVariable</code>。
赋值过程是从右到左进行的。在将值分配给运算符左侧的变量之前,将解析<code>=</code>运算符右侧的所有内容。
```js
myVar = 5;
myNum = myVar;
```
数值<code>5</code>被赋给变量<code>myVar</code>中,然后再次将变量<code>myVar</code>解析为<code>5</code>并将其赋给<code>myNum</code>变量。
</section>
## Instructions
<section id='instructions'>
把数值<code>7</code>赋给变量 <code>a</code>。
把变量<code>a</code>中的内容赋给变量<code>b</code>。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 不要修改注释上方的代码。
testString: assert(/var a;/.test(code) && /var b = 2;/.test(code));
- text: <code>a</code>的值应该是 7。
testString: assert(typeof a === 'number' && a === 7);
- text: <code>b</code>的值应该是 7。
testString: assert(typeof b === 'number' && b === 7);
- text: 你需要用<code>=</code>把<code>a</code>的值赋给<code>b</code>。
testString: assert(/b\s*=\s*a\s*;/g.test(code));
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var a;
var b = 2;
// Only change code below this line
```
</div>
### Before Test
<div id='js-setup'>
```js
if (typeof a != 'undefined') {
a = undefined;
}
if (typeof b != 'undefined') {
b = undefined;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
(function(a,b){return "a = " + a + ", b = " + b;})(a,b);
```
</div>
</section>
## Solution
<section id='solution'>
```js
var a;
var b = 2;
a = 7;
b = a;
```
</section>
|
{
"pile_set_name": "Github"
}
|
package com.coderising.ood.srp;
import com.coderising.ood.srp.utils.DBUtil;
import com.coderising.ood.srp.utils.MailUtil;
import com.coderising.ood.srp.utils.ArgsUtil;
import java.io.IOException;
import java.util.*;
/**
* PromotionMail
*
* @author Chenpz
* @package com.coderising.ood.srp
* @date 2017/6/12/23:33
*/
public class PromotionMail {
private ProductInfo productInfo;
private List<MailInfo> mailInfoList = new ArrayList<>();
private static final String NAME_KEY = "NAME";
private static final String EMAIL_KEY = "EMAIL";
public PromotionMail(){}
public PromotionMail(ProductInfo productInfo) throws Exception {
this.productInfo = productInfo;
initMailInfoList(loadMailingList());
}
/**
* 获取每个型号的手机关注的人员信息列表
* @return
* @throws Exception
*/
private List<Map<String, String>> loadMailingList() throws Exception {
String sql = "select name from subscriptions "
+ "where product_id= '" + productInfo.getProductID() +"' "
+ "and send_mail=1 ";
return DBUtil.query(sql);
}
/**
* 组装促销邮件的内容信息
* @param mailingList
*/
private void initMailInfoList(List<Map<String, String>> mailingList) {
if (ArgsUtil.isNotEmpty(mailingList)){
for (Map<String, String> map : mailingList){
// 初始化 mailInfoList
mailInfoList.add(buildMailInfo(map));
}
}
}
/**
* 组装邮件内容信息
* @param userInfo
* @return
*/
private MailInfo buildMailInfo(Map<String, String> userInfo){
String name = userInfo.get(NAME_KEY);
String subject = "您关注的产品降价了";
String message = "尊敬的 "+name+", 您关注的产品 " + productInfo.getProductDesc() + " 降价了,欢迎购买!" ;
String toAddress = userInfo.get(EMAIL_KEY);
return new MailInfo(toAddress, subject, message);
}
/**
* 发送促销邮件
* @param debug
* @throws IOException
*/
public void sendEMails(boolean debug) throws IOException {
System.out.println("开始发送邮件... ...");
if (ArgsUtil.isNotEmpty(mailInfoList)) {
for (MailInfo mailInfo : mailInfoList){
MailUtil.sendEmail(mailInfo.toAddress, mailInfo.subject, mailInfo.message, debug);
}
}else {
System.out.println("没有邮件发送... ...");
}
}
class MailInfo{
private String toAddress = null;
private String subject = null;
private String message = null;
MailInfo(String toAddress, String subject, String message){
this.toAddress = toAddress;
this.subject = subject;
this.message = message;
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.demo.servlet.json;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.leshan.core.node.LwM2mMultipleResource;
import org.eclipse.leshan.core.node.LwM2mNode;
import org.eclipse.leshan.core.node.LwM2mObject;
import org.eclipse.leshan.core.node.LwM2mObjectInstance;
import org.eclipse.leshan.core.node.LwM2mResource;
import org.eclipse.leshan.core.node.LwM2mSingleResource;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
public class LwM2mNodeDeserializer implements JsonDeserializer<LwM2mNode> {
@Override
public LwM2mNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (json == null) {
return null;
}
LwM2mNode node;
if (json.isJsonObject()) {
JsonObject object = (JsonObject) json;
Integer id = null;
if (object.has("id")) {
id = object.get("id").getAsInt();
}
if (object.has("instances")) {
if (id == null) {
throw new JsonParseException("Missing id");
}
JsonArray array = object.get("instances").getAsJsonArray();
LwM2mObjectInstance[] instances = new LwM2mObjectInstance[array.size()];
for (int i = 0; i < array.size(); i++) {
instances[i] = context.deserialize(array.get(i), LwM2mNode.class);
}
node = new LwM2mObject(id, instances);
} else if (object.has("resources")) {
JsonArray array = object.get("resources").getAsJsonArray();
LwM2mResource[] resources = new LwM2mResource[array.size()];
for (int i = 0; i < array.size(); i++) {
resources[i] = context.deserialize(array.get(i), LwM2mNode.class);
}
if (id == null) {
node = new LwM2mObjectInstance(Arrays.asList(resources));
} else {
node = new LwM2mObjectInstance(id, resources);
}
} else if (object.has("value")) {
if (id == null) {
throw new JsonParseException("Missing id");
}
// single value resource
JsonPrimitive val = object.get("value").getAsJsonPrimitive();
org.eclipse.leshan.core.model.ResourceModel.Type expectedType = getTypeFor(val);
node = LwM2mSingleResource.newResource(id, deserializeValue(val, expectedType), expectedType);
} else if (object.has("values")) {
if (id == null) {
throw new JsonParseException("Missing id");
}
// multi-instances resource
Map<Integer, Object> values = new HashMap<>();
org.eclipse.leshan.core.model.ResourceModel.Type expectedType = null;
for (Entry<String, JsonElement> entry : object.get("values").getAsJsonObject().entrySet()) {
JsonPrimitive pval = entry.getValue().getAsJsonPrimitive();
expectedType = getTypeFor(pval);
values.put(Integer.valueOf(entry.getKey()), deserializeValue(pval, expectedType));
}
// use string by default;
if (expectedType == null)
expectedType = org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
node = LwM2mMultipleResource.newResource(id, values, expectedType);
} else {
throw new JsonParseException("Invalid node element");
}
} else {
throw new JsonParseException("Invalid node element");
}
return node;
}
private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
if (val.isBoolean())
return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
if (val.isString())
return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
if (val.isNumber()) {
if (val.getAsDouble() == val.getAsLong()) {
return org.eclipse.leshan.core.model.ResourceModel.Type.INTEGER;
} else {
return org.eclipse.leshan.core.model.ResourceModel.Type.FLOAT;
}
}
// use string as default value
return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
}
private Object deserializeValue(JsonPrimitive val, org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
switch (expectedType) {
case BOOLEAN:
return val.getAsBoolean();
case STRING:
return val.getAsString();
case INTEGER:
return val.getAsLong();
case FLOAT:
return val.getAsDouble();
case TIME:
case OPAQUE:
default:
// TODO we need to better handle this.
return val.getAsString();
}
}
}
|
{
"pile_set_name": "Github"
}
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""]
cc_library(
name = "discretized_path",
srcs = ["discretized_path.cc"],
hdrs = ["discretized_path.h"],
copts = PLANNING_COPTS,
deps = [
"//modules/common/math:linear_interpolation",
"//modules/common/proto:pnc_point_cc_proto",
],
)
cc_test(
name = "discretized_path_test",
size = "small",
srcs = ["discretized_path_test.cc"],
deps = [
":discretized_path",
"//modules/common/util",
"//modules/common/util:point_factory",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "frenet_frame_path",
srcs = ["frenet_frame_path.cc"],
hdrs = ["frenet_frame_path.h"],
copts = PLANNING_COPTS,
deps = [
"//modules/common/math:linear_interpolation",
"//modules/planning/proto:planning_cc_proto",
],
)
cc_test(
name = "frenet_frame_path_test",
size = "small",
srcs = ["frenet_frame_path_test.cc"],
deps = [
":frenet_frame_path",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "path_data",
srcs = ["path_data.cc"],
hdrs = ["path_data.h"],
copts = PLANNING_COPTS,
deps = [
":discretized_path",
":frenet_frame_path",
"//modules/common/math:cartesian_frenet_conversion",
"//modules/planning/common:planning_gflags",
"//modules/planning/reference_line",
],
)
cpplint()
|
{
"pile_set_name": "Github"
}
|
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" data-namespace-typo3-fluid="true">
<f:if condition="{hasAccess}">
<f:then>
<f:form action="" name="editForm" id="NewContentElementController">
<f:form.hidden name="defValues" value="" />
<f:if condition="{hasClickEvent}">
<f:then>
<script>
{onClickEvent -> f:format.raw()}
</script>
<f:render section="Filter" />
{renderedTabs -> f:format.raw()}
<f:render section="FilterNothingFound" />
</f:then>
<f:else>
<div id="new-content-element-wizard-carousel" class="carousel slide" data-ride="carousel" data-interval="false">
<div class="carousel-inner" role="listbox">
<div class="item active" data-slide="next">
<div class="t3-new-content-element-wizard-title">
<h2>{f:translate(key: 'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:1_selectType')}</h2>
</div>
<f:render section="Filter" />
{renderedTabs -> f:format.raw()}
<f:render section="FilterNothingFound" />
</div>
<div class="item">
<div class="t3-new-content-element-wizard-title">
<h2>{f:translate(key: 'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:2_selectPosition') -> f:format.htmlspecialchars()}</h2>
</div>
<div class="t3-new-content-element-wizard-body">
{posMap -> f:format.raw()}
</div>
</div>
</div>
</div>
</f:else>
</f:if>
</f:form>
</f:then>
<f:else>
<h1>{f:translate(key: 'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:newContentElement')}</h1>
</f:else>
</f:if>
<f:section name="Filter">
<br>
<div class="container-fluid">
<div class="navbar-header">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">{f:translate(key: 'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:newContentElement.filter.label')}</span>
<input type="search" autocomplete="off" class="form-control t3js-contentWizard-search" placeholder="{f:translate(key: 'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:newContentElement.filter.placeholder')}">
</div>
</div>
</div>
</div>
</f:section>
<f:section name="FilterNothingFound">
<div class="container-fluid">
<div class="alert alert-danger hidden t3js-filter-noresult" role="alert">
<f:translate key="LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:newContentElement.filter.noResults" />
</div>
</div>
</f:section>
</html>
|
{
"pile_set_name": "Github"
}
|
import torchfile
import numpy as np
model = torchfile.load('kit.model')
weights = dict()
params = ['weight', 'bias', 'running_mean', 'running_var']
recursive = ['conv_nets']
def save_weight(name, node, level):
weights[name] = dict()
current_layer = weights[name]
for p in params:
if hasattr(node, p):
func = getattr(node, p)
arr = np.array(func)
if arr.ndim >= 1:
current_layer[p] = arr
print (" " * level + "{}.{} shape {} {}".format(name, p, current_layer[p].shape, current_layer[p].dtype))
for p in recursive:
if hasattr(node, p):
func = getattr(node, p)
if func != None:
for idx, subnode in enumerate(func):
new_name = name + ":{}:{}".format(p, idx)
save_weight(new_name, subnode, level + 1)
for idx, data in enumerate(model.modules):
if data != None:
print ("Find layer #{} : {}".format(idx, data._typename))
if hasattr(data, 'search_flag'):
print (" name = {}".format(data.search_flag))
if data.modules != None:
print (" submodule = {}#".format(len(data.modules)))
for idx_j, sub in enumerate(data.modules):
print (" layer [{}]".format(sub._typename))
name = data.search_flag + ":" + str(idx_j)
save_weight(name, sub, 2)
print ("\n")
else:
pass
#print (dir(data))
print ("\n")
with open("stylebank.npy", 'wb') as of:
np.save(of, weights)
print ("-------------------------------------------------")
load_weight = np.load('stylebank.npy').item()
for i in load_weight:
#print (i)
for j in load_weight[i]:
pass
#print (" {} with shape {}".format(j, load_weight[i][j].shape))
|
{
"pile_set_name": "Github"
}
|
#include "sphereObj.h"
#include <math.h>
#include "hardware.h"
/***********************************************************
* Constructor *
***********************************************************/
Sphere::Sphere(int _numberLevels, float _radius)
{
this->numberLevels = _numberLevels;
this->numberTriangles = 20 * pow(4.0, (double) this->numberLevels);
// Create an array dynamically to store the triangles
this->arrayTriangles = new float*[(this->numberTriangles)];
for (int indexTriangle = 0; indexTriangle < this->numberTriangles; indexTriangle++)
{
this->arrayTriangles[indexTriangle] = new float[9];
}
this->initSphere(_radius);
}
/***********************************************************
* Destructor *
***********************************************************/
Sphere::~Sphere()
{
// Delete the dynamic array
for (int indexTriangle = 0; indexTriangle < this->numberTriangles; indexTriangle++)
{
delete[] this->arrayTriangles[indexTriangle];
}
delete[] (this->arrayTriangles);
}
/***********************************************************
* Accessors *
***********************************************************/
// +-------------------------------------------------------+
// | Get the number of triangles |
// +-------------------------------------------------------+
int Sphere::getNumberTriangles()
{
return (this->numberTriangles);
}
// +-------------------------------------------------------+
// | Get the number of levels |
// +-------------------------------------------------------+
int Sphere::getNumberLevels()
{
return (this->numberLevels);
}
// +-------------------------------------------------------+
// | Get the vertices of a given triangle |
// +-------------------------------------------------------+
void Sphere::getTriangleVertices(int _triangleIndex, float *_x1, float *_y1, float *_z1, float *_x2, float *_y2, float *_z2, float *_x3, float *_y3, float *_z3)
{
*_x1 = this->arrayTriangles[_triangleIndex][0];
*_y1 = this->arrayTriangles[_triangleIndex][1];
*_z1 = this->arrayTriangles[_triangleIndex][2];
*_x2 = this->arrayTriangles[_triangleIndex][3];
*_y2 = this->arrayTriangles[_triangleIndex][4];
*_z2 = this->arrayTriangles[_triangleIndex][5];
*_x3 = this->arrayTriangles[_triangleIndex][6];
*_y3 = this->arrayTriangles[_triangleIndex][7];
*_z3 = this->arrayTriangles[_triangleIndex][8];
}
// +-------------------------------------------------------+
// | Get the radius |
// +-------------------------------------------------------+
float Sphere::getRadius()
{
return (this->radius);
}
/***********************************************************
* Computations *
***********************************************************/
// +-------------------------------------------------------+
// | Initialization of the sphere |
// +-------------------------------------------------------+
void Sphere::initSphere(float _radius)
{
// Each triangle is represented by a row of 9 points:
//
// +----------+----------+----------+
// | x1 y1 z1 | x2 y2 z2 | x3 y3 z3 |
// +----------+----------+----------+
//
// Where each set (x,y,z) represents one end of the triangle:
//
/*
// o (x1,y1,z1)
// / \
// (x2,y2,z2) o---o (x3,y3,z3)
//
*/
// Define an array to store initial points for level 0
// Each point is represented by a row of 3 points:
//
// +---------+
// | x y z |
// +---------+
//
// Define the initial points for level 0
// There are 20 triangles, and thus 12 points
float level0Points[12][3];
// Define the step size when the array of triangles is being filled
// For instance, say there are 4 levels, and thus 5120 triangles
// For level 0, each triangle is spaced by 256 rows in the array
// New triangles are then generated for level 1, and each new triangle is
// then spaced by 64 rows
// New triangles are then generated for level 2, and each new triangle is
// then spaced by 16 rows
// New triangles are then generated for level 3, and each new triangle is
// then spaced by 4 rows
// New triangles are then generated for level 4, and there is no more space
// between triangles since the array is now full
unsigned int stepSize;
/*
// When the array of triangles is being filled, use the following variables
// to generate new triangles:
//
// o Point 1
// /A\
// Point 12--> x---x <--Point 13
// /B\C/D\
// Point 2 o---x---o Point 3
// ^
// |
// Point 23
//
*/
float point1[3];
float point2[3];
float point3[3];
float point12[3];
float point23[3];
float point13[3];
float mag12;
float mag23;
float mag13;
unsigned int indexTriangleA;
unsigned int indexTriangleB;
unsigned int indexTriangleC;
unsigned int indexTriangleD;
// Define variable to store parameters to generate the triangles
float sint;
float cost;
// *************************************************************************
// * STEP 0: Compute parameters *
// *************************************************************************
// Define variable to store parameters to generate the triangles
sint = 0.4472136;
cost = 0.8944272;
// Update the radius and center of the sphere
this->radius = _radius;
// *************************************************************************
// * STEP 1: Generate the 12 points and 20 triangles for level 0 *
// *************************************************************************
// Point at the top of the sphere
level0Points[0][0] = 0;
level0Points[0][1] = 0;
level0Points[0][2] = 1;
// Point at the bottom of the sphere
level0Points[11][0] = 0;
level0Points[11][1] = 0;
level0Points[11][2] = -1;
// Now create two circles on each hemisphere that will be divided in 5
// points
// Circle on top hemisphere
level0Points[1][0] = cost * sin(2 * M_PI * 0 / 5);
level0Points[1][1] = cost * cos(2 * M_PI * 0 / 5);
level0Points[1][2] = sint;
level0Points[2][0] = cost * sin(2 * M_PI * 1 / 5);
level0Points[2][1] = cost * cos(2 * M_PI * 1 / 5);
level0Points[2][2] = sint;
level0Points[3][0] = cost * sin(2 * M_PI * 2 / 5);
level0Points[3][1] = cost * cos(2 * M_PI * 2 / 5);
level0Points[3][2] = sint;
level0Points[4][0] = cost * sin(2 * M_PI * 3 / 5);
level0Points[4][1] = cost * cos(2 * M_PI * 3 / 5);
level0Points[4][2] = sint;
level0Points[5][0] = cost * sin(2 * M_PI * 4 / 5);
level0Points[5][1] = cost * cos(2 * M_PI * 4 / 5);
level0Points[5][2] = sint;
// Circle on bottom hemisphere
level0Points[6][0] = -cost * sin(2 * M_PI * 0 / 5);
level0Points[6][1] = -cost * cos(2 * M_PI * 0 / 5);
level0Points[6][2] = -sint;
level0Points[7][0] = -cost * sin(2 * M_PI * 1 / 5);
level0Points[7][1] = -cost * cos(2 * M_PI * 1 / 5);
level0Points[7][2] = -sint;
level0Points[8][0] = -cost * sin(2 * M_PI * 2 / 5);
level0Points[8][1] = -cost * cos(2 * M_PI * 2 / 5);
level0Points[8][2] = -sint;
level0Points[9][0] = -cost * sin(2 * M_PI * 3 / 5);
level0Points[9][1] = -cost * cos(2 * M_PI * 3 / 5);
level0Points[9][2] = -sint;
level0Points[10][0] = -cost * sin(2 * M_PI * 4 / 5);
level0Points[10][1] = -cost * cos(2 * M_PI * 4 / 5);
level0Points[10][2] = -sint;
// Scale and translate the points according to radius and center
for (int indexPoint = 0; indexPoint < 12; indexPoint++)
{
level0Points[indexPoint][0] = level0Points[indexPoint][0] * this->radius;
level0Points[indexPoint][1] = level0Points[indexPoint][1] * this->radius;
level0Points[indexPoint][2] = level0Points[indexPoint][2] * this->radius;
}
// Use these points to define the 20 triangles for level 0
// Make sure points are attributed to a triangle in
// COUNTERCLOCKWISE direction. This is important for later
// as openGL renders triangle with this orientation.
// First define the step size to fill the array
stepSize = this->numberTriangles / 20;
// Fill the array
// Triangle: 0-2-1
this->arrayTriangles[0*stepSize][0] = level0Points[0][0];
this->arrayTriangles[0*stepSize][1] = level0Points[0][1];
this->arrayTriangles[0*stepSize][2] = level0Points[0][2];
this->arrayTriangles[0*stepSize][3] = level0Points[2][0];
this->arrayTriangles[0*stepSize][4] = level0Points[2][1];
this->arrayTriangles[0*stepSize][5] = level0Points[2][2];
this->arrayTriangles[0*stepSize][6] = level0Points[1][0];
this->arrayTriangles[0*stepSize][7] = level0Points[1][1];
this->arrayTriangles[0*stepSize][8] = level0Points[1][2];
// Triangle: 0-3-2
this->arrayTriangles[1*stepSize][0] = level0Points[0][0];
this->arrayTriangles[1*stepSize][1] = level0Points[0][1];
this->arrayTriangles[1*stepSize][2] = level0Points[0][2];
this->arrayTriangles[1*stepSize][3] = level0Points[3][0];
this->arrayTriangles[1*stepSize][4] = level0Points[3][1];
this->arrayTriangles[1*stepSize][5] = level0Points[3][2];
this->arrayTriangles[1*stepSize][6] = level0Points[2][0];
this->arrayTriangles[1*stepSize][7] = level0Points[2][1];
this->arrayTriangles[1*stepSize][8] = level0Points[2][2];
// Triangle: 0-4-3
this->arrayTriangles[2*stepSize][0] = level0Points[0][0];
this->arrayTriangles[2*stepSize][1] = level0Points[0][1];
this->arrayTriangles[2*stepSize][2] = level0Points[0][2];
this->arrayTriangles[2*stepSize][3] = level0Points[4][0];
this->arrayTriangles[2*stepSize][4] = level0Points[4][1];
this->arrayTriangles[2*stepSize][5] = level0Points[4][2];
this->arrayTriangles[2*stepSize][6] = level0Points[3][0];
this->arrayTriangles[2*stepSize][7] = level0Points[3][1];
this->arrayTriangles[2*stepSize][8] = level0Points[3][2];
// Triangle: 0-5-4
this->arrayTriangles[3*stepSize][0] = level0Points[0][0];
this->arrayTriangles[3*stepSize][1] = level0Points[0][1];
this->arrayTriangles[3*stepSize][2] = level0Points[0][2];
this->arrayTriangles[3*stepSize][3] = level0Points[5][0];
this->arrayTriangles[3*stepSize][4] = level0Points[5][1];
this->arrayTriangles[3*stepSize][5] = level0Points[5][2];
this->arrayTriangles[3*stepSize][6] = level0Points[4][0];
this->arrayTriangles[3*stepSize][7] = level0Points[4][1];
this->arrayTriangles[3*stepSize][8] = level0Points[4][2];
// Triangle: 0-1-5
this->arrayTriangles[4*stepSize][0] = level0Points[0][0];
this->arrayTriangles[4*stepSize][1] = level0Points[0][1];
this->arrayTriangles[4*stepSize][2] = level0Points[0][2];
this->arrayTriangles[4*stepSize][3] = level0Points[1][0];
this->arrayTriangles[4*stepSize][4] = level0Points[1][1];
this->arrayTriangles[4*stepSize][5] = level0Points[1][2];
this->arrayTriangles[4*stepSize][6] = level0Points[5][0];
this->arrayTriangles[4*stepSize][7] = level0Points[5][1];
this->arrayTriangles[4*stepSize][8] = level0Points[5][2];
// Triangle: 9-1-2
this->arrayTriangles[5*stepSize][0] = level0Points[9][0];
this->arrayTriangles[5*stepSize][1] = level0Points[9][1];
this->arrayTriangles[5*stepSize][2] = level0Points[9][2];
this->arrayTriangles[5*stepSize][3] = level0Points[1][0];
this->arrayTriangles[5*stepSize][4] = level0Points[1][1];
this->arrayTriangles[5*stepSize][5] = level0Points[1][2];
this->arrayTriangles[5*stepSize][6] = level0Points[2][0];
this->arrayTriangles[5*stepSize][7] = level0Points[2][1];
this->arrayTriangles[5*stepSize][8] = level0Points[2][2];
// Triangle: 10-2-3
this->arrayTriangles[6*stepSize][0] = level0Points[10][0];
this->arrayTriangles[6*stepSize][1] = level0Points[10][1];
this->arrayTriangles[6*stepSize][2] = level0Points[10][2];
this->arrayTriangles[6*stepSize][3] = level0Points[2][0];
this->arrayTriangles[6*stepSize][4] = level0Points[2][1];
this->arrayTriangles[6*stepSize][5] = level0Points[2][2];
this->arrayTriangles[6*stepSize][6] = level0Points[3][0];
this->arrayTriangles[6*stepSize][7] = level0Points[3][1];
this->arrayTriangles[6*stepSize][8] = level0Points[3][2];
// Triangle: 6-3-4
this->arrayTriangles[7*stepSize][0] = level0Points[6][0];
this->arrayTriangles[7*stepSize][1] = level0Points[6][1];
this->arrayTriangles[7*stepSize][2] = level0Points[6][2];
this->arrayTriangles[7*stepSize][3] = level0Points[3][0];
this->arrayTriangles[7*stepSize][4] = level0Points[3][1];
this->arrayTriangles[7*stepSize][5] = level0Points[3][2];
this->arrayTriangles[7*stepSize][6] = level0Points[4][0];
this->arrayTriangles[7*stepSize][7] = level0Points[4][1];
this->arrayTriangles[7*stepSize][8] = level0Points[4][2];
// Triangle: 7-4-5
this->arrayTriangles[8*stepSize][0] = level0Points[7][0];
this->arrayTriangles[8*stepSize][1] = level0Points[7][1];
this->arrayTriangles[8*stepSize][2] = level0Points[7][2];
this->arrayTriangles[8*stepSize][3] = level0Points[4][0];
this->arrayTriangles[8*stepSize][4] = level0Points[4][1];
this->arrayTriangles[8*stepSize][5] = level0Points[4][2];
this->arrayTriangles[8*stepSize][6] = level0Points[5][0];
this->arrayTriangles[8*stepSize][7] = level0Points[5][1];
this->arrayTriangles[8*stepSize][8] = level0Points[5][2];
// Triangle: 8-5-1
this->arrayTriangles[9*stepSize][0] = level0Points[8][0];
this->arrayTriangles[9*stepSize][1] = level0Points[8][1];
this->arrayTriangles[9*stepSize][2] = level0Points[8][2];
this->arrayTriangles[9*stepSize][3] = level0Points[5][0];
this->arrayTriangles[9*stepSize][4] = level0Points[5][1];
this->arrayTriangles[9*stepSize][5] = level0Points[5][2];
this->arrayTriangles[9*stepSize][6] = level0Points[1][0];
this->arrayTriangles[9*stepSize][7] = level0Points[1][1];
this->arrayTriangles[9*stepSize][8] = level0Points[1][2];
// Triangle: 4-7-6
this->arrayTriangles[10*stepSize][0] = level0Points[4][0];
this->arrayTriangles[10*stepSize][1] = level0Points[4][1];
this->arrayTriangles[10*stepSize][2] = level0Points[4][2];
this->arrayTriangles[10*stepSize][3] = level0Points[7][0];
this->arrayTriangles[10*stepSize][4] = level0Points[7][1];
this->arrayTriangles[10*stepSize][5] = level0Points[7][2];
this->arrayTriangles[10*stepSize][6] = level0Points[6][0];
this->arrayTriangles[10*stepSize][7] = level0Points[6][1];
this->arrayTriangles[10*stepSize][8] = level0Points[6][2];
// Triangle: 5-8-7
this->arrayTriangles[11*stepSize][0] = level0Points[5][0];
this->arrayTriangles[11*stepSize][1] = level0Points[5][1];
this->arrayTriangles[11*stepSize][2] = level0Points[5][2];
this->arrayTriangles[11*stepSize][3] = level0Points[8][0];
this->arrayTriangles[11*stepSize][4] = level0Points[8][1];
this->arrayTriangles[11*stepSize][5] = level0Points[8][2];
this->arrayTriangles[11*stepSize][6] = level0Points[7][0];
this->arrayTriangles[11*stepSize][7] = level0Points[7][1];
this->arrayTriangles[11*stepSize][8] = level0Points[7][2];
// Triangle: 1-9-8
this->arrayTriangles[12*stepSize][0] = level0Points[1][0];
this->arrayTriangles[12*stepSize][1] = level0Points[1][1];
this->arrayTriangles[12*stepSize][2] = level0Points[1][2];
this->arrayTriangles[12*stepSize][3] = level0Points[9][0];
this->arrayTriangles[12*stepSize][4] = level0Points[9][1];
this->arrayTriangles[12*stepSize][5] = level0Points[9][2];
this->arrayTriangles[12*stepSize][6] = level0Points[8][0];
this->arrayTriangles[12*stepSize][7] = level0Points[8][1];
this->arrayTriangles[12*stepSize][8] = level0Points[8][2];
// Triangle: 2-10-9
this->arrayTriangles[13*stepSize][0] = level0Points[2][0];
this->arrayTriangles[13*stepSize][1] = level0Points[2][1];
this->arrayTriangles[13*stepSize][2] = level0Points[2][2];
this->arrayTriangles[13*stepSize][3] = level0Points[10][0];
this->arrayTriangles[13*stepSize][4] = level0Points[10][1];
this->arrayTriangles[13*stepSize][5] = level0Points[10][2];
this->arrayTriangles[13*stepSize][6] = level0Points[9][0];
this->arrayTriangles[13*stepSize][7] = level0Points[9][1];
this->arrayTriangles[13*stepSize][8] = level0Points[9][2];
// Triangle: 3-6-10
this->arrayTriangles[14*stepSize][0] = level0Points[3][0];
this->arrayTriangles[14*stepSize][1] = level0Points[3][1];
this->arrayTriangles[14*stepSize][2] = level0Points[3][2];
this->arrayTriangles[14*stepSize][3] = level0Points[6][0];
this->arrayTriangles[14*stepSize][4] = level0Points[6][1];
this->arrayTriangles[14*stepSize][5] = level0Points[6][2];
this->arrayTriangles[14*stepSize][6] = level0Points[10][0];
this->arrayTriangles[14*stepSize][7] = level0Points[10][1];
this->arrayTriangles[14*stepSize][8] = level0Points[10][2];
// Triangle: 11-6-7
this->arrayTriangles[15*stepSize][0] = level0Points[11][0];
this->arrayTriangles[15*stepSize][1] = level0Points[11][1];
this->arrayTriangles[15*stepSize][2] = level0Points[11][2];
this->arrayTriangles[15*stepSize][3] = level0Points[6][0];
this->arrayTriangles[15*stepSize][4] = level0Points[6][1];
this->arrayTriangles[15*stepSize][5] = level0Points[6][2];
this->arrayTriangles[15*stepSize][6] = level0Points[7][0];
this->arrayTriangles[15*stepSize][7] = level0Points[7][1];
this->arrayTriangles[15*stepSize][8] = level0Points[7][2];
// Triangle: 11-7-8
this->arrayTriangles[16*stepSize][0] = level0Points[11][0];
this->arrayTriangles[16*stepSize][1] = level0Points[11][1];
this->arrayTriangles[16*stepSize][2] = level0Points[11][2];
this->arrayTriangles[16*stepSize][3] = level0Points[7][0];
this->arrayTriangles[16*stepSize][4] = level0Points[7][1];
this->arrayTriangles[16*stepSize][5] = level0Points[7][2];
this->arrayTriangles[16*stepSize][6] = level0Points[8][0];
this->arrayTriangles[16*stepSize][7] = level0Points[8][1];
this->arrayTriangles[16*stepSize][8] = level0Points[8][2];
// Triangle: 11-8-9
this->arrayTriangles[17*stepSize][0] = level0Points[11][0];
this->arrayTriangles[17*stepSize][1] = level0Points[11][1];
this->arrayTriangles[17*stepSize][2] = level0Points[11][2];
this->arrayTriangles[17*stepSize][3] = level0Points[8][0];
this->arrayTriangles[17*stepSize][4] = level0Points[8][1];
this->arrayTriangles[17*stepSize][5] = level0Points[8][2];
this->arrayTriangles[17*stepSize][6] = level0Points[9][0];
this->arrayTriangles[17*stepSize][7] = level0Points[9][1];
this->arrayTriangles[17*stepSize][8] = level0Points[9][2];
// Triangle: 11-9-10
this->arrayTriangles[18*stepSize][0] = level0Points[11][0];
this->arrayTriangles[18*stepSize][1] = level0Points[11][1];
this->arrayTriangles[18*stepSize][2] = level0Points[11][2];
this->arrayTriangles[18*stepSize][3] = level0Points[9][0];
this->arrayTriangles[18*stepSize][4] = level0Points[9][1];
this->arrayTriangles[18*stepSize][5] = level0Points[9][2];
this->arrayTriangles[18*stepSize][6] = level0Points[10][0];
this->arrayTriangles[18*stepSize][7] = level0Points[10][1];
this->arrayTriangles[18*stepSize][8] = level0Points[10][2];
// Triangle: 11-10-6
this->arrayTriangles[19*stepSize][0] = level0Points[11][0];
this->arrayTriangles[19*stepSize][1] = level0Points[11][1];
this->arrayTriangles[19*stepSize][2] = level0Points[11][2];
this->arrayTriangles[19*stepSize][3] = level0Points[10][0];
this->arrayTriangles[19*stepSize][4] = level0Points[10][1];
this->arrayTriangles[19*stepSize][5] = level0Points[10][2];
this->arrayTriangles[19*stepSize][6] = level0Points[6][0];
this->arrayTriangles[19*stepSize][7] = level0Points[6][1];
this->arrayTriangles[19*stepSize][8] = level0Points[6][2];
// *************************************************************************
// * STEP 2: Generate each subsequent level *
// *************************************************************************
// Loop for each level starting at 1
for (int indexLevel = 1; indexLevel <= this->numberLevels; indexLevel++)
{
// Loop for each row to be filled in the array
for (int indexRow = 0; indexRow < this->numberTriangles; indexRow += stepSize)
{
// Get the current triangle
point1[0] = this->arrayTriangles[indexRow][0];
point1[1] = this->arrayTriangles[indexRow][1];
point1[2] = this->arrayTriangles[indexRow][2];
point2[0] = this->arrayTriangles[indexRow][3];
point2[1] = this->arrayTriangles[indexRow][4];
point2[2] = this->arrayTriangles[indexRow][5];
point3[0] = this->arrayTriangles[indexRow][6];
point3[1] = this->arrayTriangles[indexRow][7];
point3[2] = this->arrayTriangles[indexRow][8];
// Find the point that would lie on the sphere between points 1 & 2
point12[0] = point1[0] + point2[0];
point12[1] = point1[1] + point2[1];
point12[2] = point1[2] + point2[2];
mag12 = sqrt(point12[0] * point12[0] + point12[1] * point12[1] + point12[2] * point12[2]);
point12[0] /= mag12;
point12[1] /= mag12;
point12[2] /= mag12;
point12[0] *= this->radius;
point12[1] *= this->radius;
point12[2] *= this->radius;
// Find the point that would lie on the sphere between points 2 & 3
point23[0] = point2[0] + point3[0];
point23[1] = point2[1] + point3[1];
point23[2] = point2[2] + point3[2];
mag23 = sqrt(point23[0] * point23[0] + point23[1] * point23[1] + point23[2] * point23[2]);
point23[0] /= mag23;
point23[1] /= mag23;
point23[2] /= mag23;
point23[0] *= this->radius;
point23[1] *= this->radius;
point23[2] *= this->radius;
// Find the point that would lie on the sphere between points 1 & 3
point13[0] = point1[0] + point3[0];
point13[1] = point1[1] + point3[1];
point13[2] = point1[2] + point3[2];
mag13 = sqrt(point13[0] * point13[0] + point13[1] * point13[1] + point13[2] * point13[2]);
point13[0] /= mag13;
point13[1] /= mag13;
point13[2] /= mag13;
point13[0] *= this->radius;
point13[1] *= this->radius;
point13[2] *= this->radius;
// Create new triangles index in the array
// Note that the big triangle that is splitted in four triangles will
// be replaced in the list by triangle A
indexTriangleA = indexRow + 0 * stepSize / 4;
indexTriangleB = indexRow + 1 * stepSize / 4;
indexTriangleC = indexRow + 2 * stepSize / 4;
indexTriangleD = indexRow + 3 * stepSize / 4;
// Copy the new values of triangle A: 1-12-13
this->arrayTriangles[indexTriangleA][0] = point1[0];
this->arrayTriangles[indexTriangleA][1] = point1[1];
this->arrayTriangles[indexTriangleA][2] = point1[2];
this->arrayTriangles[indexTriangleA][3] = point12[0];
this->arrayTriangles[indexTriangleA][4] = point12[1];
this->arrayTriangles[indexTriangleA][5] = point12[2];
this->arrayTriangles[indexTriangleA][6] = point13[0];
this->arrayTriangles[indexTriangleA][7] = point13[1];
this->arrayTriangles[indexTriangleA][8] = point13[2];
// Copy the new values of triangle B: 12-2-23
this->arrayTriangles[indexTriangleB][0] = point12[0];
this->arrayTriangles[indexTriangleB][1] = point12[1];
this->arrayTriangles[indexTriangleB][2] = point12[2];
this->arrayTriangles[indexTriangleB][3] = point2[0];
this->arrayTriangles[indexTriangleB][4] = point2[1];
this->arrayTriangles[indexTriangleB][5] = point2[2];
this->arrayTriangles[indexTriangleB][6] = point23[0];
this->arrayTriangles[indexTriangleB][7] = point23[1];
this->arrayTriangles[indexTriangleB][8] = point23[2];
// Copy the new values of triangle C: 12-23-13
this->arrayTriangles[indexTriangleC][0] = point12[0];
this->arrayTriangles[indexTriangleC][1] = point12[1];
this->arrayTriangles[indexTriangleC][2] = point12[2];
this->arrayTriangles[indexTriangleC][3] = point23[0];
this->arrayTriangles[indexTriangleC][4] = point23[1];
this->arrayTriangles[indexTriangleC][5] = point23[2];
this->arrayTriangles[indexTriangleC][6] = point13[0];
this->arrayTriangles[indexTriangleC][7] = point13[1];
this->arrayTriangles[indexTriangleC][8] = point13[2];
// Copy the new values of triangle D: 13-23-3
this->arrayTriangles[indexTriangleD][0] = point13[0];
this->arrayTriangles[indexTriangleD][1] = point13[1];
this->arrayTriangles[indexTriangleD][2] = point13[2];
this->arrayTriangles[indexTriangleD][3] = point23[0];
this->arrayTriangles[indexTriangleD][4] = point23[1];
this->arrayTriangles[indexTriangleD][5] = point23[2];
this->arrayTriangles[indexTriangleD][6] = point3[0];
this->arrayTriangles[indexTriangleD][7] = point3[1];
this->arrayTriangles[indexTriangleD][8] = point3[2];
}
// Divide the step size by four for the next level
stepSize /= 4;
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.omg.org/bpmn20" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:bpsim="http://www.bpsim.org/schemas/1.0" xmlns:color="http://www.omg.org/spec/BPMN/non-normative/color" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:drools="http://www.jboss.org/drools" id="_ohTNYAL6EeWCZM-6YanbhA" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd http://www.jboss.org/drools drools.xsd http://www.bpsim.org/schemas/1.0 bpsim.xsd" exporter="jBPM Designer" exporterVersion="6.2.0" expressionLanguage="http://www.mvel.org/2.0" targetNamespace="http://www.omg.org/bpmn20" typeLanguage="http://www.java.com/javaTypes">
<bpmn2:itemDefinition id="_inputItem" structureRef="String"/>
<bpmn2:itemDefinition id="_outputItem" structureRef="String"/>
<bpmn2:signal id="mysignal" name="mysignal"/>
<bpmn2:itemDefinition id="__3AE815AE-58FD-4153-A4FF-42E42AF7450E_GroupIdInputXItem" structureRef="Object"/>
<bpmn2:itemDefinition id="__3AE815AE-58FD-4153-A4FF-42E42AF7450E_SkippableInputXItem" structureRef="Object"/>
<bpmn2:itemDefinition id="__3AE815AE-58FD-4153-A4FF-42E42AF7450E__outputOutputXItem" structureRef="String"/>
<bpmn2:process id="intermediate-event-scope" drools:packageName="org.jbpm" drools:version="1.0" name="intermediate-event-scope" isExecutable="true">
<bpmn2:property id="input" itemSubjectRef="_inputItem"/>
<bpmn2:property id="output" itemSubjectRef="_outputItem"/>
<bpmn2:startEvent id="processStartEvent" drools:selectable="true" color:background-color="#9acd32" color:border-color="#000000" color:color="#000000" name="">
<bpmn2:outgoing>_6EDA23B0-6967-43C5-BC39-993E4901209E</bpmn2:outgoing>
</bpmn2:startEvent>
<bpmn2:scriptTask id="_CF106EAF-DE5A-4599-BB6F-13B0C70058F5" drools:selectable="true" color:background-color="#fafad2" color:border-color="#000000" color:color="#000000" name="Start" scriptFormat="http://www.java.com/java">
<bpmn2:incoming>_6EDA23B0-6967-43C5-BC39-993E4901209E</bpmn2:incoming>
<bpmn2:outgoing>_A230FE7C-6E68-4699-9649-3CB5A11FE633</bpmn2:outgoing>
<bpmn2:script><![CDATA[System.out.println("Start");]]></bpmn2:script>
</bpmn2:scriptTask>
<bpmn2:sequenceFlow id="_6EDA23B0-6967-43C5-BC39-993E4901209E" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="processStartEvent" targetRef="_CF106EAF-DE5A-4599-BB6F-13B0C70058F5"/>
<bpmn2:sequenceFlow id="_A230FE7C-6E68-4699-9649-3CB5A11FE633" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_CF106EAF-DE5A-4599-BB6F-13B0C70058F5" targetRef="_CD09BB28-8780-4E76-ADCD-FB42F45C2C94"/>
<bpmn2:parallelGateway id="_CD09BB28-8780-4E76-ADCD-FB42F45C2C94" drools:selectable="true" color:background-color="#f0e68c" color:border-color="#a67f00" color:color="#000000" name="" gatewayDirection="Diverging">
<bpmn2:incoming>_A230FE7C-6E68-4699-9649-3CB5A11FE633</bpmn2:incoming>
<bpmn2:outgoing>_0DED70DB-AA1A-4BE6-B25D-D415AFFB8FE4</bpmn2:outgoing>
<bpmn2:outgoing>_FC65D278-C001-494C-BF47-15EB14E981C3</bpmn2:outgoing>
</bpmn2:parallelGateway>
<bpmn2:userTask id="_3AE815AE-58FD-4153-A4FF-42E42AF7450E" drools:selectable="true" drools:scriptFormat="http://www.java.com/java" color:background-color="#fafad2" color:border-color="#000000" color:color="#000000" name="Complete work">
<bpmn2:incoming>_0DED70DB-AA1A-4BE6-B25D-D415AFFB8FE4</bpmn2:incoming>
<bpmn2:outgoing>_49C18474-CC32-4B7B-B492-C3B7D22AABF1</bpmn2:outgoing>
<bpmn2:ioSpecification id="_ohTNYQL6EeWCZM-6YanbhA">
<bpmn2:dataInput id="_3AE815AE-58FD-4153-A4FF-42E42AF7450E_GroupIdInputX" drools:dtype="Object" itemSubjectRef="__3AE815AE-58FD-4153-A4FF-42E42AF7450E_GroupIdInputXItem" name="GroupId"/>
<bpmn2:dataInput id="_3AE815AE-58FD-4153-A4FF-42E42AF7450E_SkippableInputX" drools:dtype="Object" itemSubjectRef="__3AE815AE-58FD-4153-A4FF-42E42AF7450E_SkippableInputXItem" name="Skippable"/>
<bpmn2:dataOutput id="_3AE815AE-58FD-4153-A4FF-42E42AF7450E__outputOutputX" drools:dtype="String" itemSubjectRef="__3AE815AE-58FD-4153-A4FF-42E42AF7450E__outputOutputXItem" name="_output"/>
<bpmn2:inputSet id="_ohTNYgL6EeWCZM-6YanbhA">
<bpmn2:dataInputRefs>_3AE815AE-58FD-4153-A4FF-42E42AF7450E_GroupIdInputX</bpmn2:dataInputRefs>
<bpmn2:dataInputRefs>_3AE815AE-58FD-4153-A4FF-42E42AF7450E_SkippableInputX</bpmn2:dataInputRefs>
</bpmn2:inputSet>
<bpmn2:outputSet id="_ohT0cAL6EeWCZM-6YanbhA">
<bpmn2:dataOutputRefs>_3AE815AE-58FD-4153-A4FF-42E42AF7450E__outputOutputX</bpmn2:dataOutputRefs>
</bpmn2:outputSet>
</bpmn2:ioSpecification>
<bpmn2:dataInputAssociation id="_ohT0cQL6EeWCZM-6YanbhA">
<bpmn2:targetRef>_3AE815AE-58FD-4153-A4FF-42E42AF7450E_GroupIdInputX</bpmn2:targetRef>
<bpmn2:assignment id="_ohT0cgL6EeWCZM-6YanbhA">
<bpmn2:from xsi:type="bpmn2:tFormalExpression" id="_ohT0cwL6EeWCZM-6YanbhA"><![CDATA[HR]]></bpmn2:from>
<bpmn2:to xsi:type="bpmn2:tFormalExpression" id="_ohT0dAL6EeWCZM-6YanbhA">_3AE815AE-58FD-4153-A4FF-42E42AF7450E_GroupIdInputX</bpmn2:to>
</bpmn2:assignment>
</bpmn2:dataInputAssociation>
<bpmn2:dataInputAssociation id="_ohT0dQL6EeWCZM-6YanbhA">
<bpmn2:targetRef>_3AE815AE-58FD-4153-A4FF-42E42AF7450E_SkippableInputX</bpmn2:targetRef>
<bpmn2:assignment id="_ohT0dgL6EeWCZM-6YanbhA">
<bpmn2:from xsi:type="bpmn2:tFormalExpression" id="_ohT0dwL6EeWCZM-6YanbhA">true</bpmn2:from>
<bpmn2:to xsi:type="bpmn2:tFormalExpression" id="_ohT0eAL6EeWCZM-6YanbhA">_3AE815AE-58FD-4153-A4FF-42E42AF7450E_SkippableInputX</bpmn2:to>
</bpmn2:assignment>
</bpmn2:dataInputAssociation>
<bpmn2:dataOutputAssociation id="_ohT0eQL6EeWCZM-6YanbhA">
<bpmn2:sourceRef>_3AE815AE-58FD-4153-A4FF-42E42AF7450E__outputOutputX</bpmn2:sourceRef>
<bpmn2:targetRef>output</bpmn2:targetRef>
</bpmn2:dataOutputAssociation>
</bpmn2:userTask>
<bpmn2:sequenceFlow id="_0DED70DB-AA1A-4BE6-B25D-D415AFFB8FE4" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_CD09BB28-8780-4E76-ADCD-FB42F45C2C94" targetRef="_3AE815AE-58FD-4153-A4FF-42E42AF7450E"/>
<bpmn2:intermediateCatchEvent id="_527AF0A7-D741-4062-9953-A05E51479C80" drools:selectable="true" drools:boundaryca="" color:background-color="#f5deb3" color:border-color="#a0522d" color:color="#000000" name="Wait">
<bpmn2:incoming>_FC65D278-C001-494C-BF47-15EB14E981C3</bpmn2:incoming>
<bpmn2:outgoing>_A9188FF9-49B0-44A3-9FCF-A87F0CD21D06</bpmn2:outgoing>
<bpmn2:dataOutput id="_527AF0A7-D741-4062-9953-A05E51479C80_data" name="data"/>
<bpmn2:dataOutputAssociation id="_ohT0ewL6EeWCZM-6YanbhA">
<bpmn2:sourceRef>_527AF0A7-D741-4062-9953-A05E51479C80_data</bpmn2:sourceRef>
<bpmn2:targetRef>input</bpmn2:targetRef>
</bpmn2:dataOutputAssociation>
<bpmn2:outputSet id="_ohT0egL6EeWCZM-6YanbhA">
<bpmn2:dataOutputRefs>_527AF0A7-D741-4062-9953-A05E51479C80_data</bpmn2:dataOutputRefs>
</bpmn2:outputSet>
<bpmn2:signalEventDefinition id="_ohT0fAL6EeWCZM-6YanbhA" signalRef="mysignal"/>
</bpmn2:intermediateCatchEvent>
<bpmn2:sequenceFlow id="_FC65D278-C001-494C-BF47-15EB14E981C3" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_CD09BB28-8780-4E76-ADCD-FB42F45C2C94" targetRef="_527AF0A7-D741-4062-9953-A05E51479C80"/>
<bpmn2:intermediateThrowEvent id="_F07DFF08-E72B-4694-A24A-807A69F13615" drools:selectable="true" color:background-color="#8cabff" color:border-color="#008cec" color:color="#000000" name="">
<bpmn2:extensionElements>
<drools:metaData name="customScope">
<drools:metaValue>processInstance</drools:metaValue>
</drools:metaData>
</bpmn2:extensionElements>
<bpmn2:incoming>_49C18474-CC32-4B7B-B492-C3B7D22AABF1</bpmn2:incoming>
<bpmn2:outgoing>_7187346B-B1AE-441E-9A83-A580A567A1F8</bpmn2:outgoing>
<bpmn2:dataInput id="_F07DFF08-E72B-4694-A24A-807A69F13615_dataInputX" drools:dtype="Object" name="data"/>
<bpmn2:dataInputAssociation id="_ohT0fgL6EeWCZM-6YanbhA">
<bpmn2:sourceRef>output</bpmn2:sourceRef>
<bpmn2:targetRef>_F07DFF08-E72B-4694-A24A-807A69F13615_dataInputX</bpmn2:targetRef>
</bpmn2:dataInputAssociation>
<bpmn2:inputSet id="_ohT0fQL6EeWCZM-6YanbhA">
<bpmn2:dataInputRefs>_F07DFF08-E72B-4694-A24A-807A69F13615_dataInputX</bpmn2:dataInputRefs>
</bpmn2:inputSet>
<bpmn2:signalEventDefinition id="_ohT0fwL6EeWCZM-6YanbhA" signalRef="mysignal"/>
</bpmn2:intermediateThrowEvent>
<bpmn2:sequenceFlow id="_49C18474-CC32-4B7B-B492-C3B7D22AABF1" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_3AE815AE-58FD-4153-A4FF-42E42AF7450E" targetRef="_F07DFF08-E72B-4694-A24A-807A69F13615"/>
<bpmn2:sequenceFlow id="_7187346B-B1AE-441E-9A83-A580A567A1F8" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_F07DFF08-E72B-4694-A24A-807A69F13615" targetRef="_A785EEED-1811-468A-AB23-39B55C4C968E"/>
<bpmn2:parallelGateway id="_A785EEED-1811-468A-AB23-39B55C4C968E" drools:selectable="true" color:background-color="#f0e68c" color:border-color="#a67f00" color:color="#000000" name="" gatewayDirection="Converging">
<bpmn2:incoming>_7187346B-B1AE-441E-9A83-A580A567A1F8</bpmn2:incoming>
<bpmn2:incoming>_A9188FF9-49B0-44A3-9FCF-A87F0CD21D06</bpmn2:incoming>
<bpmn2:outgoing>_092A9828-6B85-4F6D-8C82-4ECF5711F719</bpmn2:outgoing>
</bpmn2:parallelGateway>
<bpmn2:sequenceFlow id="_A9188FF9-49B0-44A3-9FCF-A87F0CD21D06" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_527AF0A7-D741-4062-9953-A05E51479C80" targetRef="_A785EEED-1811-468A-AB23-39B55C4C968E"/>
<bpmn2:scriptTask id="_D2FDE2EF-B321-44BB-BF5E-88F1B1D5616E" drools:selectable="true" color:background-color="#fafad2" color:border-color="#000000" color:color="#000000" name="End" scriptFormat="http://www.java.com/java">
<bpmn2:incoming>_092A9828-6B85-4F6D-8C82-4ECF5711F719</bpmn2:incoming>
<bpmn2:outgoing>_6AFB1186-0007-4F59-BE88-770D9A0A0EA8</bpmn2:outgoing>
<bpmn2:script><![CDATA[System.out.println("End");
System.out.println("Input: " + input);
System.out.println("Output: " + output);]]></bpmn2:script>
</bpmn2:scriptTask>
<bpmn2:sequenceFlow id="_092A9828-6B85-4F6D-8C82-4ECF5711F719" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_A785EEED-1811-468A-AB23-39B55C4C968E" targetRef="_D2FDE2EF-B321-44BB-BF5E-88F1B1D5616E"/>
<bpmn2:endEvent id="_4025475D-512E-4AD1-8210-2A6FCA2F09AC" drools:selectable="true" color:background-color="#ff6347" color:border-color="#000000" color:color="#000000" name="">
<bpmn2:incoming>_6AFB1186-0007-4F59-BE88-770D9A0A0EA8</bpmn2:incoming>
</bpmn2:endEvent>
<bpmn2:sequenceFlow id="_6AFB1186-0007-4F59-BE88-770D9A0A0EA8" drools:selectable="true" color:background-color="#000000" color:border-color="#000000" color:color="#000000" sourceRef="_D2FDE2EF-B321-44BB-BF5E-88F1B1D5616E" targetRef="_4025475D-512E-4AD1-8210-2A6FCA2F09AC"/>
</bpmn2:process>
<bpmndi:BPMNDiagram id="_ohT0gAL6EeWCZM-6YanbhA">
<bpmndi:BPMNPlane id="_ohT0gQL6EeWCZM-6YanbhA" bpmnElement="intermediate-event-scope">
<bpmndi:BPMNShape id="_ohT0ggL6EeWCZM-6YanbhA" bpmnElement="processStartEvent">
<dc:Bounds height="30.0" width="30.0" x="120.0" y="165.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="_ohT0gwL6EeWCZM-6YanbhA" bpmnElement="_CF106EAF-DE5A-4599-BB6F-13B0C70058F5">
<dc:Bounds height="80.0" width="100.0" x="195.0" y="140.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohT0hAL6EeWCZM-6YanbhA" bpmnElement="_6EDA23B0-6967-43C5-BC39-993E4901209E">
<di:waypoint xsi:type="dc:Point" x="135.0" y="180.0"/>
<di:waypoint xsi:type="dc:Point" x="245.0" y="180.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="_ohT0hQL6EeWCZM-6YanbhA" bpmnElement="_A230FE7C-6E68-4699-9649-3CB5A11FE633">
<di:waypoint xsi:type="dc:Point" x="245.0" y="180.0"/>
<di:waypoint xsi:type="dc:Point" x="360.0" y="180.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="_ohT0hgL6EeWCZM-6YanbhA" bpmnElement="_CD09BB28-8780-4E76-ADCD-FB42F45C2C94">
<dc:Bounds height="40.0" width="40.0" x="340.0" y="160.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="_ohT0hwL6EeWCZM-6YanbhA" bpmnElement="_3AE815AE-58FD-4153-A4FF-42E42AF7450E">
<dc:Bounds height="80.0" width="100.0" x="425.0" y="240.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohT0iAL6EeWCZM-6YanbhA" bpmnElement="_0DED70DB-AA1A-4BE6-B25D-D415AFFB8FE4">
<di:waypoint xsi:type="dc:Point" x="360.0" y="180.0"/>
<di:waypoint xsi:type="dc:Point" x="360.0" y="280.0"/>
<di:waypoint xsi:type="dc:Point" x="475.0" y="280.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="_ohUbgAL6EeWCZM-6YanbhA" bpmnElement="_527AF0A7-D741-4062-9953-A05E51479C80">
<dc:Bounds height="30.0" width="30.0" x="457.0" y="79.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohUbgQL6EeWCZM-6YanbhA" bpmnElement="_FC65D278-C001-494C-BF47-15EB14E981C3">
<di:waypoint xsi:type="dc:Point" x="360.0" y="180.0"/>
<di:waypoint xsi:type="dc:Point" x="360.0" y="94.0"/>
<di:waypoint xsi:type="dc:Point" x="472.0" y="94.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="_ohUbggL6EeWCZM-6YanbhA" bpmnElement="_F07DFF08-E72B-4694-A24A-807A69F13615">
<dc:Bounds height="30.0" width="30.0" x="592.0" y="265.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohUbgwL6EeWCZM-6YanbhA" bpmnElement="_49C18474-CC32-4B7B-B492-C3B7D22AABF1">
<di:waypoint xsi:type="dc:Point" x="475.0" y="280.0"/>
<di:waypoint xsi:type="dc:Point" x="607.0" y="280.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="_ohUbhAL6EeWCZM-6YanbhA" bpmnElement="_7187346B-B1AE-441E-9A83-A580A567A1F8">
<di:waypoint xsi:type="dc:Point" x="607.0" y="280.0"/>
<di:waypoint xsi:type="dc:Point" x="650.0" y="280.0"/>
<di:waypoint xsi:type="dc:Point" x="650.0" y="180.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="_ohUbhQL6EeWCZM-6YanbhA" bpmnElement="_A785EEED-1811-468A-AB23-39B55C4C968E">
<dc:Bounds height="40.0" width="40.0" x="630.0" y="160.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohUbhgL6EeWCZM-6YanbhA" bpmnElement="_A9188FF9-49B0-44A3-9FCF-A87F0CD21D06">
<di:waypoint xsi:type="dc:Point" x="472.0" y="94.0"/>
<di:waypoint xsi:type="dc:Point" x="650.0" y="94.0"/>
<di:waypoint xsi:type="dc:Point" x="650.0" y="180.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="_ohUbhwL6EeWCZM-6YanbhA" bpmnElement="_D2FDE2EF-B321-44BB-BF5E-88F1B1D5616E">
<dc:Bounds height="80.0" width="100.0" x="705.0" y="140.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohUbiAL6EeWCZM-6YanbhA" bpmnElement="_092A9828-6B85-4F6D-8C82-4ECF5711F719">
<di:waypoint xsi:type="dc:Point" x="650.0" y="180.0"/>
<di:waypoint xsi:type="dc:Point" x="755.0" y="180.0"/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="_ohUbiQL6EeWCZM-6YanbhA" bpmnElement="_4025475D-512E-4AD1-8210-2A6FCA2F09AC">
<dc:Bounds height="28.0" width="28.0" x="840.0" y="166.0"/>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="_ohUbigL6EeWCZM-6YanbhA" bpmnElement="_6AFB1186-0007-4F59-BE88-770D9A0A0EA8">
<di:waypoint xsi:type="dc:Point" x="755.0" y="180.0"/>
<di:waypoint xsi:type="dc:Point" x="854.0" y="180.0"/>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Currency.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_View_Helper_Abstract.php */
require_once 'Zend/View/Helper/Abstract.php';
/**
* Currency view helper
*
* @category Zend
* @package Zend_View
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_View_Helper_Currency extends Zend_View_Helper_Abstract
{
/**
* Currency object
*
* @var Zend_Currency
*/
protected $_currency;
/**
* Constructor for manually handling
*
* @param Zend_Currency $currency Instance of Zend_Currency
* @return void
*/
public function __construct($currency = null)
{
if ($currency === null) {
require_once 'Zend/Registry.php';
if (Zend_Registry::isRegistered('Zend_Currency')) {
$currency = Zend_Registry::get('Zend_Currency');
}
}
$this->setCurrency($currency);
}
/**
* Output a formatted currency
*
* @param integer|float $value Currency value to output
* @param string|Zend_Locale|Zend_Currency $currency OPTIONAL Currency to use for this call
* @return string Formatted currency
*/
public function currency($value = null, $currency = null)
{
if ($value === null) {
return $this;
}
if (is_string($currency) || ($currency instanceof Zend_Locale)) {
require_once 'Zend/Locale.php';
if (Zend_Locale::isLocale($currency)) {
$currency = array('locale' => $currency);
}
}
if (is_string($currency)) {
$currency = array('currency' => $currency);
}
if (is_array($currency)) {
return $this->_currency->toCurrency($value, $currency);
}
return $this->_currency->toCurrency($value);
}
/**
* Sets a currency to use
*
* @param Zend_Currency|String|Zend_Locale $currency Currency to use
* @throws Zend_View_Exception When no or a false currency was set
* @return Zend_View_Helper_Currency
*/
public function setCurrency($currency = null)
{
if (!$currency instanceof Zend_Currency) {
require_once 'Zend/Currency.php';
$currency = new Zend_Currency($currency);
}
$this->_currency = $currency;
return $this;
}
/**
* Retrieve currency object
*
* @return Zend_Currency|null
*/
public function getCurrency()
{
return $this->_currency;
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/renderer_frame_manager.h"
#include <algorithm>
#include "base/logging.h"
#include "base/sys_info.h"
namespace content {
RendererFrameManager* RendererFrameManager::GetInstance() {
return Singleton<RendererFrameManager>::get();
}
void RendererFrameManager::AddFrame(RendererFrameManagerClient* frame,
bool locked) {
RemoveFrame(frame);
if (locked)
locked_frames_[frame] = 1;
else
unlocked_frames_.push_front(frame);
CullUnlockedFrames();
}
void RendererFrameManager::RemoveFrame(RendererFrameManagerClient* frame) {
std::map<RendererFrameManagerClient*, size_t>::iterator locked_iter =
locked_frames_.find(frame);
if (locked_iter != locked_frames_.end())
locked_frames_.erase(locked_iter);
unlocked_frames_.remove(frame);
}
void RendererFrameManager::LockFrame(RendererFrameManagerClient* frame) {
std::list<RendererFrameManagerClient*>::iterator unlocked_iter =
std::find(unlocked_frames_.begin(), unlocked_frames_.end(), frame);
if (unlocked_iter != unlocked_frames_.end()) {
DCHECK(locked_frames_.find(frame) == locked_frames_.end());
unlocked_frames_.remove(frame);
locked_frames_[frame] = 1;
} else {
DCHECK(locked_frames_.find(frame) != locked_frames_.end());
locked_frames_[frame]++;
}
}
void RendererFrameManager::UnlockFrame(RendererFrameManagerClient* frame) {
DCHECK(locked_frames_.find(frame) != locked_frames_.end());
size_t locked_count = locked_frames_[frame];
DCHECK(locked_count);
if (locked_count > 1) {
locked_frames_[frame]--;
} else {
RemoveFrame(frame);
unlocked_frames_.push_front(frame);
CullUnlockedFrames();
}
}
RendererFrameManager::RendererFrameManager() {
max_number_of_saved_frames_ =
#if defined(OS_ANDROID)
1;
#else
std::min(5, 2 + (base::SysInfo::AmountOfPhysicalMemoryMB() / 256));
#endif
}
RendererFrameManager::~RendererFrameManager() {}
void RendererFrameManager::CullUnlockedFrames() {
while (!unlocked_frames_.empty() &&
unlocked_frames_.size() + locked_frames_.size() >
max_number_of_saved_frames()) {
size_t old_size = unlocked_frames_.size();
// Should remove self from list.
unlocked_frames_.back()->EvictCurrentFrame();
DCHECK_EQ(unlocked_frames_.size() + 1, old_size);
}
}
} // namespace content
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Ui\Component\Form\Element;
use Magento\Framework\Data\OptionSourceInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
/**
* Base abstract form element.
*
* phpcs:disable Magento2.Classes.AbstractApi
* @api
* @since 100.1.0
*/
abstract class AbstractOptionsField extends AbstractElement
{
/**
* @var array|OptionSourceInterface|null
* @since 100.1.0
*/
protected $options;
/**
* Constructor
*
* @param ContextInterface $context
* @param array|OptionSourceInterface|null $options
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
$options = null,
array $components = [],
array $data = []
) {
$this->options = $options;
parent::__construct($context, $components, $data);
}
/**
* Prepare component configuration
*
* @return void
* @since 100.1.0
*/
public function prepare()
{
$config = $this->getData('config');
if (isset($this->options)) {
if (!isset($config['options'])) {
$config['options'] = [];
}
if ($this->options instanceof OptionSourceInterface) {
$options = $this->options->toOptionArray();
} else {
$options = array_values($this->options);
}
if (empty($config['rawOptions'])) {
$options = $this->convertOptionsValueToString($options);
}
array_walk(
$options,
function (&$item) {
$item['__disableTmpl'] = true;
}
);
$config['options'] = array_values(array_replace_recursive($config['options'], $options));
}
$this->setData('config', (array)$config);
parent::prepare();
}
/**
* Check if option value
*
* @param string $optionValue
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
* @since 100.1.0
*/
abstract public function getIsSelected($optionValue);
/**
* Convert options value to string
*
* @param array $options
* @return array
* @since 100.1.0
*/
protected function convertOptionsValueToString(array $options)
{
array_walk(
$options,
function (&$value) {
if (isset($value['value']) && is_scalar($value['value'])) {
$value['value'] = (string)$value['value'];
}
}
);
return $options;
}
}
|
{
"pile_set_name": "Github"
}
|
"""
@package gmodeler.preferences
@brief wxGUI Graphical Modeler - preferences
Classes:
- preferences::PreferencesDialog
- preferences::PropertiesDialog
(C) 2010-2013 by the GRASS Development Team
This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.
@author Martin Landa <landa.martin gmail.com>
"""
import wx
import wx.lib.colourselect as csel
from core import globalvar
from gui_core.preferences import PreferencesBaseDialog
from core.settings import UserSettings
from gui_core.wrap import SpinCtrl, Button, StaticText, \
StaticBox, TextCtrl
class PreferencesDialog(PreferencesBaseDialog):
"""User preferences dialog"""
def __init__(self, parent, giface, settings=UserSettings,
title=_("Modeler settings")):
PreferencesBaseDialog.__init__(
self,
parent=parent,
giface=giface,
title=title,
settings=settings)
# create notebook pages
self._createGeneralPage(self.notebook)
self._createActionPage(self.notebook)
self._createDataPage(self.notebook)
self._createLoopPage(self.notebook)
self._createCommentPage(self.notebook)
self.SetMinSize(self.GetBestSize())
self.SetSize(self.size)
def _createGeneralPage(self, notebook):
"""Create notebook page for action settings"""
panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
notebook.AddPage(page=panel, text=_("General"))
# colors
border = wx.BoxSizer(wx.VERTICAL)
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Item properties"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Disabled:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
rColor = csel.ColourSelect(
parent=panel,
id=wx.ID_ANY,
colour=self.settings.Get(
group='modeler',
key='disabled',
subkey='color'),
size=globalvar.DIALOG_COLOR_SIZE)
rColor.SetName('GetColour')
self.winId['modeler:disabled:color'] = rColor.GetId()
gridSizer.Add(rColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
panel.SetSizer(border)
return panel
def _createActionPage(self, notebook):
"""Create notebook page for action settings"""
panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
notebook.AddPage(page=panel, text=_("Command"))
# colors
border = wx.BoxSizer(wx.VERTICAL)
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Color"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Valid:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
vColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='action', subkey=(
'color', 'valid')), size=globalvar.DIALOG_COLOR_SIZE)
vColor.SetName('GetColour')
self.winId['modeler:action:color:valid'] = vColor.GetId()
gridSizer.Add(vColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Invalid:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
iColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='action', subkey=(
'color', 'invalid')), size=globalvar.DIALOG_COLOR_SIZE)
iColor.SetName('GetColour')
self.winId['modeler:action:color:invalid'] = iColor.GetId()
gridSizer.Add(iColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Running:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
rColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='action', subkey=(
'color', 'running')), size=globalvar.DIALOG_COLOR_SIZE)
rColor.SetName('GetColour')
self.winId['modeler:action:color:running'] = rColor.GetId()
gridSizer.Add(rColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
# size
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Shape size"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Width:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
width = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='action',
subkey=(
'size',
'width')))
width.SetName('GetValue')
self.winId['modeler:action:size:width'] = width.GetId()
gridSizer.Add(width,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Height:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
height = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='action',
subkey=(
'size',
'height')))
height.SetName('GetValue')
self.winId['modeler:action:size:height'] = height.GetId()
gridSizer.Add(height,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
panel.SetSizer(border)
return panel
def _createDataPage(self, notebook):
"""Create notebook page for data settings"""
panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
notebook.AddPage(page=panel, text=_("Data"))
# colors
border = wx.BoxSizer(wx.VERTICAL)
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Type"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Raster:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
rColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='data', subkey=(
'color', 'raster')), size=globalvar.DIALOG_COLOR_SIZE)
rColor.SetName('GetColour')
self.winId['modeler:data:color:raster'] = rColor.GetId()
gridSizer.Add(rColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("3D raster:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
r3Color = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='data', subkey=(
'color', 'raster3d')), size=globalvar.DIALOG_COLOR_SIZE)
r3Color.SetName('GetColour')
self.winId['modeler:data:color:raster3d'] = r3Color.GetId()
gridSizer.Add(r3Color,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Vector:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
vColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='data', subkey=(
'color', 'vector')), size=globalvar.DIALOG_COLOR_SIZE)
vColor.SetName('GetColour')
self.winId['modeler:data:color:vector'] = vColor.GetId()
gridSizer.Add(vColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Table:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
tColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='data', subkey=(
'color', 'dbtable')), size=globalvar.DIALOG_COLOR_SIZE)
tColor.SetName('GetColour')
self.winId['modeler:data:color:dbtable'] = tColor.GetId()
gridSizer.Add(tColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
# size
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Shape size"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Width:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
width = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='data',
subkey=(
'size',
'width')))
width.SetName('GetValue')
self.winId['modeler:data:size:width'] = width.GetId()
gridSizer.Add(width,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Height:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
height = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='data',
subkey=(
'size',
'height')))
height.SetName('GetValue')
self.winId['modeler:data:size:height'] = height.GetId()
gridSizer.Add(height,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
panel.SetSizer(border)
return panel
def _createLoopPage(self, notebook):
"""Create notebook page for loop settings"""
panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
notebook.AddPage(page=panel, text=_("Loop"))
# colors
border = wx.BoxSizer(wx.VERTICAL)
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Color"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Valid:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
vColor = csel.ColourSelect(
parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
group='modeler', key='loop', subkey=(
'color', 'valid')), size=globalvar.DIALOG_COLOR_SIZE)
vColor.SetName('GetColour')
self.winId['modeler:loop:color:valid'] = vColor.GetId()
gridSizer.Add(vColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
# size
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Shape size"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Width:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
width = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='loop',
subkey=(
'size',
'width')))
width.SetName('GetValue')
self.winId['modeler:loop:size:width'] = width.GetId()
gridSizer.Add(width,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Height:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
height = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='loop',
subkey=(
'size',
'height')))
height.SetName('GetValue')
self.winId['modeler:loop:size:height'] = height.GetId()
gridSizer.Add(height,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
panel.SetSizer(border)
return panel
def _createCommentPage(self, notebook):
"""Create notebook page for comment settings"""
panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
notebook.AddPage(page=panel, text=_("Comment"))
# colors
border = wx.BoxSizer(wx.VERTICAL)
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Color"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Valid:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
vColor = csel.ColourSelect(
parent=panel,
id=wx.ID_ANY,
colour=self.settings.Get(
group='modeler',
key='comment',
subkey='color'),
size=globalvar.DIALOG_COLOR_SIZE)
vColor.SetName('GetColour')
self.winId['modeler:comment:color'] = vColor.GetId()
gridSizer.Add(vColor,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
# size
box = StaticBox(parent=panel, id=wx.ID_ANY,
label=" %s " % _("Shape size"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Width:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
width = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='comment',
subkey=(
'size',
'width')))
width.SetName('GetValue')
self.winId['modeler:comment:size:width'] = width.GetId()
gridSizer.Add(width,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
row += 1
gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
label=_("Height:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 0))
height = SpinCtrl(
parent=panel,
id=wx.ID_ANY,
min=0,
max=500,
initial=self.settings.Get(
group='modeler',
key='comment',
subkey=(
'size',
'height')))
height.SetName('GetValue')
self.winId['modeler:comment:size:height'] = height.GetId()
gridSizer.Add(height,
flag=wx.ALIGN_RIGHT |
wx.ALIGN_CENTER_VERTICAL,
pos=(row, 1))
gridSizer.AddGrowableCol(0)
sizer.Add(
gridSizer,
proportion=1,
flag=wx.ALL | wx.EXPAND,
border=5)
border.Add(sizer, proportion=0, flag=wx.LEFT |
wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=3)
panel.SetSizer(border)
return panel
def OnApply(self, event):
"""Button 'Apply' pressed"""
PreferencesBaseDialog.OnApply(self, event)
self.parent.GetModel().Update()
self.parent.GetCanvas().Refresh()
def OnSave(self, event):
"""Button 'Save' pressed"""
PreferencesBaseDialog.OnSave(self, event)
self.parent.GetModel().Update()
self.parent.GetCanvas().Refresh()
class PropertiesDialog(wx.Dialog):
"""Model properties dialog
"""
def __init__(self, parent, id=wx.ID_ANY,
title=_('Model properties'),
size=(350, 400),
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
wx.Dialog.__init__(self, parent, id, title, size=size,
style=style)
self.metaBox = StaticBox(parent=self, id=wx.ID_ANY,
label=" %s " % _("Metadata"))
self.cmdBox = StaticBox(parent=self, id=wx.ID_ANY,
label=" %s " % _("Commands"))
self.name = TextCtrl(parent=self, id=wx.ID_ANY,
size=(300, 25))
self.desc = TextCtrl(parent=self, id=wx.ID_ANY,
style=wx.TE_MULTILINE,
size=(300, 50))
self.author = TextCtrl(parent=self, id=wx.ID_ANY,
size=(300, 25))
# commands
self.overwrite = wx.CheckBox(parent=self, id=wx.ID_ANY, label=_(
"Allow output files to overwrite existing files"))
self.overwrite.SetValue(
UserSettings.Get(
group='cmd',
key='overwrite',
subkey='enabled'))
# buttons
self.btnOk = Button(self, wx.ID_OK)
self.btnCancel = Button(self, wx.ID_CANCEL)
self.btnOk.SetDefault()
self.btnOk.SetToolTip(_("Apply properties"))
self.btnOk.SetDefault()
self.btnCancel.SetToolTip(_("Close dialog and ignore changes"))
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self._layout()
def _layout(self):
metaSizer = wx.StaticBoxSizer(self.metaBox, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
gridSizer.Add(StaticText(parent=self, id=wx.ID_ANY,
label=_("Name:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(0, 0))
gridSizer.Add(self.name,
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
pos=(0, 1))
gridSizer.Add(StaticText(parent=self, id=wx.ID_ANY,
label=_("Description:")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(1, 0))
gridSizer.Add(self.desc,
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
pos=(1, 1))
gridSizer.Add(StaticText(parent=self, id=wx.ID_ANY,
label=_("Author(s):")),
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL,
pos=(2, 0))
gridSizer.Add(self.author,
flag=wx.ALIGN_LEFT |
wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
pos=(2, 1))
gridSizer.AddGrowableCol(1)
gridSizer.AddGrowableRow(1)
metaSizer.Add(gridSizer, proportion=1, flag=wx.EXPAND)
cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
cmdSizer.Add(self.overwrite,
flag=wx.EXPAND | wx.ALL, border=3)
btnStdSizer = wx.StdDialogButtonSizer()
btnStdSizer.AddButton(self.btnCancel)
btnStdSizer.AddButton(self.btnOk)
btnStdSizer.Realize()
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(metaSizer, proportion=1,
flag=wx.EXPAND | wx.ALL, border=5)
mainSizer.Add(
cmdSizer,
proportion=0,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
border=5)
mainSizer.Add(btnStdSizer, proportion=0,
flag=wx.EXPAND | wx.ALL, border=5)
self.SetSizer(mainSizer)
mainSizer.Fit(self)
def OnCloseWindow(self, event):
self.Hide()
def GetValues(self):
"""Get values"""
return {'name': self.name.GetValue(),
'description': self.desc.GetValue(),
'author': self.author.GetValue(),
'overwrite': self.overwrite.IsChecked()}
def Init(self, prop):
"""Initialize dialog"""
self.name.SetValue(prop['name'])
self.desc.SetValue(prop['description'])
self.author.SetValue(prop['author'])
if 'overwrite' in prop:
self.overwrite.SetValue(prop['overwrite'])
|
{
"pile_set_name": "Github"
}
|
/*
Firewall Builder
Copyright (C) 2011 NetCitadel, LLC
Author: Vadim Kurland vadim@fwbuilder.org
This program is free software which we release under the GNU General Public
License. You may redistribute and/or modify this program under the terms
of that license as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To get a copy of the GNU General Public License, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "getProtoByName.h"
#ifndef _WIN32
# include <netdb.h>
# include <netinet/in.h>
#else
# include <winsock2.h>
#endif
QMap<QString, int> GetProtoByName::protocols;
int GetProtoByName::getProtocolByName(const QString &name)
{
if (protocols.size() == 0)
{
protocols["icmp"] = 1;
protocols["igmp"] = 2;
protocols["ggp"] = 3;
protocols["ipencap"] = 4;
protocols["st"] = 5;
protocols["tcp"] = 6;
protocols["egp"] = 8;
protocols["igp"] = 9;
protocols["pup"] = 12;
protocols["udp"] = 17;
protocols["hmp"] = 20;
protocols["xns-idp"] = 22;
protocols["rdp"] = 27;
protocols["iso-tp4"] = 29;
protocols["xtp"] = 36;
protocols["ddp"] = 37;
protocols["idpr-cmtp"] = 38;
protocols["ipv6"] = 41;
protocols["ipv6-route"] = 43;
protocols["ipv6-frag"]= 44;
protocols["idrp"] = 45;
protocols["rsvp"] = 46;
protocols["gre"] = 47;
protocols["esp"] = 50;
protocols["ah"] = 51;
protocols["skip"] = 57;
protocols["ipv6-icmp"] = 58;
protocols["ipv6-nonxt"] = 59;
protocols["ipv6-opts"] = 60;
protocols["rspf"] = 73;
protocols["vmtp"] = 81;
protocols["eigrp"] = 88;
protocols["ospf"] = 89;
protocols["ax.25"] = 93;
protocols["ipip"] = 94;
protocols["etherip"] = 97;
protocols["encap"] = 98;
protocols["pim"] = 103;
protocols["ipcomp"] = 108;
protocols["vrrp"] = 112;
protocols["l2tp"] = 115;
protocols["isis"] = 124;
protocols["sctp"] = 132;
protocols["fc"] = 133;
protocols["udplite"] = 136;
protocols["mpls-in-ip"] = 137;
protocols["manet"] = 138;
protocols["hip"] = 139;
// these are found in Cisco configs. Some of these names
// duplicate protocols listed above but a few are extras.
protocols["ah"] = 51;
protocols["ahp"] = 51;
protocols["eigrp"] = 88;
protocols["esp"] = 50;
protocols["gre"] = 47;
protocols["igmp"] = 2;
protocols["igrp"] = 9;
protocols["ip"] = 0;
protocols["ipinip"] = 4;
protocols["nos"] = 94;
protocols["ospf"] = 89;
protocols["pim"] = 103;
protocols["pcp"] = 108;
protocols["snp"] = 109;
// ASA configs use protocol name "ipsec" as an alias for "esp"
// and "pptp" as an alias for "gre"
protocols["ipsec"] = 50;
protocols["pptp"] = 47;
}
bool ok = false;
int protocol = name.toInt(&ok);
if (ok) return protocol;
if (protocols.contains(name)) return protocols[name];
struct protoent *pe = getprotobyname(name.toLatin1().constData());
if (pe!=nullptr)
return pe->p_proto;
return -1;
}
|
{
"pile_set_name": "Github"
}
|
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.
@prefix owl: <http://www.w3.org/2002/07/owl#>.
@prefix mon: <http://www.semwebtech.org/mondial/10/meta#>.
@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
@prefix : <foo://bla/>.
_:Longitude a rdfs:Datatype; owl:onDatatype xsd:int;
owl:withRestrictions (_:long1 _:long2).
_:long1 xsd:minInclusive -180 .
_:long2 xsd:maxInclusive 180 .
#_:Latitude a rdfs:Datatype; owl:onDatatype xsd:int;
# owl:withRestrictions (_:lat1 _:lat2).
#_:lat1 xsd:minInclusive -90 .
#_:lat2 xsd:maxInclusive 90 .
# ********** with that it complains:*************************
_:EasternLongitude a rdfs:Datatype; owl:onDatatype _:Longitude;
owl:withRestrictions (_:eastlong).
# ********** with that it works:*************************
# _:EasternLongitude a rdfs:Datatype; owl:onDatatype xsd:int;
# owl:withRestrictions (_:eastlong).
_:eastlong xsd:minInclusive 0 .
:EasternHemispherePlace owl:equivalentClass [a owl:Restriction;
owl:onProperty mon:longitude; owl:someValuesFrom _:EasternLongitude].
mon:longitude rdfs:range _:Longitude.
#mon:latitude rdfs:range _:Latitude.
:Berlin a mon:City; :name "Berlin"; mon:longitude 13; mon:latitude 52 .
#:Atlantis a mon:City; :name "Atlantis"; mon:longitude -200; mon:latitude 100 .
:Lisbon a mon:City; :name "Lisbon"; mon:longitude -9; mon:latitude 38 .
|
{
"pile_set_name": "Github"
}
|
# frv testcase for tige $ICCi_2,$GRi,$s12
# mach: all
.include "testutils.inc"
start
.global tige
tige:
and_spr_immed -4081,tbr ; clear tbr.tt
set_gr_spr tbr,gr7
inc_gr_immed 2112,gr7 ; address of exception handler
set_bctrlr_0_0 gr7 ; bctrlr 0,0
set_spr_immed 128,lcr
set_gr_immed 0,gr7
set_psr_et 1
set_spr_addr ok0,lr
set_icc 0x0 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
ok0:
set_psr_et 1
set_spr_addr ok1,lr
set_icc 0x1 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
ok1:
set_spr_addr bad,lr
set_icc 0x2 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_spr_addr bad,lr
set_icc 0x3 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_psr_et 1
set_spr_addr ok4,lr
set_icc 0x4 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
ok4:
set_psr_et 1
set_spr_addr ok5,lr
set_icc 0x5 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
ok5:
set_psr_et 1
set_spr_addr bad,lr
set_icc 0x6 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_spr_addr bad,lr
set_icc 0x7 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_spr_addr bad,lr
set_icc 0x8 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_spr_addr bad,lr
set_icc 0x9 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_psr_et 1
set_spr_addr oka,lr
set_icc 0xa 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
oka:
set_psr_et 1
set_spr_addr okb,lr
set_icc 0xb 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
okb:
set_spr_addr bad,lr
set_icc 0xc 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_spr_addr bad,lr
set_icc 0xd 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
set_psr_et 1
set_spr_addr oke,lr
set_icc 0xe 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
oke:
set_psr_et 1
set_spr_addr okf,lr
set_icc 0xf 0
tige icc0,gr7,4 ; should branch to tbr + (128 + 4)*16
fail
okf:
pass
bad:
fail
|
{
"pile_set_name": "Github"
}
|
import numpy as np
from bmtk.builder.networks import NetworkBuilder
from bmtk.builder.auxi.node_params import positions_columinar
from bmtk.builder.auxi.edge_connectors import distance_connector
"""Create Nodes"""
net = NetworkBuilder("V1")
net.add_nodes(N=80, # Create a population of 80 neurons
positions=positions_columinar(N=80, center=[0, 50.0, 0], max_radius=30.0, height=100.0),
pop_name='Scnn1a', location='VisL4', ei='e', # optional parameters
model_type='point_process', # Tells the simulator to use point-based neurons
model_template='nest:iaf_psc_alpha', # tells the simulator to use NEST iaf_psc_alpha models
dynamics_params='472363762_point.json' # File containing iaf_psc_alpha mdoel parameters
)
net.add_nodes(N=20, pop_name='PV', location='VisL4', ei='i',
positions=positions_columinar(N=20, center=[0, 50.0, 0], max_radius=30.0, height=100.0),
model_type='point_process',
model_template='nest:iaf_psc_alpha',
dynamics_params='472912177_point.json')
net.add_nodes(N=200, pop_name='LIF_exc', location='L4', ei='e',
positions=positions_columinar(N=200, center=[0, 50.0, 0], min_radius=30.0, max_radius=60.0, height=100.0),
model_type='point_process',
model_template='nest:iaf_psc_alpha',
dynamics_params='IntFire1_exc_point.json')
net.add_nodes(N=100, pop_name='LIF_inh', location='L4', ei='i',
positions=positions_columinar(N=100, center=[0, 50.0, 0], min_radius=30.0, max_radius=60.0, height=100.0),
model_type='point_process',
model_template='nest:iaf_psc_alpha',
dynamics_params='IntFire1_inh_point.json')
"""Create edges"""
## E-to-E connections
net.add_edges(source={'ei': 'e'}, target={'pop_name': 'Scnn1a'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 0.34, 'd_max': 300.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=5.0,
delay=2.0,
dynamics_params='ExcToExc.json',
model_template='static_synapse')
net.add_edges(source={'ei': 'e'}, target={'pop_name': 'LIF_exc'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 0.34, 'd_max': 300.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=10.0,
delay=2.0,
dynamics_params='instanteneousExc.json',
model_template='static_synapse')
### Generating I-to-I connections
net.add_edges(source={'ei': 'i'}, target={'pop_name': 'PV'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 1.0, 'd_max': 160.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=-1.0,
delay=2.0,
dynamics_params='InhToInh.json',
model_template='static_synapse')
net.add_edges(source={'ei': 'i'}, target={'ei': 'i', 'pop_name': 'LIF_inh'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 1.0, 'd_max': 160.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=-1.0,
delay=2.0,
dynamics_params='instanteneousInh.json',
model_template='static_synapse')
### Generating I-to-E connections
net.add_edges(source={'ei': 'i'}, target={'ei': 'e', 'pop_name': 'Scnn1a'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 1.0, 'd_max': 160.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=-15.0,
delay=2.0,
dynamics_params='InhToExc.json',
model_template='static_synapse')
net.add_edges(source={'ei': 'i'}, target={'ei': 'e', 'pop_name': 'LIF_exc'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 1.0, 'd_max': 160.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=-15.0,
delay=2.0,
dynamics_params='instanteneousInh.json',
model_template='static_synapse')
### Generating E-to-I connections
net.add_edges(source={'ei': 'e'}, target={'pop_name': 'PV'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 0.26, 'd_max': 300.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=15.0,
delay=2.0,
dynamics_params='ExcToInh.json',
model_template='static_synapse')
net.add_edges(source={'ei': 'e'}, target={'pop_name': 'LIF_inh'},
connection_rule=distance_connector,
connection_params={'d_weight_min': 0.0, 'd_weight_max': 0.26, 'd_max': 300.0, 'nsyn_min': 3, 'nsyn_max': 7},
syn_weight=5.0,
delay=2.0,
dynamics_params='instanteneousExc.json',
model_template='static_synapse')
net.build()
net.save_nodes(output_dir='network')
net.save_edges(output_dir='network')
lgn = NetworkBuilder('LGN')
lgn.add_nodes(N=500,
pop_name='tON',
potential='exc',
model_type='virtual')
def select_source_cells(sources, target, nsources_min=10, nsources_max=30, nsyns_min=3, nsyns_max=12):
total_sources = len(sources)
nsources = np.random.randint(nsources_min, nsources_max)
selected_sources = np.random.choice(total_sources, nsources, replace=False)
syns = np.zeros(total_sources)
syns[selected_sources] = np.random.randint(nsyns_min, nsyns_max, size=nsources)
return syns
lgn.add_edges(source=lgn.nodes(), target=net.nodes(pop_name='Scnn1a'),
iterator='all_to_one',
connection_rule=select_source_cells,
connection_params={'nsources_min': 10, 'nsources_max': 25},
syn_weight=20.0,
delay=2.0,
dynamics_params='ExcToExc.json',
model_template='static_synapse')
lgn.add_edges(source=lgn.nodes(), target=net.nodes(pop_name='PV1'),
connection_rule=select_source_cells,
connection_params={'nsources_min': 15, 'nsources_max': 30},
iterator='all_to_one',
syn_weight=20.0,
delay=2.0,
dynamics_params='ExcToInh.json',
model_template='static_synapse')
lgn.add_edges(source=lgn.nodes(), target=net.nodes(pop_name='LIF_exc'),
connection_rule=select_source_cells,
connection_params={'nsources_min': 10, 'nsources_max': 25},
iterator='all_to_one',
syn_weight=10.0,
delay=2.0,
dynamics_params='instanteneousExc.json',
model_template='static_synapse')
lgn.add_edges(source=lgn.nodes(), target=net.nodes(pop_name='LIF_inh'),
connection_rule=select_source_cells,
connection_params={'nsources_min': 15, 'nsources_max': 30},
iterator='all_to_one',
syn_weight=10.0,
delay=2.0,
dynamics_params='instanteneousExc.json',
model_template='static_synapse')
lgn.build()
lgn.save_nodes(output_dir='network')
lgn.save_edges(output_dir='network')
|
{
"pile_set_name": "Github"
}
|
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Core
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial interface ICorePointerInputSource
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
bool HasCapture
{
get;
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
global::Windows.UI.Core.CoreCursor PointerCursor
{
get;
set;
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
global::Windows.Foundation.Point PointerPosition
{
get;
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
void ReleasePointerCapture();
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
void SetPointerCapture();
#endif
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.HasCapture.get
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerPosition.get
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerCursor.get
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerCursor.set
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerCaptureLost.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerCaptureLost.remove
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerEntered.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerEntered.remove
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerExited.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerExited.remove
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerMoved.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerMoved.remove
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerPressed.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerPressed.remove
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerReleased.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerReleased.remove
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerWheelChanged.add
// Forced skipping of method Windows.UI.Core.ICorePointerInputSource.PointerWheelChanged.remove
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerCaptureLost;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerEntered;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerExited;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerMoved;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerPressed;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerReleased;
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
event global::Windows.Foundation.TypedEventHandler<object, global::Windows.UI.Core.PointerEventArgs> PointerWheelChanged;
#endif
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V251.Segment{
///<summary>
/// Represents an HL7 MRG message segment.
/// This segment has the following fields:<ol>
///<li>MRG-1: Prior Patient Identifier List (CX)</li>
///<li>MRG-2: Prior Alternate Patient ID (CX)</li>
///<li>MRG-3: Prior Patient Account Number (CX)</li>
///<li>MRG-4: Prior Patient ID (CX)</li>
///<li>MRG-5: Prior Visit Number (CX)</li>
///<li>MRG-6: Prior Alternate Visit ID (CX)</li>
///<li>MRG-7: Prior Patient Name (XPN)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class MRG : AbstractSegment {
/**
* Creates a MRG (Merge Patient Information) segment object that belongs to the given
* message.
*/
public MRG(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(CX), true, 0, 250, new System.Object[]{message}, "Prior Patient Identifier List");
this.add(typeof(CX), false, 0, 250, new System.Object[]{message}, "Prior Alternate Patient ID");
this.add(typeof(CX), false, 1, 250, new System.Object[]{message}, "Prior Patient Account Number");
this.add(typeof(CX), false, 1, 250, new System.Object[]{message}, "Prior Patient ID");
this.add(typeof(CX), false, 1, 250, new System.Object[]{message}, "Prior Visit Number");
this.add(typeof(CX), false, 1, 250, new System.Object[]{message}, "Prior Alternate Visit ID");
this.add(typeof(XPN), false, 0, 250, new System.Object[]{message}, "Prior Patient Name");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns a single repetition of Prior Patient Identifier List(MRG-1).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CX GetPriorPatientIdentifierList(int rep)
{
CX ret = null;
try
{
IType t = this.GetField(1, rep);
ret = (CX)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Prior Patient Identifier List (MRG-1).
///</summary>
public CX[] GetPriorPatientIdentifierList() {
CX[] ret = null;
try {
IType[] t = this.GetField(1);
ret = new CX[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CX)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Prior Patient Identifier List (MRG-1).
///</summary>
public int PriorPatientIdentifierListRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(1);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns a single repetition of Prior Alternate Patient ID(MRG-2).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CX GetPriorAlternatePatientID(int rep)
{
CX ret = null;
try
{
IType t = this.GetField(2, rep);
ret = (CX)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Prior Alternate Patient ID (MRG-2).
///</summary>
public CX[] GetPriorAlternatePatientID() {
CX[] ret = null;
try {
IType[] t = this.GetField(2);
ret = new CX[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CX)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Prior Alternate Patient ID (MRG-2).
///</summary>
public int PriorAlternatePatientIDRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(2);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Prior Patient Account Number(MRG-3).
///</summary>
public CX PriorPatientAccountNumber
{
get{
CX ret = null;
try
{
IType t = this.GetField(3, 0);
ret = (CX)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Prior Patient ID(MRG-4).
///</summary>
public CX PriorPatientID
{
get{
CX ret = null;
try
{
IType t = this.GetField(4, 0);
ret = (CX)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Prior Visit Number(MRG-5).
///</summary>
public CX PriorVisitNumber
{
get{
CX ret = null;
try
{
IType t = this.GetField(5, 0);
ret = (CX)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Prior Alternate Visit ID(MRG-6).
///</summary>
public CX PriorAlternateVisitID
{
get{
CX ret = null;
try
{
IType t = this.GetField(6, 0);
ret = (CX)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Prior Patient Name(MRG-7).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public XPN GetPriorPatientName(int rep)
{
XPN ret = null;
try
{
IType t = this.GetField(7, rep);
ret = (XPN)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Prior Patient Name (MRG-7).
///</summary>
public XPN[] GetPriorPatientName() {
XPN[] ret = null;
try {
IType[] t = this.GetField(7);
ret = new XPN[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (XPN)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Prior Patient Name (MRG-7).
///</summary>
public int PriorPatientNameRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(7);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
}}
|
{
"pile_set_name": "Github"
}
|
from unittest.mock import patch
from .....graphql.csv.enums import ProductFieldEnum
from .....product.models import Attribute, Product, ProductImage, VariantImage
from .....warehouse.models import Warehouse
from ....utils.products_data import (
ProductExportFields,
add_attribute_info_to_data,
add_collection_info_to_data,
add_image_uris_to_data,
add_warehouse_info_to_data,
get_products_relations_data,
get_variants_relations_data,
prepare_products_relations_data,
prepare_variants_relations_data,
)
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
def test_get_products_relations_data(prepare_products_data_mocked, product_list):
# given
qs = Product.objects.all()
export_fields = {
"collections__slug" "images__image",
"name",
"description",
}
attribute_ids = []
# when
get_products_relations_data(qs, export_fields, attribute_ids)
# then
prepare_products_data_mocked.called_once_with(
qs, {"collections__slug", "images__image"}, attribute_ids
)
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
def test_get_products_relations_data_no_relations_fields(
prepare_products_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = []
# when
get_products_relations_data(qs, export_fields, attribute_ids)
# then
prepare_products_data_mocked.assert_not_called()
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
def test_get_products_relations_data_attribute_ids(
prepare_products_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
# when
get_products_relations_data(qs, export_fields, attribute_ids)
# then
prepare_products_data_mocked.called_once_with(qs, {}, attribute_ids)
def test_prepare_products_relations_data(product_with_image, collection_list):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
collection_list[1].products.add(product_with_image)
qs = Product.objects.all()
fields = set(
ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values()
)
attribute_ids = [
str(attr.assignment.attribute.pk)
for attr in product_with_image.attributes.all()
]
# when
result = prepare_products_relations_data(qs, fields, attribute_ids)
# then
collections = ", ".join(
sorted([collection.slug for collection in collection_list[:2]])
)
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
for image in product_with_image.images.all()
]
)
expected_result = {pk: {"collections__slug": collections, "images__image": images}}
assigned_attribute = product_with_image.attributes.first()
if assigned_attribute:
header = f"{assigned_attribute.attribute.slug} (product attribute)"
expected_result[pk][header] = assigned_attribute.values.first().slug
assert result == expected_result
def test_prepare_products_relations_data_only_fields(
product_with_image, collection_list
):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
collection_list[1].products.add(product_with_image)
qs = Product.objects.all()
fields = {"collections__slug"}
attribute_ids = []
# when
result = prepare_products_relations_data(qs, fields, attribute_ids)
# then
collections = ", ".join(
sorted([collection.slug for collection in collection_list[:2]])
)
expected_result = {pk: {"collections__slug": collections}}
assert result == expected_result
def test_prepare_products_relations_data_only_attributes_ids(
product_with_image, collection_list
):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
collection_list[1].products.add(product_with_image)
qs = Product.objects.all()
fields = {"name"}
attribute_ids = [
str(attr.assignment.attribute.pk)
for attr in product_with_image.attributes.all()
]
# when
result = prepare_products_relations_data(qs, fields, attribute_ids)
# then
expected_result = {pk: {}}
assigned_attribute = product_with_image.attributes.first()
if assigned_attribute:
header = f"{assigned_attribute.attribute.slug} (product attribute)"
expected_result[pk][header] = assigned_attribute.values.first().slug
assert result == expected_result
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data(prepare_variants_data_mocked, product_list):
# given
qs = Product.objects.all()
export_fields = {
"collections__slug",
"variants__sku",
"variants__images__image",
}
attribute_ids = []
warehouse_ids = []
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(
qs, {ProductFieldEnum.VARIANT_IMAGES.value}, attribute_ids, warehouse_ids
)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_no_relations_fields(
prepare_variants_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "variants__sku"}
attribute_ids = []
warehouse_ids = []
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.assert_not_called()
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_attribute_ids(
prepare_variants_data_mocked, product_list
):
# given
qs = Product.objects.all()
export_fields = {"name", "variants__sku"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
warehouse_ids = []
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_warehouse_ids(
prepare_variants_data_mocked, product_list, warehouses
):
# given
qs = Product.objects.all()
export_fields = {"name", "variants__sku"}
attribute_ids = []
warehouse_ids = list(Warehouse.objects.values_list("pk", flat=True))
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data_attributes_and_warehouses_ids(
prepare_variants_data_mocked, product_list, warehouses
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
warehouse_ids = list(Warehouse.objects.values_list("pk", flat=True))
# when
get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
# then
prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
def test_prepare_variants_relations_data(
product_with_variant_with_two_attributes, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
product_image = ProductImage.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
VariantImage.objects.create(variant=variant, image=product_image)
fields = {"variants__images__image"}
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
for image in variant.images.all()
]
)
expected_result = {pk: {"variants__images__image": images}}
for assigned_attribute in variant.attributes.all():
header = f"{assigned_attribute.attribute.slug} (variant attribute)"
if str(assigned_attribute.attribute.pk) in attribute_ids:
expected_result[pk][header] = assigned_attribute.values.first().slug
for stock in variant.stocks.all():
if str(stock.warehouse.pk) in warehouse_ids:
slug = stock.warehouse.slug
warehouse_headers = [
f"{slug} (warehouse quantity)",
]
expected_result[pk][warehouse_headers[0]] = stock.quantity
assert result == expected_result
def test_prepare_variants_relations_data_only_fields(
product_with_variant_with_two_attributes, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
product_image = ProductImage.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
VariantImage.objects.create(variant=variant, image=product_image)
fields = {"variants__images__image"}
attribute_ids = []
warehouse_ids = []
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
for image in variant.images.all()
]
)
expected_result = {pk: {"variants__images__image": images}}
assert result == expected_result
def test_prepare_variants_relations_data_attributes_ids(
product_with_variant_with_two_attributes, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
product_image = ProductImage.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
VariantImage.objects.create(variant=variant, image=product_image)
fields = set()
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = []
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
expected_result = {pk: {}}
for assigned_attribute in variant.attributes.all():
header = f"{assigned_attribute.attribute.slug} (variant attribute)"
if str(assigned_attribute.attribute.pk) in attribute_ids:
expected_result[pk][header] = assigned_attribute.values.first().slug
assert result == expected_result
def test_prepare_variants_relations_data_warehouse_ids(
product_with_single_variant, image, media_root
):
# given
qs = Product.objects.all()
variant = product_with_single_variant.variants.first()
fields = set()
attribute_ids = []
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
# when
result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
# then
pk = variant.pk
expected_result = {pk: {}}
for stock in variant.stocks.all():
if str(stock.warehouse.pk) in warehouse_ids:
slug = stock.warehouse.slug
warehouse_headers = [
f"{slug} (warehouse quantity)",
]
expected_result[pk][warehouse_headers[0]] = stock.quantity
assert result == expected_result
def test_add_collection_info_to_data(product):
# given
pk = product.pk
collection = "test_collection"
input_data = {pk: {}}
# when
result = add_collection_info_to_data(product.pk, collection, input_data)
# then
assert result[pk]["collections__slug"] == {collection}
def test_add_collection_info_to_data_update_collections(product):
# given
pk = product.pk
existing_collection = "test2"
collection = "test_collection"
input_data = {pk: {"collections__slug": {existing_collection}}}
# when
result = add_collection_info_to_data(product.pk, collection, input_data)
# then
assert result[pk]["collections__slug"] == {collection, existing_collection}
def test_add_collection_info_to_data_no_collection(product):
# given
pk = product.pk
collection = None
input_data = {pk: {}}
# when
result = add_collection_info_to_data(product.pk, collection, input_data)
# then
assert result == input_data
def test_add_image_uris_to_data(product):
# given
pk = product.pk
image_path = "test/path/image.jpg"
field = "variant_images"
input_data = {pk: {}}
# when
result = add_image_uris_to_data(product.pk, image_path, field, input_data)
# then
assert result[pk][field] == {"http://mirumee.com/media/" + image_path}
def test_add_image_uris_to_data_update_images(product):
# given
pk = product.pk
old_path = "http://mirumee.com/media/test/image0.jpg"
image_path = "test/path/image.jpg"
input_data = {pk: {"product_images": {old_path}}}
field = "product_images"
# when
result = add_image_uris_to_data(product.pk, image_path, field, input_data)
# then
assert result[pk][field] == {"http://mirumee.com/media/" + image_path, old_path}
def test_add_image_uris_to_data_no_image_path(product):
# given
pk = product.pk
image_path = None
input_data = {pk: {"name": "test"}}
# when
result = add_image_uris_to_data(
product.pk, image_path, "product_images", input_data
)
# then
assert result == input_data
def test_add_attribute_info_to_data(product):
# given
pk = product.pk
slug = "test_attribute_slug"
value = "test value"
attribute_data = {
"slug": slug,
"value": value,
}
input_data = {pk: {}}
# when
result = add_attribute_info_to_data(
product.pk, attribute_data, "product attribute", input_data
)
# then
expected_header = f"{slug} (product attribute)"
assert result[pk][expected_header] == {value}
def test_add_attribute_info_to_data_update_attribute_data(product):
# given
pk = product.pk
slug = "test_attribute_slug"
value = "test value"
expected_header = f"{slug} (variant attribute)"
attribute_data = {
"slug": slug,
"value": value,
}
input_data = {pk: {expected_header: {"value1"}}}
# when
result = add_attribute_info_to_data(
product.pk, attribute_data, "variant attribute", input_data
)
# then
assert result[pk][expected_header] == {value, "value1"}
def test_add_attribute_info_to_data_no_slug(product):
# given
pk = product.pk
attribute_data = {
"slug": None,
"value": None,
}
input_data = {pk: {}}
# when
result = add_attribute_info_to_data(
product.pk, attribute_data, "variant attribute", input_data
)
# then
assert result == input_data
def test_add_warehouse_info_to_data(product):
# given
pk = product.pk
slug = "test_warehouse"
warehouse_data = {
"slug": slug,
"qty": 12,
"qty_alc": 10,
}
input_data = {pk: {}}
# when
result = add_warehouse_info_to_data(product.pk, warehouse_data, input_data)
# then
expected_header = f"{slug} (warehouse quantity)"
assert result[pk][expected_header] == 12
def test_add_warehouse_info_to_data_data_not_changed(product):
# given
pk = product.pk
slug = "test_warehouse"
warehouse_data = {
"slug": slug,
"qty": 12,
"qty_alc": 10,
}
input_data = {
pk: {
f"{slug} (warehouse quantity)": 5,
f"{slug} (warehouse quantity allocated)": 8,
}
}
# when
result = add_warehouse_info_to_data(product.pk, warehouse_data, input_data)
# then
assert result == input_data
def test_add_warehouse_info_to_data_data_no_slug(product):
# given
pk = product.pk
warehouse_data = {
"slug": None,
"qty": None,
"qty_alc": None,
}
input_data = {pk: {}}
# when
result = add_warehouse_info_to_data(product.pk, warehouse_data, input_data)
# then
assert result == input_data
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_LOADER_ASYNC_RESOURCE_HANDLER_H_
#define CONTENT_BROWSER_LOADER_ASYNC_RESOURCE_HANDLER_H_
#include <stdint.h>
#include <string>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/timer/timer.h"
#include "content/browser/loader/resource_handler.h"
#include "content/browser/loader/resource_message_delegate.h"
#include "net/base/io_buffer.h"
#include "url/gurl.h"
namespace net {
class URLRequest;
}
namespace content {
class ResourceBuffer;
class ResourceContext;
class ResourceDispatcherHostImpl;
class ResourceMessageFilter;
class SharedIOBuffer;
// Used to complete an asynchronous resource request in response to resource
// load events from the resource dispatcher host.
class AsyncResourceHandler : public ResourceHandler,
public ResourceMessageDelegate {
public:
AsyncResourceHandler(net::URLRequest* request,
ResourceDispatcherHostImpl* rdh);
~AsyncResourceHandler() override;
bool OnMessageReceived(const IPC::Message& message) override;
// ResourceHandler implementation:
bool OnRequestRedirected(const net::RedirectInfo& redirect_info,
ResourceResponse* response,
bool* defer) override;
bool OnResponseStarted(ResourceResponse* response, bool* defer) override;
bool OnWillStart(const GURL& url, bool* defer) override;
bool OnBeforeNetworkStart(const GURL& url, bool* defer) override;
bool OnWillRead(scoped_refptr<net::IOBuffer>* buf,
int* buf_size,
int min_size) override;
bool OnReadCompleted(int bytes_read, bool* defer) override;
void OnResponseCompleted(const net::URLRequestStatus& status,
const std::string& security_info,
bool* defer) override;
void OnDataDownloaded(int bytes_downloaded) override;
private:
class InliningHelper;
// IPC message handlers:
void OnFollowRedirect(int request_id);
void OnDataReceivedACK(int request_id);
void OnUploadProgressACK(int request_id);
void ReportUploadProgress();
bool EnsureResourceBufferIsInitialized();
void ResumeIfDeferred();
void OnDefer();
bool CheckForSufficientResource();
int CalculateEncodedDataLengthToReport();
void RecordHistogram();
scoped_refptr<ResourceBuffer> buffer_;
ResourceDispatcherHostImpl* rdh_;
// Number of messages we've sent to the renderer that we haven't gotten an
// ACK for. This allows us to avoid having too many messages in flight.
int pending_data_count_;
int allocation_size_;
bool did_defer_;
bool has_checked_for_sufficient_resources_;
bool sent_received_response_msg_;
bool sent_data_buffer_msg_;
std::unique_ptr<InliningHelper> inlining_helper_;
base::TimeTicks response_started_ticks_;
uint64_t last_upload_position_;
bool waiting_for_upload_progress_ack_;
base::TimeTicks last_upload_ticks_;
base::RepeatingTimer progress_timer_;
int64_t reported_transfer_size_;
DISALLOW_COPY_AND_ASSIGN(AsyncResourceHandler);
};
} // namespace content
#endif // CONTENT_BROWSER_LOADER_ASYNC_RESOURCE_HANDLER_H_
|
{
"pile_set_name": "Github"
}
|
# coding=utf-8
"""Tests for medusa/test_list_associated_files.py."""
from __future__ import unicode_literals
import os
from medusa import app
from medusa.post_processor import PostProcessor
import pytest
def _rar_basename(filepath, files):
for found_file in files:
if os.path.splitext(os.path.basename(found_file))[1] == '.rar':
return os.path.basename(os.path.splitext(os.path.basename(found_file))[0].lower())
@pytest.mark.parametrize('p', [
{ # p0: No associated files. Wrong basename
'path': 'media/postprocess/',
'structure': (
'bow.514.hdtv-lol[ettv].mkv',
'bow.514.hdtv-lol.srt',
{'samples': (
'sample.mkv', 'other.mkv',
{'inception': ()}
)}
),
'expected_associated_files': [],
'allowed_extensions': 'nfo,srt'
},
{ # p1: No associated files
'path': 'media/postprocess/',
'structure': (
'bow.514.hdtv-lol[ettv].mkv',
{'samples': (
'sample.mkv', 'other.mkv',
{'inception': (
'cool.txt', 'bla.nfo'
)}
)}
),
'expected_associated_files': [],
'allowed_extensions': 'nfo,srt'
},
{ # p2: No media file, so can't list associated files
'path': 'media/postprocess/',
'structure': (
'bow.514.hdtv-lol.srt',
),
'expected_associated_files': [],
'allowed_extensions': 'nfo,srt'
},
{ # p3: .srt and .nfo associated files. Check subfolders
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv',
{'samples': (
'sample.mkv', 'other.mkv',
{'inception': (
'cool.txt', 'bla.nfo'
)}
)}
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
],
'allowed_extensions': 'nfo,srt',
'subfolders': True,
'refine': True
},
{ # p4: Only .nfo associated file allowed
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv'
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
],
'allowed_extensions': 'nfo',
'refine': True
},
{ # p5: No allowed extensions
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv'
),
'expected_associated_files': [],
'allowed_extensions': '',
'refine': True
},
{ # p6: Associated file based on RARed file
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'show.101.720p-dimension.rar',
'show.101.720p-dimension.nfo'
),
'expected_associated_files': ['show.101.720p-dimension.nfo'],
'allowed_extensions': 'nfo'
},
{ # p7: 'Subtitles only' param for associated files
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv'
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt'],
'allowed_extensions': 'nfo,srt',
'subtitles_only': True
},
{ # p8: Subtitle in subfolder. Check subfolders enabled
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
{'subs': (
'RARBG.txt', 'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
)}
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
],
'allowed_extensions': 'nfo,srt',
'subfolders': True
},
])
def test_list_associated_files(p, create_structure, monkeypatch):
"""Run the test."""
# Given
test_path = create_structure(p['path'], structure=p['structure'])
path = os.path.join(test_path, os.path.normcase(p['path']))
file_path = os.path.join(path, p['structure'][0])
expected_associated_files = p['expected_associated_files']
subtitles_only = p.get('subtitles_only', False)
subfolders = p.get('subfolders', False)
refine = p.get('refine', False)
monkeypatch.setattr(app, 'ALLOWED_EXTENSIONS', p['allowed_extensions'])
monkeypatch.setattr(app, 'MOVE_ASSOCIATED_FILES', 1)
processor = PostProcessor(file_path)
processor._rar_basename = _rar_basename
# When
found_associated_files = processor.list_associated_files(file_path, subfolders=subfolders,
subtitles_only=subtitles_only, refine=refine)
associated_files_basenames = [os.path.basename(i) for i in found_associated_files]
# Then
assert set(associated_files_basenames) == set(expected_associated_files)
|
{
"pile_set_name": "Github"
}
|
namespace ImgCodec.IconAndCursor
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(31, 36);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(138, 38);
this.button1.TabIndex = 0;
this.button1.Text = "TestCursor1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(31, 80);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(138, 38);
this.button2.TabIndex = 1;
this.button2.Text = "TestCursor2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(262, 36);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(138, 38);
this.button4.TabIndex = 2;
this.button4.Text = "TestIcon1";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 603);
this.Controls.Add(this.button4);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button4;
}
}
|
{
"pile_set_name": "Github"
}
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Base Timer 0
namespace Bt4PwmTmcr{ ///<Timer Control Register
using Addr = Register::Address<0x4002520c,0xffff8080,0x00000000,unsigned>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> cks20{};
///Restart enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> rtgen{};
///Pulse output mask bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pmsk{};
///Trigger input edge selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> egs{};
///Timer function selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> fmd{};
///Output polarity specification bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> osel{};
///Mode selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> mdse{};
///Count operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cten{};
///Software trigger bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> strg{};
}
namespace Bt4PwmTmcr2{ ///<Timer Control Register 2
using Addr = Register::Address<0x40025211,0xfffffffe,0x00000000,unsigned char>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cks3{};
}
namespace Bt4PwmStc{ ///< Status Control Register
using Addr = Register::Address<0x40025210,0xffffff88,0x00000000,unsigned char>;
///Trigger interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tgie{};
///Duty match interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> dtie{};
///Underflow interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> udie{};
///Trigger interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tgir{};
///Duty match interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dtir{};
///Underflow interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> udir{};
}
namespace Bt4PwmPcsr{ ///<PWM Cycle Set Register
using Addr = Register::Address<0x40025200,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4PwmPdut{ ///<PWM Duty Set Register
using Addr = Register::Address<0x40025204,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4PwmTmr{ ///<Timer Register
using Addr = Register::Address<0x40025208,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4PpgTmcr{ ///<Timer Control Register
using Addr = Register::Address<0x4002520c,0xffff8080,0x00000000,unsigned>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> cks20{};
///Restart enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> rtgen{};
/// Pulse output mask bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pmsk{};
///Trigger input edge selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> egs{};
///Timer function selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> fmd{};
///Output polarity specification bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> osel{};
///Mode selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> mdse{};
///Count operation enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cten{};
///Software trigger bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> strg{};
}
namespace Bt4PpgTmcr2{ ///<Timer Control Register 2
using Addr = Register::Address<0x40025211,0xfffffffd,0x00000000,unsigned char>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cks3{};
}
namespace Bt4PpgStc{ ///<Status Control Register
using Addr = Register::Address<0x40025210,0xffffffaa,0x00000000,unsigned char>;
///Trigger interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tgie{};
///Underflow interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> udie{};
///Trigger interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tgir{};
///Underflow interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> udir{};
}
namespace Bt4PpgPrll{ ///<LOW Width Reload Register
using Addr = Register::Address<0x40025200,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4PpgPrlh{ ///<HIGH Width Reload Register
using Addr = Register::Address<0x40025204,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4PpgTmr{ ///<Timer Register
using Addr = Register::Address<0x40025208,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4RtTmcr{ ///<Timer Control Register
using Addr = Register::Address<0x4002520c,0xffff8c00,0x00000000,unsigned>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> cks20{};
///Trigger input edge selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> egs{};
///32-bit timer selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> t32{};
///Timer function selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> fmd{};
///Output polarity specification bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> osel{};
///Mode selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> mdse{};
///Timer enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cten{};
///Software trigger bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> strg{};
}
namespace Bt4RtTmcr2{ ///<Timer Control Register 2
using Addr = Register::Address<0x40025211,0xfffffffe,0x00000000,unsigned char>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cks3{};
}
namespace Bt4RtStc{ ///<Status Control Register
using Addr = Register::Address<0x40025210,0xffffffaa,0x00000000,unsigned char>;
///Trigger interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tgie{};
///Underflow interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> udie{};
///Trigger interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> tgir{};
///Underflow interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> udir{};
}
namespace Bt4RtPcsr{ ///<PWM Cycle Set Register
using Addr = Register::Address<0x40025200,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4RtTmr{ ///<Timer Register
using Addr = Register::Address<0x40025208,0xffffffff,0x00000000,unsigned>;
}
namespace Bt4PwcTmcr{ ///<Timer Control Register
using Addr = Register::Address<0x4002520c,0xffff8809,0x00000000,unsigned>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> cks20{};
///Measurement edge selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,unsigned> egs{};
///32-bit timer selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> t32{};
///Timer function selection bits
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> fmd{};
///Mode selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> mdse{};
///Timer enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cten{};
}
namespace Bt4PwcTmcr2{ ///<Timer Control Register 2
using Addr = Register::Address<0x40025211,0xfffffffe,0x00000000,unsigned char>;
///Count clock selection bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cks3{};
}
namespace Bt4PwcStc{ ///<Status Control Register
using Addr = Register::Address<0x40025210,0xffffff2a,0x00000000,unsigned char>;
///Error flag bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err{};
///Measurement completion interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> edie{};
///Overflow interrupt request enable bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ovie{};
///Measurement completion interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> edir{};
///Overflow interrupt request bit
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ovir{};
}
namespace Bt4PwcDtbf{ ///<Data Buffer Register
using Addr = Register::Address<0x40025204,0xffffffff,0x00000000,unsigned>;
}
}
|
{
"pile_set_name": "Github"
}
|
package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// DefaultSecurityRulesClient is the network Client
type DefaultSecurityRulesClient struct {
ManagementClient
}
// NewDefaultSecurityRulesClient creates an instance of the DefaultSecurityRulesClient client.
func NewDefaultSecurityRulesClient(subscriptionID string) DefaultSecurityRulesClient {
return NewDefaultSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewDefaultSecurityRulesClientWithBaseURI creates an instance of the DefaultSecurityRulesClient client.
func NewDefaultSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) DefaultSecurityRulesClient {
return DefaultSecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get get the specified default network security rule.
//
// resourceGroupName is the name of the resource group. networkSecurityGroupName is the name of the network security
// group. defaultSecurityRuleName is the name of the default security rule.
func (client DefaultSecurityRulesClient) Get(resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (result SecurityRule, err error) {
req, err := client.GetPreparer(resourceGroupName, networkSecurityGroupName, defaultSecurityRuleName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client DefaultSecurityRulesClient) GetPreparer(resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"defaultSecurityRuleName": autorest.Encode("path", defaultSecurityRuleName),
"networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client DefaultSecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client DefaultSecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all default security rules in a network security group.
//
// resourceGroupName is the name of the resource group. networkSecurityGroupName is the name of the network security
// group.
func (client DefaultSecurityRulesClient) List(resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResult, err error) {
req, err := client.ListPreparer(resourceGroupName, networkSecurityGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client DefaultSecurityRulesClient) ListPreparer(resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-09-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client DefaultSecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client DefaultSecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListNextResults retrieves the next set of results, if any.
func (client DefaultSecurityRulesClient) ListNextResults(lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) {
req, err := lastResults.SecurityRuleListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to next results request")
}
return
}
// ListComplete gets all elements from the list without paging.
func (client DefaultSecurityRulesClient) ListComplete(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (<-chan SecurityRule, <-chan error) {
resultChan := make(chan SecurityRule)
errChan := make(chan error, 1)
go func() {
defer func() {
close(resultChan)
close(errChan)
}()
list, err := client.List(resourceGroupName, networkSecurityGroupName)
if err != nil {
errChan <- err
return
}
if list.Value != nil {
for _, item := range *list.Value {
select {
case <-cancel:
return
case resultChan <- item:
// Intentionally left blank
}
}
}
for list.NextLink != nil {
list, err = client.ListNextResults(list)
if err != nil {
errChan <- err
return
}
if list.Value != nil {
for _, item := range *list.Value {
select {
case <-cancel:
return
case resultChan <- item:
// Intentionally left blank
}
}
}
}
}()
return resultChan, errChan
}
|
{
"pile_set_name": "Github"
}
|
function nn = nnff(nn, x, y)
%NNFF performs a feedforward pass
% nn = nnff(nn, x, y) returns an neural network structure with updated
% layer activations, error and loss (nn.a, nn.e and nn.L)
n = nn.n;
m = size(x, 1);
x = [ones(m,1) x];
nn.a{1} = x;
%feedforward pass
for i = 2 : n-1
switch nn.activation_function
case 'sigm'
% Calculate the unit's outputs (including the bias term)
nn.a{i} = sigm(nn.a{i - 1} * nn.W{i - 1}');
case 'tanh_opt'
nn.a{i} = tanh_opt(nn.a{i - 1} * nn.W{i - 1}');
end
%dropout
if(nn.dropoutFraction > 0)
if(nn.testing)
nn.a{i} = nn.a{i}.*(1 - nn.dropoutFraction);
else
nn.dropOutMask{i} = (rand(size(nn.a{i}))>nn.dropoutFraction);
nn.a{i} = nn.a{i}.*nn.dropOutMask{i};
end
end
%calculate running exponential activations for use with sparsity
if(nn.nonSparsityPenalty>0)
nn.p{i} = 0.99 * nn.p{i} + 0.01 * mean(nn.a{i}, 1);
end
%Add the bias term
nn.a{i} = [ones(m,1) nn.a{i}];
end
switch nn.output
case 'sigm'
nn.a{n} = sigm(nn.a{n - 1} * nn.W{n - 1}');
case 'linear'
nn.a{n} = nn.a{n - 1} * nn.W{n - 1}';
case 'softmax'
nn.a{n} = nn.a{n - 1} * nn.W{n - 1}';
nn.a{n} = exp(bsxfun(@minus, nn.a{n}, max(nn.a{n},[],2)));
nn.a{n} = bsxfun(@rdivide, nn.a{n}, sum(nn.a{n}, 2));
end
%error and loss
nn.e = y - nn.a{n};
switch nn.output
case {'sigm', 'linear'}
nn.L = 1/2 * sum(sum(nn.e .^ 2)) / m;
case 'softmax'
nn.L = -sum(sum(y .* log(nn.a{n}))) / m;
end
end
|
{
"pile_set_name": "Github"
}
|
namespace AcademyGeometry
{
using System;
using System.Linq;
class Cylinder : Figure, IAreaMeasurable, IVolumeMeasurable
{
public Cylinder(Vector3D bottom, Vector3D top, double radius)
: base(bottom, top)
{
this.Radius = radius;
}
public double Radius { get; private set; }
public Vector3D Top
{
get { return new Vector3D(this.vertices[0].X, this.vertices[0].Y, this.vertices[0].Z); }
private set { this.vertices[0] = new Vector3D(value.X, value.Y, value.Z); }
}
public Vector3D Bottom
{
get { return new Vector3D(this.vertices[1].X, this.vertices[1].Y, this.vertices[1].Z); }
private set { this.vertices[1] = new Vector3D(value.X, value.Y, value.Z); }
}
public double GetVolume()
{
return Math.PI * this.Radius * this.Radius * (this.Top - this.Bottom).Magnitude;
}
public double GetArea()
{
double baseArea = Math.PI * this.Radius * this.Radius;
double topAndBottomArea = baseArea * 2;
double basePerimeter = 2 * Math.PI * this.Radius;
double sideArea = basePerimeter * (this.Top - this.Bottom).Magnitude;
return sideArea + topAndBottomArea;
}
public override double GetPrimaryMeasure()
{
return this.GetVolume();
}
}
}
|
{
"pile_set_name": "Github"
}
|
const test = require("ava");
const TemplateRender = require("../src/TemplateRender");
const EleventyExtensionMap = require("../src/EleventyExtensionMap");
function getNewTemplateRender(name, inputDir) {
let tr = new TemplateRender(name, inputDir);
tr.extensionMap = new EleventyExtensionMap();
return tr;
}
// Mustache
test("Mustache", async (t) => {
t.is(getNewTemplateRender("mustache").getEngineName(), "mustache");
});
test("Mustache Render", async (t) => {
let fn = await getNewTemplateRender("mustache").getCompiledTemplate(
"<p>{{name}}</p>"
);
t.is(await fn({ name: "Zach" }), "<p>Zach</p>");
});
test("Mustache Render Partial (raw text content)", async (t) => {
let fn = await getNewTemplateRender(
"mustache",
"./test/stubs/"
).getCompiledTemplate("<p>{{> included}}</p>");
t.is(await fn(), "<p>This is an include.</p>");
});
test.skip("Mustache Render Partial (relative path, raw text content)", async (t) => {
let fn = await getNewTemplateRender(
"./test/stubs/does_not_exist_and_thats_ok.mustache",
"./test/stubs/"
).getCompiledTemplate("<p>{{> ./includedrelative}}</p>");
t.is(await fn(), "<p>This is an includdde.</p>");
});
test("Mustache Render Partial (uses a variable in content)", async (t) => {
let fn = await getNewTemplateRender(
"mustache",
"./test/stubs/"
).getCompiledTemplate("<p>{{> includedvar}}</p>");
t.is(await fn({ name: "Zach" }), "<p>This is a Zach.</p>");
});
test("Mustache Render Partial (Subdirectory)", async (t) => {
let fn = await getNewTemplateRender(
"mustache",
"./test/stubs/"
).getCompiledTemplate("<p>{{> subfolder/included}}</p>");
t.is(await fn({ name: "Zach" }), "<p>This is an include.</p>");
});
test("Mustache Render: with Library Override", async (t) => {
let tr = getNewTemplateRender("mustache");
let lib = require("mustache");
tr.engine.setLibrary(lib);
let fn = await tr.getCompiledTemplate("<p>{{name}}</p>");
t.is(await fn({ name: "Zach" }), "<p>Zach</p>");
});
test("Mustache Render Unescaped Output (no HTML)", async (t) => {
let fn = await getNewTemplateRender("mustache").getCompiledTemplate(
"<p>{{{name}}}</p>"
);
t.is(await fn({ name: "Zach" }), "<p>Zach</p>");
});
test("Mustache Render Escaped Output", async (t) => {
let fn = await getNewTemplateRender("mustache").getCompiledTemplate(
"<p>{{name}}</p>"
);
t.is(
await fn({ name: "<b>Zach</b>" }),
"<p><b>Zach</b></p>"
);
});
test("Mustache Render Unescaped Output (HTML)", async (t) => {
let fn = await getNewTemplateRender("mustache").getCompiledTemplate(
"<p>{{{name}}}</p>"
);
t.is(await fn({ name: "<b>Zach</b>" }), "<p><b>Zach</b></p>");
});
|
{
"pile_set_name": "Github"
}
|
{{ partial "header.html" . }}
<div class="main-container">
<section class="space--xs ">
<div class="container">
<div class="row">
<div class="col-md-12">
<span class="h2 inline-block">Articles & News</span>
<!--
<div class="typed-headline">
<span class="h2 inline-block">Hue helps you</span>
<span class="h2 inline-block typed-text typed-text--cursor color--primary" data-typed-strings="discover insights.,write SQL.,visualize data."></span>
</div>
-->
</div>
</div>
</div>
</section>
<section class="text-center space--xs ">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="masonry-filter-container d-flex align-items-center">
<span>Category:</span>
<div class="masonry-filter-holder">
<div class="masonry__filters">
<ul>
{{ $currentUrl := .URL }}
{{if eq $currentUrl `/posts/`}}
<li class="active"><a href="/posts">All Categories</a></li>
{{else}}
<li class="active">{{ .Title }}</li>
<li><a href="/posts">All Categories</a></li>
{{end}}
{{ range $key, $value := .Site.Taxonomies.categories }}
<li><a href="/categories/{{ $key | urlize }}">{{ $key | humanize }}</a> ({{ len $value }})</li>
{{ end }}
</ul>
</div>
</div>
</div>
<hr>
</div>
</div>
</div>
<!--end of container-->
</section>
{{ $paginator := .Paginate (where .Data.Pages "Type" "post") }}
{{ range $paginator.Pages }}
<section class="space--xs blog-article-wide">
<div class="container">
<div class="row cta cta--horizontal text-center-xs">
<div class="col-md-3">
<h4>{{ .Date.Format "02 January 2006" }}</h4>
</div>
<div class="col-md-6">
<a href="{{ .Permalink }}">
<p class="lead">
{{ .Title }}
</p>
</a>
<p class="mt-2">{{ .Summary }}{{ if .Truncated }}…{{ end }}</p>
{{ $read := .ReadingTime }}
<span>{{ .ReadingTime }} minute{{ if gt $read 1 }}s{{ end }} read</span> -
{{ $categories := .Params.categories }}
{{ range $index, $element := $categories }}
<a href="{{ "/categories/" | relLangURL }}{{ $element | urlize }}">{{ $element }}</a>
{{ if (ne (add $index 1) (len $categories)) }}
/
{{ end }}
{{ end }}
</div>
<div class="col-md-3 text-right text-center-xs">
<a class="btn type--uppercase" href="{{ .Permalink }}">
<span class="btn__text">
Read Article
</span>
</a>
</div>
</div>
<!--end of row-->
</div>
<!--end of container-->
</section>
{{ end }}
<section>
<div class="container">
<div class="row">
<div class="col-md-12">
{{ $pag := $.Paginator }}
{{ if gt $pag.TotalPages 1 }}
<div class="pagination">
{{ with $pag.First }}
<a class="pagination__prev" href="{{ .URL }}" title="First Page">««</a>
{{ end }}
<!-- {{ if $pag.HasPrev }}
<a class="pagination__prev ml-5" href="{{ $pag.Prev.URL }}" title="Previous Page">«</a>
{{ end }} -->
<ol>
{{ $ellipsed := false }}
{{ $shouldEllipse := false }}
{{ range $pag.Pagers }}
{{ $right := sub .TotalPages .PageNumber }}
{{ $showNumber := or (le .PageNumber 3) (eq $right 0) }}
{{ $showNumber := or $showNumber (and (gt .PageNumber (sub $pag.PageNumber 2)) (lt .PageNumber (add $pag.PageNumber 2))) }}
{{ if $showNumber }}
{{ $ellipsed = false }}
{{ $shouldEllipse = false }}
{{ else }}
{{ $shouldEllipse = not $ellipsed }}
{{ $ellipsed = true }}
{{ end }}
{{ if $showNumber }}
<li class="{{ if eq . $pag }}pagination__current{{ end }}"><a href="{{ .URL }}">{{ .PageNumber }}</a></li>
{{ else if $shouldEllipse }}
<li class="page-item disabled"><span aria-hidden="true"> … </span></li>
{{ end }}
{{ end }}
</ol>
<!-- {{ if $pag.HasNext }}
<a class="pagination__next mr-5" href="{{ $pag.Next.URL }}" title="Next Page">»</a>
{{ end }} -->
{{ with $pag.Last }}
<a class="pagination__next" href="{{ .URL }}" title="Last Page">»»</a>
{{ end }}
</div>
{{ end }}
</div>
</div>
<!--end of row-->
</div>
<!--end of container-->
</section>
{{ partial "latest.html" . }}
</div>
{{ partial "footer.html" . }}
|
{
"pile_set_name": "Github"
}
|
// OsmSharp - OpenStreetMap (OSM) SDK
// Copyright (C) 2013 Abelshausen Ben
//
// This file is part of OsmSharp.
//
// OsmSharp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// OsmSharp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OsmSharp. If not, see <http://www.gnu.org/licenses/>.
using OsmSharp.Logging;
#if __UNIFIED__
using UIKit;
#else
using MonoTouch.UIKit;
using Foundation = MonoTouch.Foundation;
#endif
namespace OsmSharp.iOS.UI.Log
{
/// <summary>
/// A log trace listener that writes message to a given text view.
/// </summary>
public class TextViewTraceListener : TraceListener
{
/// <summary>
/// Holds the textview to write to.
/// </summary>
private UITextView _textView;
/// <summary>
/// Creates a new text view trace listener.
/// </summary>
/// <param name="textView"></param>
public TextViewTraceListener(UITextView textView)
{
_textView = textView;
}
/// <summary>
/// Writes the given message to the textview.
/// </summary>
/// <param name="message"></param>
public override void Write(string message)
{
_textView.InvokeOnMainThread(() =>
{
_textView.Text = _textView.Text + message;
_textView.ScrollRangeToVisible(
new Foundation.NSRange(_textView.Text.Length, 0));
});
}
/// <summary>
/// Writes the given message to the textview.
/// </summary>
/// <param name="message"></param>
public override void WriteLine(string message)
{
_textView.InvokeOnMainThread(() =>
{
_textView.Text = _textView.Text + message + System.Environment.NewLine;
_textView.ScrollRangeToVisible(
new Foundation.NSRange(_textView.Text.Length, 0));
});
}
}
}
|
{
"pile_set_name": "Github"
}
|
#pragma warning disable
/*
* Warewolf - Once bitten, there's no going back
* Copyright 2019 by Warewolf Ltd <alpha@warewolf.io>
* Licensed under GNU Affero General Public License 3.0 or later.
* Some rights reserved.
* Visit our website for more information <http://warewolf.io/>
* AUTHORS <http://warewolf.io/authors.php> , CONTRIBUTORS <http://warewolf.io/contributors.php>
* @license GNU Affero General Public License <http://www.gnu.org/licenses/agpl-3.0.html>
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Dev2.Common.DateAndTime;
using Dev2.Common.Interfaces.Core.Convertors.DateAndTime;
using Dev2.Data.Interfaces;
using Dev2.Data.Interfaces.Enums;
using Dev2.DataList.Contract;
using Dev2.Intellisense.Provider;
using Dev2.Studio.Interfaces;
namespace Dev2.Studio.InterfaceImplementors
{
public class DateTimeIntellisenseProvider : IIntellisenseProvider
{
#region Class Members
List<IIntellisenseResult> _intellisenseResults;
#endregion Class Members
#region Constructors
public DateTimeIntellisenseProvider()
{
Optional = false;
IntellisenseProviderType = IntellisenseProviderType.NonDefault;
var dateTimeParser = DateTimeConverterFactory.CreateStandardParser();
_intellisenseResults = dateTimeParser.DateTimeFormatParts.Select(p =>
{
var intellisenseResult = IntellisenseFactory.CreateDateTimeResult(IntellisenseFactory.CreateDateTimePart(p.Value, p.Description));
return intellisenseResult;
}).OrderBy(p => p.Option.DisplayValue).ToList();
}
public DateTimeIntellisenseProvider(List<IIntellisenseResult> intellisenseResults)
{
Optional = false;
_intellisenseResults = intellisenseResults;
}
#endregion Constructors
#region Override Methods
public IntellisenseProviderType IntellisenseProviderType { get; private set; }
public string PerformResultInsertion(string input, IntellisenseProviderContext context)
{
throw new NotSupportedException();
}
public IList<IntellisenseProviderResult> GetIntellisenseResults(IntellisenseProviderContext context)
{
if(context == null)
{
return new List<IntellisenseProviderResult>();
}
var oldResults = GetIntellisenseResultsImpl(context);
var results = new List<IntellisenseProviderResult>();
if (oldResults != null)
{
foreach (IIntellisenseResult currentResult in oldResults)
{
if (currentResult.ErrorCode != enIntellisenseErrorCode.None && currentResult.Type == enIntellisenseResultType.Error && currentResult.IsClosedRegion)
{
results.Add(new IntellisenseProviderResult(this, currentResult.Option.DisplayValue, currentResult.Message, currentResult.Message, true));
}
if (currentResult.Type == enIntellisenseResultType.Selectable)
{
results.Add(new IntellisenseProviderResult(this, currentResult.Option.DisplayValue, currentResult.Option.Description, currentResult.Option.Description, false));
}
}
}
return results;
}
public IList<IIntellisenseResult> GetIntellisenseResultsImpl(IntellisenseProviderContext context)
{
var searchText = context.FindTextToSearch();
var results = new List<IIntellisenseResult>();
if (context.DesiredResultSet == IntellisenseDesiredResultSet.EntireSet)
{
results.AddRange(IntellisenseResults);
}
else
{
if (!InLiteralRegion(context.InputText, context.CaretPosition))
{
var filteredResults = IntellisenseResults.Where(i => i.Option.DisplayValue.ToLower(System.Globalization.CultureInfo.CurrentCulture).StartsWith(searchText.ToLower(System.Globalization.CultureInfo.CurrentCulture)));
results.AddRange(filteredResults);
}
}
return results;
}
public void Dispose()
{
_intellisenseResults = null;
}
#endregion Override Methods
#region Private Methods
/// <summary>
/// Determines if the caret in a literal region
/// </summary>
public static bool InLiteralRegion(string inputText, int caretPosition)
{
var inLiteralRegion = false;
var text = inputText;
if (caretPosition <= text.Length)
{
text = text.Replace("\\\\", "##").Replace("\\'", "##").Replace("'''", "###");
inLiteralRegion = text.Substring(0, caretPosition).Count(s => s == '\'') % 2 != 0;
}
return inLiteralRegion;
}
#endregion Private Methods
#region Properties
public bool Optional { get; set; }
public bool HandlesResultInsertion { get; set; }
public List<IIntellisenseResult> IntellisenseResults => _intellisenseResults;
#endregion Properties
}
}
|
{
"pile_set_name": "Github"
}
|
/*
MIT License
Copyright (c) 2016-2017 Florian Cäsar, Michael Plainer
For full license see LICENSE in the root directory of this project.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Sigma.Core.Handlers;
using Sigma.Core.MathAbstract;
using Sigma.Core.Utils;
namespace Sigma.Core.Training.Hooks.Scorers
{
/// <summary>
/// A multi-class classification accuracy scorer that scores model predictions against their targets with topx accuracy (e.g. top1, top3 and top10).
/// </summary>
[Serializable]
public class MultiClassificationAccuracyScorer : BaseAccuracyScorer
{
/// <summary>
/// Create a multi-class classification accuracy scorer hook for a certain validation iterator.
/// Note: The "external_default" output may not always be the actual final output in your model.
/// If your model contains multiple output you may need to explicitly specify the actual final output with this alias.
/// </summary>
/// <param name="validationIteratorName">The validation data iterator name (as in the trainer).</param>
/// <param name="resultBaseKey">The base key under which the results will be available (base entry + tops[i]).</param>
/// <param name="tops">The tops that should be scored (e.g. top 1, top 3, top5).</param>
/// <param name="timestep">The time step.</param>
public MultiClassificationAccuracyScorer(string validationIteratorName, string resultBaseKey, ITimeStep timestep, params int[] tops) : base(validationIteratorName, timestep)
{
if (tops == null) throw new ArgumentNullException(nameof(tops));
if (tops.Length == 0) throw new ArgumentException($"The tops must be of length > 0 (otherwise what should be scored? It doesn't make sense).");
ParameterRegistry["tops"] = tops;
ParameterRegistry["result_base_key"] = resultBaseKey;
}
/// <summary>
/// Begin a validation scoring session.
/// Reset the scoring here.
/// </summary>
/// <param name="registry">The registry containing the required values for this hook's execution.</param>
/// <param name="resolver">A helper resolver for complex registry entries (automatically cached).</param>
protected override void ScoreBegin(IRegistry registry, IRegistryResolver resolver)
{
int[] tops = ParameterRegistry.Get<int[]>("tops");
foreach (int t in tops)
{
ParameterRegistry[$"correct_classifications_top{t}"] = 0;
}
ParameterRegistry["total_classifications"] = 0;
}
/// <summary>
/// Score an intermediate result (part of the entire validation dataset was used as specified by the validation iterator).
/// </summary>
/// <param name="predictions">The predictions.</param>
/// <param name="targets">The targets.</param>
/// <param name="handler">The computation handler.</param>
protected override void ScoreIntermediate(INDArray predictions, INDArray targets, IComputationHandler handler)
{
predictions = handler.FlattenTimeAndFeatures(predictions);
if (predictions.Shape[1] <= 1)
{
throw new InvalidOperationException($"Cannot score multi-class classification accuracy on targets with less than 2 feature indices (there were {predictions.Shape[1]}.");
}
int[] tops = ParameterRegistry.Get<int[]>("tops");
predictions = handler.RowWise(predictions, handler.SoftMax);
var perRowTopPredictions = handler.RowWiseTransform(predictions,
row => row.GetDataAs<double>().Data.Select((x, i) => new KeyValuePair<double, int>(x, i)).OrderByDescending(x => x.Key).Select(p => p.Value).ToArray()).ToList();
int[] targetIndices = handler.RowWiseTransform(handler.FlattenTimeAndFeatures(targets), handler.MaxIndex);
foreach (int top in tops)
{
int correctClassifications = perRowTopPredictions.Where((rowPredictions, rowIndex) => rowPredictions.Take(top).Any(predicted => predicted == targetIndices[rowIndex])).Count();
ParameterRegistry[$"correct_classifications_top{top}"] = ParameterRegistry.Get<int>($"correct_classifications_top{top}") + correctClassifications;
}
ParameterRegistry["total_classifications"] = ParameterRegistry.Get<int>("total_classifications") + targetIndices.Length;
}
/// <summary>
/// End a validation scoring session.
/// Write out results here.
/// </summary>
/// <param name="registry">The registry containing the required values for this hook's execution.</param>
/// <param name="resolver">A helper resolver for complex registry entries (automatically cached).</param>
protected override void ScoreEnd(IRegistry registry, IRegistryResolver resolver)
{
int[] tops = ParameterRegistry.Get<int[]>("tops");
foreach (int top in tops)
{
string resultBaseKey = ParameterRegistry.Get<string>("result_base_key");
int totalClassifications = ParameterRegistry.Get<int>("total_classifications");
int correctClassifications = ParameterRegistry.Get<int>($"correct_classifications_top{top}");
double score = ((double) correctClassifications) / totalClassifications;
resolver.ResolveSet(resultBaseKey + top, score, addIdentifierIfNotExists: true);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
import pytest
import pandas as pd
from pandas import TimedeltaIndex
class TestTimedeltaIndexRendering(object):
@pytest.mark.parametrize('method', ['__repr__', '__unicode__', '__str__'])
def test_representation(self, method):
idx1 = TimedeltaIndex([], freq='D')
idx2 = TimedeltaIndex(['1 days'], freq='D')
idx3 = TimedeltaIndex(['1 days', '2 days'], freq='D')
idx4 = TimedeltaIndex(['1 days', '2 days', '3 days'], freq='D')
idx5 = TimedeltaIndex(['1 days 00:00:01', '2 days', '3 days'])
exp1 = """TimedeltaIndex([], dtype='timedelta64[ns]', freq='D')"""
exp2 = ("TimedeltaIndex(['1 days'], dtype='timedelta64[ns]', "
"freq='D')")
exp3 = ("TimedeltaIndex(['1 days', '2 days'], "
"dtype='timedelta64[ns]', freq='D')")
exp4 = ("TimedeltaIndex(['1 days', '2 days', '3 days'], "
"dtype='timedelta64[ns]', freq='D')")
exp5 = ("TimedeltaIndex(['1 days 00:00:01', '2 days 00:00:00', "
"'3 days 00:00:00'], dtype='timedelta64[ns]', freq=None)")
with pd.option_context('display.width', 300):
for idx, expected in zip([idx1, idx2, idx3, idx4, idx5],
[exp1, exp2, exp3, exp4, exp5]):
result = getattr(idx, method)()
assert result == expected
def test_representation_to_series(self):
idx1 = TimedeltaIndex([], freq='D')
idx2 = TimedeltaIndex(['1 days'], freq='D')
idx3 = TimedeltaIndex(['1 days', '2 days'], freq='D')
idx4 = TimedeltaIndex(['1 days', '2 days', '3 days'], freq='D')
idx5 = TimedeltaIndex(['1 days 00:00:01', '2 days', '3 days'])
exp1 = """Series([], dtype: timedelta64[ns])"""
exp2 = ("0 1 days\n"
"dtype: timedelta64[ns]")
exp3 = ("0 1 days\n"
"1 2 days\n"
"dtype: timedelta64[ns]")
exp4 = ("0 1 days\n"
"1 2 days\n"
"2 3 days\n"
"dtype: timedelta64[ns]")
exp5 = ("0 1 days 00:00:01\n"
"1 2 days 00:00:00\n"
"2 3 days 00:00:00\n"
"dtype: timedelta64[ns]")
with pd.option_context('display.width', 300):
for idx, expected in zip([idx1, idx2, idx3, idx4, idx5],
[exp1, exp2, exp3, exp4, exp5]):
result = repr(pd.Series(idx))
assert result == expected
def test_summary(self):
# GH#9116
idx1 = TimedeltaIndex([], freq='D')
idx2 = TimedeltaIndex(['1 days'], freq='D')
idx3 = TimedeltaIndex(['1 days', '2 days'], freq='D')
idx4 = TimedeltaIndex(['1 days', '2 days', '3 days'], freq='D')
idx5 = TimedeltaIndex(['1 days 00:00:01', '2 days', '3 days'])
exp1 = ("TimedeltaIndex: 0 entries\n"
"Freq: D")
exp2 = ("TimedeltaIndex: 1 entries, 1 days to 1 days\n"
"Freq: D")
exp3 = ("TimedeltaIndex: 2 entries, 1 days to 2 days\n"
"Freq: D")
exp4 = ("TimedeltaIndex: 3 entries, 1 days to 3 days\n"
"Freq: D")
exp5 = ("TimedeltaIndex: 3 entries, 1 days 00:00:01 to 3 days "
"00:00:00")
for idx, expected in zip([idx1, idx2, idx3, idx4, idx5],
[exp1, exp2, exp3, exp4, exp5]):
result = idx._summary()
assert result == expected
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for Truthcoin's mathematical tools.
"""
from __future__ import division, unicode_literals, absolute_import
import os
import sys
import platform
import numpy as np
import numpy.ma as ma
if platform.python_version() < "2.7":
unittest = __import__("unittest2")
else:
import unittest
HERE = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(HERE, os.pardir))
import custommath as custom
class TestCustommath(unittest.TestCase):
def setUp(self):
self.votes = np.array([[1, 1, 0, 0],
[1, 0, 0, 0],
[1, 1, 0, 0],
[1, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]])
self.votes = ma.masked_array(self.votes, np.isnan(self.votes))
self.c = [1, 2, 3, np.nan, 3]
self.c2 = ma.masked_array(self.c, np.isnan(self.c))
self.c3 = [2, 3, -1, 4, 0]
def test_WeightedMedian(self):
data = [
[7, 1, 2, 4, 10],
[7, 1, 2, 4, 10],
[7, 1, 2, 4, 10, 15],
[1, 2, 4, 7, 10, 15],
[0, 10, 20, 30],
[1, 2, 3, 4, 5],
[30, 40, 50, 60, 35],
[2, 0.6, 1.3, 0.3, 0.3, 1.7, 0.7, 1.7, 0.4],
]
weights = [
[1, 1/3, 1/3, 1/3, 1],
[1, 1, 1, 1, 1],
[1, 1/3, 1/3, 1/3, 1, 1],
[1/3, 1/3, 1/3, 1, 1, 1],
[30, 191, 9, 0],
[10, 1, 1, 1, 9],
[1, 3, 5, 4, 2],
[2, 2, 0, 1, 2, 2, 1, 6, 0],
]
answers = [7, 4, 8.5, 8.5, 10, 2.5, 50, 1.7]
for datum, weight, answer in zip(data, weights, answers):
self.assertEqual(custom.WeightedMedian(datum, weight), answer)
def test_MeanNa(self):
expected = [1.0, 2.0, 3.0, 2.25, 3.0]
actual = custom.MeanNa(self.c2)
self.assertListEqual(list(actual.base), expected)
def test_Catch(self):
expected = [0, 1, 0.5, 0]
actual = [custom.Catch(0.4),
custom.Catch(0.6),
custom.Catch(0.4, 0.3),
custom.Catch(0.4, 0.1)]
self.assertEqual(actual, expected)
def test_Influence(self):
expected = [np.array([0.88888889]),
np.array([1.33333333]),
np.array([1.]),
np.array([1.33333333])]
actual = custom.Influence(custom.GetWeight(self.c2))
result = []
for i in range(len(actual)):
result.append((actual[i] - expected[i])**2)
self.assertLess(sum(result), 0.000000000001)
def test_ReWeight(self):
expected = [0.08888888888888889,
0.17777777777777778,
0.26666666666666666,
0.2,
0.26666666666666666]
custom.MeanNa(self.c2)
actual = custom.ReWeight(self.c2)
self.assertListEqual(expected, list(actual.base))
def test_ReverseMatrix(self):
expected = np.array([[0, 0, 1, 1],
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 1, 0, 0],
[1, 1, 0, 0]])
actual = custom.ReverseMatrix(self.votes)
self.assertEqual(np.sum(expected == actual), 24)
def test_WeightedPrinComp(self):
expected = np.array([-0.81674714,
-0.35969107,
-0.81674714,
-0.35969107,
1.17643821,
1.17643821])
actual = custom.WeightedPrinComp(self.votes)[1]
result = []
for i in range(len(actual)):
result.append((actual[i] - expected[i])**2)
self.assertLess(sum(result), 0.000000000001)
def tearDown(self):
del self.votes
del self.c
del self.c2
del self.c3
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(TestCustommath)
unittest.TextTestRunner(verbosity=2).run(suite)
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TOOLS_JSON_SCHEMA_COMPILER_UTIL_H_
#define TOOLS_JSON_SCHEMA_COMPILER_UTIL_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/values.h"
namespace json_schema_compiler {
namespace util {
// Populates the item |out| from the value |from|. These are used by template
// specializations of |Get(Optional)ArrayFromList|.
bool PopulateItem(const base::Value& from, std::unique_ptr<base::Value>* out);
bool PopulateItem(const base::Value& from, int* out);
bool PopulateItem(const base::Value& from, int* out, base::string16* error);
bool PopulateItem(const base::Value& from, bool* out);
bool PopulateItem(const base::Value& from, bool* out, base::string16* error);
bool PopulateItem(const base::Value& from, double* out);
bool PopulateItem(const base::Value& from, double* out, base::string16* error);
bool PopulateItem(const base::Value& from, std::string* out);
bool PopulateItem(const base::Value& from,
std::string* out,
base::string16* error);
bool PopulateItem(const base::Value& from, std::vector<char>* out);
bool PopulateItem(const base::Value& from,
std::vector<char>* out,
base::string16* error);
bool PopulateItem(const base::Value& from,
std::unique_ptr<base::Value>* out,
base::string16* error);
bool PopulateItem(const base::Value& from, std::unique_ptr<base::Value>* out);
// This template is used for types generated by tools/json_schema_compiler.
template <class T>
bool PopulateItem(const base::Value& from, std::unique_ptr<T>* out) {
const base::DictionaryValue* dict = nullptr;
if (!from.GetAsDictionary(&dict))
return false;
std::unique_ptr<T> obj(new T());
if (!T::Populate(*dict, obj.get()))
return false;
*out = std::move(obj);
return true;
}
// This template is used for types generated by tools/json_schema_compiler.
template <class T>
bool PopulateItem(const base::Value& from, T* out) {
const base::DictionaryValue* dict = nullptr;
if (!from.GetAsDictionary(&dict))
return false;
T obj;
if (!T::Populate(*dict, &obj))
return false;
*out = std::move(obj);
return true;
}
// This template is used for types generated by tools/json_schema_compiler with
// error generation enabled.
template <class T>
bool PopulateItem(const base::Value& from,
std::unique_ptr<T>* out,
base::string16* error) {
const base::DictionaryValue* dict = nullptr;
if (!from.GetAsDictionary(&dict))
return false;
std::unique_ptr<T> obj(new T());
if (!T::Populate(*dict, obj.get(), error))
return false;
*out = std::move(obj);
return true;
}
// This template is used for types generated by tools/json_schema_compiler with
// error generation enabled.
template <class T>
bool PopulateItem(const base::Value& from, T* out, base::string16* error) {
const base::DictionaryValue* dict = nullptr;
if (!from.GetAsDictionary(&dict))
return false;
T obj;
if (!T::Populate(*dict, &obj, error))
return false;
*out = std::move(obj);
return true;
}
// Populates |out| with |list|. Returns false if there is no list at the
// specified key or if the list has anything other than |T|.
template <class T>
bool PopulateArrayFromList(const base::ListValue& list, std::vector<T>* out) {
out->clear();
T item;
for (const auto& value : list) {
if (!PopulateItem(*value, &item))
return false;
// T might not be movable, but in that case it should be copyable, and this
// will still work.
out->push_back(std::move(item));
}
return true;
}
// Populates |out| with |list|. Returns false and sets |error| if there is no
// list at the specified key or if the list has anything other than |T|.
template <class T>
bool PopulateArrayFromList(const base::ListValue& list,
std::vector<T>* out,
base::string16* error) {
out->clear();
T item;
for (const auto& value : list) {
if (!PopulateItem(*value, &item, error))
return false;
out->push_back(std::move(item));
}
return true;
}
// Creates a new vector containing |list| at |out|. Returns
// true on success or if there is nothing at the specified key. Returns false
// if anything other than a list of |T| is at the specified key.
template <class T>
bool PopulateOptionalArrayFromList(const base::ListValue& list,
std::unique_ptr<std::vector<T>>* out) {
out->reset(new std::vector<T>());
if (!PopulateArrayFromList(list, out->get())) {
out->reset();
return false;
}
return true;
}
template <class T>
bool PopulateOptionalArrayFromList(const base::ListValue& list,
std::unique_ptr<std::vector<T>>* out,
base::string16* error) {
out->reset(new std::vector<T>());
if (!PopulateArrayFromList(list, out->get(), error)) {
out->reset();
return false;
}
return true;
}
// Appends a Value newly created from |from| to |out|. These used by template
// specializations of |Set(Optional)ArrayToList|.
void AddItemToList(const int from, base::ListValue* out);
void AddItemToList(const bool from, base::ListValue* out);
void AddItemToList(const double from, base::ListValue* out);
void AddItemToList(const std::string& from, base::ListValue* out);
void AddItemToList(const std::vector<char>& from, base::ListValue* out);
void AddItemToList(const std::unique_ptr<base::Value>& from,
base::ListValue* out);
void AddItemToList(const std::unique_ptr<base::DictionaryValue>& from,
base::ListValue* out);
// This template is used for types generated by tools/json_schema_compiler.
template <class T>
void AddItemToList(const std::unique_ptr<T>& from, base::ListValue* out) {
out->Append(from->ToValue());
}
// This template is used for types generated by tools/json_schema_compiler.
template <class T>
void AddItemToList(const T& from, base::ListValue* out) {
out->Append(from.ToValue());
}
// Set |out| to the the contents of |from|. Requires PopulateItem to be
// implemented for |T|.
template <class T>
void PopulateListFromArray(const std::vector<T>& from, base::ListValue* out) {
out->Clear();
for (const T& item : from)
AddItemToList(item, out);
}
// Set |out| to the the contents of |from| if |from| is not null. Requires
// PopulateItem to be implemented for |T|.
template <class T>
void PopulateListFromOptionalArray(const std::unique_ptr<std::vector<T>>& from,
base::ListValue* out) {
if (from)
PopulateListFromArray(*from, out);
}
template <class T>
std::unique_ptr<base::Value> CreateValueFromArray(const std::vector<T>& from) {
std::unique_ptr<base::ListValue> list(new base::ListValue());
PopulateListFromArray(from, list.get());
return std::move(list);
}
template <class T>
std::unique_ptr<base::Value> CreateValueFromOptionalArray(
const std::unique_ptr<std::vector<T>>& from) {
return from ? CreateValueFromArray(*from) : nullptr;
}
} // namespace util
} // namespace json_schema_compiler
#endif // TOOLS_JSON_SCHEMA_COMPILER_UTIL_H_
|
{
"pile_set_name": "Github"
}
|
// OpenTween - Client of Twitter
// Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
// (c) 2008-2011 Moz (@syo68k)
// (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
// (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
// (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
// (c) 2011 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
// All rights reserved.
//
// This file is part of OpenTween.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>, or write to
// the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
// Boston, MA 02110-1301, USA.
#nullable enable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenTween.Api;
using OpenTween.Connection;
using OpenTween.Api.DataModel;
namespace OpenTween
{
public partial class MyLists : OTBaseForm
{
private readonly TwitterApi twitterApi = null!;
private readonly string contextScreenName = null!;
/// <summary>自分が所有しているリスト</summary>
private ListElement[] ownedLists = Array.Empty<ListElement>();
/// <summary>操作対象のユーザーが追加されているリストのID</summary>
private long[] addedListIds = Array.Empty<long>();
public MyLists()
=> this.InitializeComponent();
public MyLists(string screenName, TwitterApi twitterApi)
{
this.InitializeComponent();
this.twitterApi = twitterApi;
this.contextScreenName = screenName;
this.Text = screenName + Properties.Resources.MyLists1;
}
private async Task RefreshListBox()
{
using (var dialog = new WaitingDialog(Properties.Resources.ListsGetting))
{
var cancellationToken = dialog.EnableCancellation();
var task = Task.Run(() => this.FetchMembershipListIds());
await dialog.WaitForAsync(this, task);
cancellationToken.ThrowIfCancellationRequested();
}
using (ControlTransaction.Update(this.ListsCheckedListBox))
{
this.ListsCheckedListBox.Items.Clear();
foreach (var list in this.ownedLists)
{
var added = this.addedListIds.Contains(list.Id);
this.ListsCheckedListBox.Items.Add(list, isChecked: added);
}
}
}
private async Task FetchMembershipListIds()
{
var ownedListData = await TwitterLists.GetAllItemsAsync(x =>
this.twitterApi.ListsOwnerships(this.twitterApi.CurrentScreenName, cursor: x, count: 1000))
.ConfigureAwait(false);
this.ownedLists = ownedListData.Select(x => new ListElement(x, null!)).ToArray();
var listsUserAddedTo = await TwitterLists.GetAllItemsAsync(x =>
this.twitterApi.ListsMemberships(this.contextScreenName, cursor: x, count: 1000, filterToOwnedLists: true))
.ConfigureAwait(false);
this.addedListIds = listsUserAddedTo.Select(x => x.Id).ToArray();
}
private async Task AddToList(ListElement list)
{
try
{
await this.twitterApi.ListsMembersCreate(list.Id, this.contextScreenName)
.IgnoreResponse();
var index = this.ListsCheckedListBox.Items.IndexOf(list);
this.ListsCheckedListBox.SetItemCheckState(index, CheckState.Checked);
}
catch (WebApiException ex)
{
MessageBox.Show(string.Format(Properties.Resources.ListManageOKButton2, ex.Message));
}
}
private async Task RemoveFromList(ListElement list)
{
try
{
await this.twitterApi.ListsMembersDestroy(list.Id, this.contextScreenName)
.IgnoreResponse();
var index = this.ListsCheckedListBox.Items.IndexOf(list);
this.ListsCheckedListBox.SetItemCheckState(index, CheckState.Unchecked);
}
catch (WebApiException ex)
{
MessageBox.Show(string.Format(Properties.Resources.ListManageOKButton2, ex.Message));
}
}
private async void MyLists_Load(object sender, EventArgs e)
{
using (ControlTransaction.Disabled(this))
{
try
{
await this.RefreshListBox();
}
catch (OperationCanceledException)
{
this.DialogResult = DialogResult.Cancel;
}
catch (WebApiException ex)
{
MessageBox.Show($"Failed to get lists. ({ex.Message})");
this.DialogResult = DialogResult.Abort;
}
}
}
private async void ListsCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
// 他のイベント等で操作中の場合は無視する
if (!this.Enabled)
return;
using (ControlTransaction.Disabled(this))
{
var list = (ListElement)this.ListsCheckedListBox.Items[e.Index];
if (e.CurrentValue == CheckState.Unchecked)
await this.AddToList(list);
else
await this.RemoveFromList(list);
}
}
private void ListsCheckedListBox_MouseDown(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Left:
//項目が無い部分をクリックしても、選択されている項目のチェック状態が変更されてしまうので、その対策
for (var index = 0; index < this.ListsCheckedListBox.Items.Count; index++)
{
if (this.ListsCheckedListBox.GetItemRectangle(index).Contains(e.Location))
return;
}
this.ListsCheckedListBox.SelectedItem = null;
break;
case MouseButtons.Right:
//コンテキストメニューの項目実行時にSelectedItemプロパティを利用出来るように
for (var index = 0; index < this.ListsCheckedListBox.Items.Count; index++)
{
if (this.ListsCheckedListBox.GetItemRectangle(index).Contains(e.Location))
{
this.ListsCheckedListBox.SetSelected(index, true);
return;
}
}
this.ListsCheckedListBox.SelectedItem = null;
break;
}
}
private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e)
=> e.Cancel = this.ListsCheckedListBox.SelectedItem == null;
private async void MenuItemAdd_Click(object sender, EventArgs e)
{
using (ControlTransaction.Disabled(this))
{
await this.AddToList((ListElement)this.ListsCheckedListBox.SelectedItem);
}
}
private async void MenuItemDelete_Click(object sender, EventArgs e)
{
using (ControlTransaction.Disabled(this))
{
await this.RemoveFromList((ListElement)this.ListsCheckedListBox.SelectedItem);
}
}
private async void MenuItemReload_Click(object sender, EventArgs e)
{
using (ControlTransaction.Disabled(this))
{
try
{
await this.RefreshListBox();
}
catch (OperationCanceledException) { }
catch (WebApiException ex)
{
MessageBox.Show($"Failed to get lists. ({ex.Message})");
}
}
}
private async void ListRefreshButton_Click(object sender, EventArgs e)
{
using (ControlTransaction.Disabled(this))
{
try
{
await this.RefreshListBox();
}
catch (OperationCanceledException) { }
catch (WebApiException ex)
{
MessageBox.Show($"Failed to get lists. ({ex.Message})");
}
}
}
private void CloseButton_Click(object sender, EventArgs e)
=> this.Close();
}
}
|
{
"pile_set_name": "Github"
}
|
package provider
import (
"fmt"
"net/http"
"testing"
fake "github.com/rackspace/gophercloud/openstack/networking/v2/common"
"github.com/rackspace/gophercloud/openstack/networking/v2/networks"
"github.com/rackspace/gophercloud/pagination"
th "github.com/rackspace/gophercloud/testhelper"
)
func TestList(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
{
"networks": [
{
"status": "ACTIVE",
"subnets": [
"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
],
"name": "private-network",
"admin_state_up": true,
"tenant_id": "4fd44f30292945e481c7b8a0c8908869",
"shared": true,
"id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
"provider:segmentation_id": null,
"provider:physical_network": null,
"provider:network_type": "local"
},
{
"status": "ACTIVE",
"subnets": [
"08eae331-0402-425a-923c-34f7cfe39c1b"
],
"name": "private",
"admin_state_up": true,
"tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e",
"shared": true,
"id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324",
"provider:segmentation_id": 1234567890,
"provider:physical_network": null,
"provider:network_type": "local"
}
]
}
`)
})
count := 0
networks.List(fake.ServiceClient(), networks.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
count++
actual, err := ExtractList(page)
if err != nil {
t.Errorf("Failed to extract networks: %v", err)
return false, err
}
expected := []NetworkExtAttrs{
NetworkExtAttrs{
Status: "ACTIVE",
Subnets: []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"},
Name: "private-network",
AdminStateUp: true,
TenantID: "4fd44f30292945e481c7b8a0c8908869",
Shared: true,
ID: "d32019d3-bc6e-4319-9c1d-6722fc136a22",
NetworkType: "local",
PhysicalNetwork: "",
SegmentationID: "",
},
NetworkExtAttrs{
Status: "ACTIVE",
Subnets: []string{"08eae331-0402-425a-923c-34f7cfe39c1b"},
Name: "private",
AdminStateUp: true,
TenantID: "26a7980765d0414dbc1fc1f88cdb7e6e",
Shared: true,
ID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324",
NetworkType: "local",
PhysicalNetwork: "",
SegmentationID: "1234567890",
},
}
th.CheckDeepEquals(t, expected, actual)
return true, nil
})
if count != 1 {
t.Errorf("Expected 1 page, got %d", count)
}
}
func TestGet(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/networks/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
{
"network": {
"status": "ACTIVE",
"subnets": [
"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
],
"name": "private-network",
"provider:physical_network": null,
"admin_state_up": true,
"tenant_id": "4fd44f30292945e481c7b8a0c8908869",
"provider:network_type": "local",
"shared": true,
"id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
"provider:segmentation_id": null
}
}
`)
})
res := networks.Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22")
n, err := ExtractGet(res)
th.AssertNoErr(t, err)
th.AssertEquals(t, "", n.PhysicalNetwork)
th.AssertEquals(t, "local", n.NetworkType)
th.AssertEquals(t, "", n.SegmentationID)
}
func TestCreate(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "POST")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
th.TestHeader(t, r, "Content-Type", "application/json")
th.TestHeader(t, r, "Accept", "application/json")
th.TestJSONRequest(t, r, `
{
"network": {
"name": "sample_network",
"admin_state_up": true
}
}
`)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `
{
"network": {
"status": "ACTIVE",
"subnets": [
"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
],
"name": "private-network",
"provider:physical_network": null,
"admin_state_up": true,
"tenant_id": "4fd44f30292945e481c7b8a0c8908869",
"provider:network_type": "local",
"shared": true,
"id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
"provider:segmentation_id": null
}
}
`)
})
options := networks.CreateOpts{Name: "sample_network", AdminStateUp: Up}
res := networks.Create(fake.ServiceClient(), options)
n, err := ExtractCreate(res)
th.AssertNoErr(t, err)
th.AssertEquals(t, "", n.PhysicalNetwork)
th.AssertEquals(t, "local", n.NetworkType)
th.AssertEquals(t, "", n.SegmentationID)
}
func TestUpdate(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "PUT")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
th.TestHeader(t, r, "Content-Type", "application/json")
th.TestHeader(t, r, "Accept", "application/json")
th.TestJSONRequest(t, r, `
{
"network": {
"name": "new_network_name",
"admin_state_up": false,
"shared": true
}
}
`)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
{
"network": {
"status": "ACTIVE",
"subnets": [
"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
],
"name": "private-network",
"provider:physical_network": null,
"admin_state_up": true,
"tenant_id": "4fd44f30292945e481c7b8a0c8908869",
"provider:network_type": "local",
"shared": true,
"id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
"provider:segmentation_id": null
}
}
`)
})
iTrue := true
options := networks.UpdateOpts{Name: "new_network_name", AdminStateUp: Down, Shared: &iTrue}
res := networks.Update(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", options)
n, err := ExtractUpdate(res)
th.AssertNoErr(t, err)
th.AssertEquals(t, "", n.PhysicalNetwork)
th.AssertEquals(t, "local", n.NetworkType)
th.AssertEquals(t, "", n.SegmentationID)
}
|
{
"pile_set_name": "Github"
}
|
State
Country
Form
2555-EZ
Department of the Treasury
Internal Revenue Service
(99)
Foreign Earned Income Exclusion
a
Attach to Form 1040.
a
.
OMB No. 1545-0074
20
13
Attachment
Sequence No.
34A
Name shown on Form 1040
Your social security number
You May Use
This Form
If You:
• Are a U.S. citizen or a resident alien.
• Earned wages/salaries in a foreign country.
• Had total foreign earned income
of $97,600 or less.
• Are filing a calendar year return that covers
a 12-month period.
And You:
• Do not have self-employment income.
• Do not have business/moving expenses.
• Do not claim the foreign housing
exclusion or deduction.
Part I
Tests To See If You Can Take the Foreign Earned Income Exclusion
1 Bona Fide Residence Test
a
Were you a bona fide resident of a foreign country or countries for a period that includes an entire tax year
(see instructions)?
..............................
Yes
No
• If you answered “Yes,” you meet this test. Fill in line 1b and then go to line 3.
b
Enter the date your bona fide residence began
a
, and ended (see instructions)
a
.
2 Physical Presence Test
a
Were you physically present in a foreign country or countries for at least 330 full days during—
{
any other period of 12 months in a row starting or ending in 2013?
}
.............
Yes
No
• If you answered “Yes,” you meet this test. Fill in line 2b and then go to line 3.
Bona Fide Residence Test above.
b
The physical presence test is based on the 12-month period from
a
through
a
.
3 Tax Home Test.
Was your tax home in a foreign country or countries throughout your period of bona fide
residence or physical presence, whichever applies?
...................
Yes
No
• If you answered “Yes,” you can take the exclusion. Complete Part II below and then go to page 2.
Part II
General Information
4
Your foreign address (including country)
5
Your occupation
6
Employer’s name
7
Employer’s U.S. address (including ZIP code)
8
Employer’s foreign address
9
Employer is (check any that apply):
a
A U.S. business
...................................
b
A foreign business
..................................
c
Other (specify)
a
10
a
If you previously filed Form 2555 or 2555-EZ, enter the last year you filed the form.
a
b
If you did not previously file Form 2555 or 2555-EZ, check here
a
and go to line 11a now.
c
Have you ever revoked the foreign earned income exclusion?
...............
Yes
No
d
If you answered “Yes,” enter the tax year for which the revocation was effective.
a
11a
List your tax home(s) during 2013 and date(s) established.
a
b
Of what country are you a citizen/national?
a
For Paperwork Reduction Act Notice, see the Form 1040 instructions.
Cat. No. 13272W
Form
2555-EZ
(2013)
City
Country Code
Address
Address
Addr
Addr2
City
Prov
Postal
Country
Addr
City
ZIP
Information about Form 2555-EZ and its separate instructions is at www.irs.gov/form2555ez
• If you answered “No,” you do not meet this test. Go to line 2 to see if you meet the Physical Presence Test.
2013 or
• If you answered “No,” you do not meet this test. You cannot take the exclusion unless you meet the
• If you answered “No,” you cannot take the exclusion. Do not file this form.
----------------Page (0) Break----------------
Days Present in the United States
Figure Your Foreign Earned Income Exclusion
Form 2555-EZ (2013)
Page
2
Part III
Complete this part if you were in the
United States or its possessions during 2013.
12
(a)
Date arrived in U.S.
(b)
Date left U.S.
(c)
Number of days
in U.S. on business
(d)
Income earned in U.S.
on business (attach computation)
Part IV
13
Maximum foreign earned income exclusion
..................
13
14
Enter the number of days in your qualifying period that fall within 2013 .
14
days
15
Did you enter 365 on line 14?
a decimal (rounded to at least three places).
}
.............
15
×
.
16
Multiply line 13 by line 15
........................
16
17
Enter, in U.S. dollars, the total foreign earned income you earned and received in 2013 (see
instructions). Be sure to include this amount on Form 1040, line 7
...........
17
18
from your income to arrive at total income on Form 1040, line 22 .
..........
a
18
Form
2555-EZ
(2013)
$97,600
Foreign earned income exclusion. Enter the smaller of line 16 or line 17 here and in parentheses
on Form 1040, line 21. Next to the amount enter •2555-EZ.Ž On Form 1040, subtract this amount
No. Divide line 14 by 365 and enter the result as
Yes. Enter “1.000.”
----------------Page (1) Break----------------
|
{
"pile_set_name": "Github"
}
|
## 序言
本教程希望让您快速熟悉使用React Native来编写iOS和Android App的技巧。如果你希望知道React Native是什么以及为什么Facebook打造了它,可以读读[这篇博文](http://bbs.reactnative.cn/topic/14)
我们这里假设你已经有了使用React编写Web应用程序的经验。如果还没有,建议你可以先从[React官网](http://facebook.github.io/react/)开始学习。
## 准备工作
React Native需要一些基础的配置工作,你可以参考[开始使用React Native](/docs/getting-started.html)来进行。
在所有依赖的软件都已经安装完毕后,只需要输入两条命令就可以创建一个React Native工程。
1. `npm install -g react-native-cli`
react-native-cli是一个终端命令,它可以完成其余的设置工作。它可以通过npm安装。刚才这条命令会往你的终端安装一个叫做`react-native`的命令。这个安装过程你只需要进行一次。
2. `react-native init AwesomeProject`
这个命令会初始化一个工程、下载React Native的所有源代码和依赖包,最后在`AwesomePrjoect/iOS/AwesomeProject.xcodeproj`和`AwesomeProject/android/app`下分别创建一个新的XCode工程和一个gradle工程。
__译注__:由于众所周知的网络原因,react-native命令行从npm官方源拖代码时会遇上麻烦。请先将npm仓库源替换为国内镜像:
```bash
npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist
```
另,执行init时切记不要在前面加上sudo(否则新项目的目录所有者会变为root而不是当前用户,导致一系列权限问题,请使用chown修复)。
本站论坛区提供了[完整的绿色纯净新项目包](http://bbs.reactnative.cn/topic/11)。完整打包全部iOS和Android的第三方依赖,只要环境配置正确,无需科学上网漫长等待,解压即可直接运行。
## 开发
想开发iOS版本,你现在可以在XCode中打开刚刚创建的工程(`AwesomePrjoect/iOS/AwesomeProject.xcodeproj`),然后只要按下`⌘+R`就可以构建并运行。这个操作会同时打开一个用于实现动态代码加载的Node服务(React Packager)。所以每当你修改代码,你只需要在模拟器中按下`⌘+R`,而无需重新在XCode中编译。
想开发Android版本,先连接你的设备或启动模拟器,然后在`AwesomeProject`目录下运行`react-native run-android`,就会构建工程并自动安装到你的模拟器或者设备,同时启动用于实现动态代码加载的Node服务。当你修改代码之后,你需要打开摇一摇菜单(摇一下设备,或者按下设备的Menu键,或者在模拟器上按下F2或Page Up,Genymotion按下⌘+M),然后在菜单中点击“Reload JS”。
在本向导中我们会创建一个简单的Movies应用,它可以获取25个上映中的电影,然后把他们在一个ListView中显示。
### Hello World
`react-native init`命令会创建一个指定名字的应用,我们刚才输入的命令就创建了一个名为AwesomePrjoect的应用。这是一个简单的Hello World应用。对于iOS版本,你可以编辑`index.ios.js`来做一些改动,然后在模拟器中按⌘+R来看到修改的结果。对Android版本,你可以编辑`index.android.js`来做一些改动,然后在摇一摇菜单中点击“Reload JS”来看到修改的结果。
### 模拟数据
__译注__:本文的示例代码改用了ES6语法,可能和其他文档写法不一致。但React Native从0.18之后,新建项目默认已经采用了ES6语法,故我们推荐不熟悉ES6与ES5区别的朋友先读读[这篇文章](http://bbs.reactnative.cn/topic/15),另外还可以看看[阮一峰老师的书](http://es6.ruanyifeng.com/)。
在我们真正从Rotten Tomatoes(_译注:一个国外的电影社区_)抓取数据之前,我们先制造一些模拟数据来练一练手。在Facebook我们通常在JS文件的开头,紧跟着import语句之后声明一个常量,不过这不重要,你可以把它放在`index.ios.js`和`index.android.js`的任意位置:
```javascript
var MOCKED_MOVIES_DATA = [
{title: '标题', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];
```
### 展现一个电影
我们接下来要展现一个电影,绘制它的标题、年份、以及缩略图(_译注:这个过程我们通常会叫做“渲染/render”,后面我们都会用“渲染”这个词_)。渲染缩略图需要用到Image组件,所以把Image添加到对React的import列表中。
```javascript
import React, {
AppRegistry,
Component,
Image,
StyleSheet,
Text,
View,
} from 'react-native';
```
然后修改一下render函数,这样我们可以把上面创建的模拟数据渲染出来。
```javascript
render() {
var movie = MOCKED_MOVIES_DATA[0];
return (
<View style={styles.container}>
<Text>{movie.title}</Text>
<Text>{movie.year}</Text>
<Image source={{uri: movie.posters.thumbnail}} />
</View>
);
}
```
按下`⌘+R`或者`Reload JS`,现在你应该能看到文字"Title"和"2015",但现在Image组件没渲染任何东西,这是因为我们还没有为图片指定我们想要渲染的宽和高。这通过样式来实现。当我们修改样式的时候,我们也应该清理掉我们不再使用的样式。
```javascript
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
thumbnail: {
width: 53,
height: 81,
},
});
```
然后把它应用到Image组件上:
```javascript
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
```
按下`⌘+R`或者`Reload JS`,现在图片应该可以被渲染出来了。
| | |
|--|--|
| ||
### 添加样式
现在我们已经成功的把我们的数据渲染出来了,下面让我们把它弄的更好看一些。我想把文字放在图片的右边,然后把标题弄的大一些,并且水平居中:
```
+---------------------------------+
|+-------++----------------------+|
|| || 标题 ||
|| 图片 || ||
|| || 年份 ||
|+-------++----------------------+|
+---------------------------------+
```
所以我们需要增加一个container来实现一个水平布局内嵌套一个垂直布局。
```javascript
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
```
和之前相比并没有太多变化,我们增加了一个container来包装文字,然后把它移到了Image的后面(因为他们最终在图片的右边)。然后我们来看看样式要怎么改:
```javascript
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
```
我们用Flexbox来布局。如果你想了解更多,可以读读[这篇文章](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)。
在上面的代码片段中,我们用了一句`flexDirection: 'row'`来让我们的主容器的成员从左到右横向布局,而非默认的从上到下纵向布局。
现在我们往`style`对象里增加另一个样式:
```javascript
rightContainer: {
flex: 1,
},
```
这句话的作用是让`rightContainer`在父容器中占据Image之外剩下的全部空间。如果你还不是很理解的话,你可以往`rightContainer`里增加一个`backgroundColor`看一看,然后再去掉`flex:1`对比一下。你会发现去掉这一句后,容器会变成能容纳它孩子的最小大小。
给文字添加样式就简单的多了:
```javascript
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
```
再按一次`⌘+R`或者`Reload JS`来看看最新的结果。
| | |
|--|--|
| ||
### 拉取真正的数据
从Rotten Tomatoes的API拉取数据和学习React Native并没有什么直接关系,所以你也可以直接跳过本节。
把下面的常量放到文件的最开头(通常在require下面)来创建我们请求数据所需的地址常量REQUEST_URL
```javascript
/**
* 为了避免骚扰,我们用了一个样例数据来替代Rotten Tomatoes的API
* 请求,这个样例数据放在React Native的Github库中。
*/
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
```
首先在应用中创建一个初始的null状态,这样可以通过`this.state.movies == null`来判断我们的数据是不是已经被抓取到了。我们在服务器响应返回的时候执行`this.setState({movies: moviesData})`来改变这个状态。把下面这段代码放到我们的React类的render函数之前:
```javascript
constructor(props) {
super(props); //这一句不能省略,照抄即可
this.state = {
movies: null, //这里放你自己定义的state变量及初始值
};
}
```
组件加载完毕之后,就可以向服务器请求数据。`componentDidMount`是React组件的一个生命周期方法,它会在组件刚加载完成的时候调用一次,以后不再会被调用。React中的各种生命周期方法请[参阅此文档](http://facebook.github.io/react/docs/component-specs.html)。
```javascript
componentDidMount() {
this.fetchData();
}
```
现在我们来为组件添加`fetchData`函数。你所需要做的就是在Promise调用链结束后执行`this.setState({movies:data})`。在React的工作机制下,`setState`实际上会触发一次重新渲染的流程,此时render函数被触发,发现this.state.movies不再是`null`。注意我们在Promise调用链的最后调用了`done()` —— 这样可以抛出异常而不是简单忽略。
```javascript
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
})
.done();
}
```
现在我们来修改render函数。在电影数据加载完毕之前,先渲染一个“加载中”的视图;而如果电影数据已经加载完毕了,则渲染第一个电影数据。
```javascript
render() {
if (!this.state.movies) {
return this.renderLoadingView();
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
正在加载电影数据……
</Text>
</View>
);
}
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}
```
现在再按一次`⌘+R`或者`Reload JS`,你会首先看到“正在加载电影数据……”,然后在响应数据到达之后,看到第一个电影的信息。
| | |
|--|--|
| ||
## ListView
现在我们来让我们的应用能够渲染所有的数据而不是仅仅第一部电影。我们要用到的就是ListView组件。
为什么建议把内容放到ListView里?比起直接渲染出所有的元素,或是放到一个ScrollView里有什么优势?这是因为尽管React很高效,渲染一个可能很大的元素列表还是会很慢。`ListView`会安排视图的渲染,只显示当前在屏幕上的那些元素。而那些已经渲染好了但移动到了屏幕之外的元素,则会从原生视图结构中移除(以提高性能)。
首先要做的事情:在文件最开头,从React中引入`ListView`。
```javascript
import React, {
AppRegistry,
Component,
Image,
ListView,
StyleSheet,
Text,
View,
} from 'react-native';
```
现在来修改render函数。当我们已经有了数据之后,渲染一个包含多个电影信息的ListView,而不仅仅是单个的电影。
```javascript
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
}
```
`dataSource`接口用来在ListView的整个更新过程中判断哪些数据行发生了变化。
你会注意到我们现在用到了`this.state`中的`dataSource`。下一步就是在`constructor`生成的初始状态中添加一个空白的`dataSource`。另外,我们现在要把数据存储在`dataSource`中了,所以不再另外用`this.state.movies`来保存数据。我们可以在state里用一个布尔型的属性(`this.state.loaded`)来判断数据加载是否已经完成了。
```javascript
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
```
同时我们也要修改`fetchData`方法来把数据更新到dataSource里:
```javascript
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
}
```
最后,我们再在`styles`对象里给`ListView`添加一些样式。
```javascript
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
```
现在可以体现最终的结果了:
| | |
|--|--|
| ||
为了实现一个完整功能的应用,接下来其实还有一些工作要做,譬如:添加导航器,搜索,加载更多,等等等等。可以在[Movies示例](https://github.com/facebook/react-native/tree/master/Examples/Movies)中看看我们做了什么。
### 最终的代码
```javascript
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, {
AppRegistry,
Component,
Image,
ListView,
StyleSheet,
Text,
View,
} from 'react-native';
var API_KEY = '7waqfqbprs7pajbz28mqf6vz';
var API_URL = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json';
var PAGE_SIZE = 25;
var PARAMS = '?apikey=' + API_KEY + '&page_limit=' + PAGE_SIZE;
var REQUEST_URL = API_URL + PARAMS;
class AwesomeProject extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
}
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
Loading movies...
</Text>
</View>
);
}
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
```
|
{
"pile_set_name": "Github"
}
|
# Hello Program Sample
The clasical program, using a complete declaration of divisions.
## Setup
Install [Node.js](http://nodejs.org).
## Run
With the command line:
```
node run hello.cob
```
The output:
```
Hello, world
```
hello.cob has the clasical four COBOL divisions declared:
```cobol
identification division.
program-id. hello.
author. A.J.Lopez.
installation. test.
date-written. 2012-12-22.
date-compiled. 2012-12-22.
environment division.
configuration section.
source-computer. node.
object-computer. node.
data division.
procedure division.
display "Hello, world".
```
|
{
"pile_set_name": "Github"
}
|
{
"name": "jsonld",
"version": "3.1.2-0",
"description": "A JSON-LD Processor and API implementation in JavaScript.",
"homepage": "https://github.com/digitalbazaar/jsonld.js",
"author": {
"name": "Digital Bazaar, Inc.",
"email": "support@digitalbazaar.com",
"url": "https://digitalbazaar.com/"
},
"contributors": [
"Dave Longley <dlongley@digitalbazaar.com>",
"David I. Lehn <dlehn@digitalbazaar.com>"
],
"repository": {
"type": "git",
"url": "https://github.com/digitalbazaar/jsonld.js"
},
"bugs": {
"url": "https://github.com/digitalbazaar/jsonld.js/issues",
"email": "support@digitalbazaar.com"
},
"license": "BSD-3-Clause",
"main": "lib/index.js",
"files": [
"dist/*.js",
"dist/*.js.map",
"dist/node6/**/*.js",
"lib/*.js",
"lib/**/*.js"
],
"dependencies": {
"canonicalize": "^1.0.1",
"lru-cache": "^5.1.1",
"object.fromentries": "^2.0.2",
"rdf-canonize": "^1.0.2",
"request": "^2.88.0",
"semver": "^6.3.0",
"xmldom": "0.1.19"
},
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/plugin-proposal-object-rest-spread": "^7.7.4",
"@babel/plugin-transform-modules-commonjs": "^7.7.5",
"@babel/plugin-transform-runtime": "^7.7.5",
"@babel/preset-env": "^7.7.5",
"@babel/register": "^7.7.4",
"@babel/runtime": "^7.7.5",
"babel-loader": "^8.0.5",
"benchmark": "^2.1.4",
"browserify": "^16.2.3",
"chai": "^4.2.0",
"commander": "^2.19.0",
"core-js": "^2.6.5",
"cors": "^2.7.1",
"cross-env": "^5.2.0",
"eslint": "^6.8.0",
"eslint-config-digitalbazaar": "^2.3.0",
"express": "^4.16.4",
"fs-extra": "^8.1.0",
"join-path-js": "0.0.0",
"karma": "^3.1.1",
"karma-babel-preprocessor": "^8.0.0",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-edge-launcher": "^0.4.2",
"karma-firefox-launcher": "^1.1.0",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.5",
"karma-safari-launcher": "^1.0.0",
"karma-server-side": "^1.7.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-tap-reporter": "0.0.6",
"karma-webpack": "^3.0.5",
"mocha": "^6.2.2",
"mocha-lcov-reporter": "^1.3.0",
"nyc": "^14.1.1",
"webpack": "^4.29.5",
"webpack-cli": "^3.2.3",
"webpack-merge": "^4.2.1"
},
"engines": {
"node": ">=6"
},
"keywords": [
"JSON",
"Linked Data",
"JSON-LD",
"RDF",
"Semantic Web",
"jsonld"
],
"scripts": {
"prepublish": "npm run build",
"build": "npm run build-webpack && npm run build-node6",
"build-webpack": "webpack",
"build-node6": "BROWSERSLIST='node 6' babel --no-babelrc lib --out-dir dist/node6/lib --presets=@babel/preset-env",
"fetch-test-suites": "npm run fetch-json-ld-wg-test-suite && npm run fetch-json-ld-org-test-suite && npm run fetch-normalization-test-suite",
"fetch-json-ld-wg-test-suite": "npm run fetch-json-ld-api-test-suite && npm run fetch-json-ld-framing-test-suite",
"fetch-json-ld-api-test-suite": "if [ ! -e test-suites/json-wg-api ]; then git clone --depth 1 https://github.com/w3c/json-ld-api.git test-suites/json-ld-api; fi",
"fetch-json-ld-framing-test-suite": "if [ ! -e test-suites/json-wg-framing ]; then git clone --depth 1 https://github.com/w3c/json-ld-framing.git test-suites/json-ld-framing; fi",
"fetch-json-ld-org-test-suite": "if [ ! -e test-suites/json-ld.org ]; then git clone --depth 1 https://github.com/json-ld/json-ld.org.git test-suites/json-ld.org; fi",
"fetch-normalization-test-suite": "if [ ! -e test-suites/normalization ]; then git clone --depth 1 https://github.com/json-ld/normalization.git test-suites/normalization; fi",
"test": "cross-env NODE_ENV=test mocha --delay -t 30000 -A -R ${REPORTER:-spec} tests/test.js",
"test-karma": "cross-env NODE_ENV=test karma start",
"coverage": "nyc --reporter=lcov --reporter=text-summary npm test",
"coverage-report": "nyc report",
"lint": "eslint *.js lib/**.js tests/**.js"
},
"nyc": {
"exclude": [
"lib/documentLoaders/xhr.js",
"tests"
]
},
"browser": {
"lib/index.js": "./lib/jsonld.js",
"crypto": false,
"http": false,
"jsonld-request": false,
"request": false,
"url": false,
"util": false,
"xmldom": false
}
}
|
{
"pile_set_name": "Github"
}
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class Operations(object):
"""Operations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client Api Version. Constant value: "2020-02-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2020-02-01"
self.config = config
def list(
self, custom_headers=None, raw=False, **operation_config):
"""Gets a list of compute operations.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of OperationValue
:rtype:
~azure.mgmt.containerservice.v2020_02_01.models.OperationValuePaged[~azure.mgmt.containerservice.v2020_02_01.models.OperationValue]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list.metadata['url']
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.OperationValuePaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list.metadata = {'url': '/providers/Microsoft.ContainerService/operations'}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* WordPress Export Administration API
*
* @package WordPress
* @subpackage Administration
*/
/**
* Version number for the export format.
*
* Bump this when something changes that might affect compatibility.
*
* @since 2.5.0
*/
define( 'WXR_VERSION', '1.2' );
/**
* Generates the WXR export file for download.
*
* Default behavior is to export all content, however, note that post content will only
* be exported for post types with the `can_export` argument enabled. Any posts with the
* 'auto-draft' status will be skipped.
*
* @since 2.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global WP_Post $post Global post object.
*
* @param array $args {
* Optional. Arguments for generating the WXR export file for download. Default empty array.
*
* @type string $content Type of content to export. If set, only the post content of this post type
* will be exported. Accepts 'all', 'post', 'page', 'attachment', or a defined
* custom post. If an invalid custom post type is supplied, every post type for
* which `can_export` is enabled will be exported instead. If a valid custom post
* type is supplied but `can_export` is disabled, then 'posts' will be exported
* instead. When 'all' is supplied, only post types with `can_export` enabled will
* be exported. Default 'all'.
* @type string $author Author to export content for. Only used when `$content` is 'post', 'page', or
* 'attachment'. Accepts false (all) or a specific author ID. Default false (all).
* @type string $category Category (slug) to export content for. Used only when `$content` is 'post'. If
* set, only post content assigned to `$category` will be exported. Accepts false
* or a specific category slug. Default is false (all categories).
* @type string $start_date Start date to export content from. Expected date format is 'Y-m-d'. Used only
* when `$content` is 'post', 'page' or 'attachment'. Default false (since the
* beginning of time).
* @type string $end_date End date to export content to. Expected date format is 'Y-m-d'. Used only when
* `$content` is 'post', 'page' or 'attachment'. Default false (latest publish date).
* @type string $status Post status to export posts for. Used only when `$content` is 'post' or 'page'.
* Accepts false (all statuses except 'auto-draft'), or a specific status, i.e.
* 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', or
* 'trash'. Default false (all statuses except 'auto-draft').
* }
*/
function export_wp( $args = array() ) {
global $wpdb, $post;
$defaults = array(
'content' => 'all',
'author' => false,
'category' => false,
'start_date' => false,
'end_date' => false,
'status' => false,
);
$args = wp_parse_args( $args, $defaults );
/**
* Fires at the beginning of an export, before any headers are sent.
*
* @since 2.3.0
*
* @param array $args An array of export arguments.
*/
do_action( 'export_wp', $args );
$sitename = sanitize_key( get_bloginfo( 'name' ) );
if ( ! empty( $sitename ) ) {
$sitename .= '.';
}
$date = gmdate( 'Y-m-d' );
$wp_filename = $sitename . 'WordPress.' . $date . '.xml';
/**
* Filters the export filename.
*
* @since 4.4.0
*
* @param string $wp_filename The name of the file for download.
* @param string $sitename The site name.
* @param string $date Today's date, formatted.
*/
$filename = apply_filters( 'export_wp_filename', $wp_filename, $sitename, $date );
header( 'Content-Description: File Transfer' );
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );
if ( 'all' !== $args['content'] && post_type_exists( $args['content'] ) ) {
$ptype = get_post_type_object( $args['content'] );
if ( ! $ptype->can_export ) {
$args['content'] = 'post';
}
$where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] );
} else {
$post_types = get_post_types( array( 'can_export' => true ) );
$esses = array_fill( 0, count( $post_types ), '%s' );
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types );
}
if ( $args['status'] && ( 'post' === $args['content'] || 'page' === $args['content'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] );
} else {
$where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
}
$join = '';
if ( $args['category'] && 'post' === $args['content'] ) {
$term = term_exists( $args['category'], 'category' );
if ( $term ) {
$join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] );
}
}
if ( in_array( $args['content'], array( 'post', 'page', 'attachment' ), true ) ) {
if ( $args['author'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] );
}
if ( $args['start_date'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", gmdate( 'Y-m-d', strtotime( $args['start_date'] ) ) );
}
if ( $args['end_date'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", gmdate( 'Y-m-d', strtotime( '+1 month', strtotime( $args['end_date'] ) ) ) );
}
}
// Grab a snapshot of post IDs, just in case it changes during the export.
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" );
/*
* Get the requested terms ready, empty unless posts filtered by category
* or all content.
*/
$cats = array();
$tags = array();
$terms = array();
if ( isset( $term ) && $term ) {
$cat = get_term( $term['term_id'], 'category' );
$cats = array( $cat->term_id => $cat );
unset( $term, $cat );
} elseif ( 'all' === $args['content'] ) {
$categories = (array) get_categories( array( 'get' => 'all' ) );
$tags = (array) get_tags( array( 'get' => 'all' ) );
$custom_taxonomies = get_taxonomies( array( '_builtin' => false ) );
$custom_terms = (array) get_terms(
array(
'taxonomy' => $custom_taxonomies,
'get' => 'all',
)
);
// Put categories in order with no child going before its parent.
while ( $cat = array_shift( $categories ) ) {
if ( 0 == $cat->parent || isset( $cats[ $cat->parent ] ) ) {
$cats[ $cat->term_id ] = $cat;
} else {
$categories[] = $cat;
}
}
// Put terms in order with no child going before its parent.
while ( $t = array_shift( $custom_terms ) ) {
if ( 0 == $t->parent || isset( $terms[ $t->parent ] ) ) {
$terms[ $t->term_id ] = $t;
} else {
$custom_terms[] = $t;
}
}
unset( $categories, $custom_taxonomies, $custom_terms );
}
/**
* Wrap given string in XML CDATA tag.
*
* @since 2.1.0
*
* @param string $str String to wrap in XML CDATA tag.
* @return string
*/
function wxr_cdata( $str ) {
if ( ! seems_utf8( $str ) ) {
$str = utf8_encode( $str );
}
// $str = ent2ncr(esc_html($str));
$str = '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $str ) . ']]>';
return $str;
}
/**
* Return the URL of the site
*
* @since 2.5.0
*
* @return string Site URL.
*/
function wxr_site_url() {
if ( is_multisite() ) {
// Multisite: the base URL.
return network_home_url();
} else {
// WordPress (single site): the blog URL.
return get_bloginfo_rss( 'url' );
}
}
/**
* Output a cat_name XML tag from a given category object
*
* @since 2.1.0
*
* @param object $category Category Object
*/
function wxr_cat_name( $category ) {
if ( empty( $category->name ) ) {
return;
}
echo '<wp:cat_name>' . wxr_cdata( $category->name ) . "</wp:cat_name>\n";
}
/**
* Output a category_description XML tag from a given category object
*
* @since 2.1.0
*
* @param object $category Category Object
*/
function wxr_category_description( $category ) {
if ( empty( $category->description ) ) {
return;
}
echo '<wp:category_description>' . wxr_cdata( $category->description ) . "</wp:category_description>\n";
}
/**
* Output a tag_name XML tag from a given tag object
*
* @since 2.3.0
*
* @param object $tag Tag Object
*/
function wxr_tag_name( $tag ) {
if ( empty( $tag->name ) ) {
return;
}
echo '<wp:tag_name>' . wxr_cdata( $tag->name ) . "</wp:tag_name>\n";
}
/**
* Output a tag_description XML tag from a given tag object
*
* @since 2.3.0
*
* @param object $tag Tag Object
*/
function wxr_tag_description( $tag ) {
if ( empty( $tag->description ) ) {
return;
}
echo '<wp:tag_description>' . wxr_cdata( $tag->description ) . "</wp:tag_description>\n";
}
/**
* Output a term_name XML tag from a given term object
*
* @since 2.9.0
*
* @param object $term Term Object
*/
function wxr_term_name( $term ) {
if ( empty( $term->name ) ) {
return;
}
echo '<wp:term_name>' . wxr_cdata( $term->name ) . "</wp:term_name>\n";
}
/**
* Output a term_description XML tag from a given term object
*
* @since 2.9.0
*
* @param object $term Term Object
*/
function wxr_term_description( $term ) {
if ( empty( $term->description ) ) {
return;
}
echo "\t\t<wp:term_description>" . wxr_cdata( $term->description ) . "</wp:term_description>\n";
}
/**
* Output term meta XML tags for a given term object.
*
* @since 4.6.0
*
* @param WP_Term $term Term object.
*/
function wxr_term_meta( $term ) {
global $wpdb;
$termmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->termmeta WHERE term_id = %d", $term->term_id ) );
foreach ( $termmeta as $meta ) {
/**
* Filters whether to selectively skip term meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 4.6.0
*
* @param bool $skip Whether to skip the current piece of term meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( ! apply_filters( 'wxr_export_skip_termmeta', false, $meta->meta_key, $meta ) ) {
printf( "\t\t<wp:termmeta>\n\t\t\t<wp:meta_key>%s</wp:meta_key>\n\t\t\t<wp:meta_value>%s</wp:meta_value>\n\t\t</wp:termmeta>\n", wxr_cdata( $meta->meta_key ), wxr_cdata( $meta->meta_value ) );
}
}
}
/**
* Output list of authors with posts
*
* @since 3.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int[] $post_ids Optional. Array of post IDs to filter the query by.
*/
function wxr_authors_list( array $post_ids = null ) {
global $wpdb;
if ( ! empty( $post_ids ) ) {
$post_ids = array_map( 'absint', $post_ids );
$and = 'AND ID IN ( ' . implode( ', ', $post_ids ) . ')';
} else {
$and = '';
}
$authors = array();
$results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft' $and" );
foreach ( (array) $results as $result ) {
$authors[] = get_userdata( $result->post_author );
}
$authors = array_filter( $authors );
foreach ( $authors as $author ) {
echo "\t<wp:author>";
echo '<wp:author_id>' . intval( $author->ID ) . '</wp:author_id>';
echo '<wp:author_login>' . wxr_cdata( $author->user_login ) . '</wp:author_login>';
echo '<wp:author_email>' . wxr_cdata( $author->user_email ) . '</wp:author_email>';
echo '<wp:author_display_name>' . wxr_cdata( $author->display_name ) . '</wp:author_display_name>';
echo '<wp:author_first_name>' . wxr_cdata( $author->first_name ) . '</wp:author_first_name>';
echo '<wp:author_last_name>' . wxr_cdata( $author->last_name ) . '</wp:author_last_name>';
echo "</wp:author>\n";
}
}
/**
* Output all navigation menu terms
*
* @since 3.1.0
*/
function wxr_nav_menu_terms() {
$nav_menus = wp_get_nav_menus();
if ( empty( $nav_menus ) || ! is_array( $nav_menus ) ) {
return;
}
foreach ( $nav_menus as $menu ) {
echo "\t<wp:term>";
echo '<wp:term_id>' . intval( $menu->term_id ) . '</wp:term_id>';
echo '<wp:term_taxonomy>nav_menu</wp:term_taxonomy>';
echo '<wp:term_slug>' . wxr_cdata( $menu->slug ) . '</wp:term_slug>';
wxr_term_name( $menu );
echo "</wp:term>\n";
}
}
/**
* Output list of taxonomy terms, in XML tag format, associated with a post
*
* @since 2.3.0
*/
function wxr_post_taxonomy() {
$post = get_post();
$taxonomies = get_object_taxonomies( $post->post_type );
if ( empty( $taxonomies ) ) {
return;
}
$terms = wp_get_object_terms( $post->ID, $taxonomies );
foreach ( (array) $terms as $term ) {
echo "\t\t<category domain=\"{$term->taxonomy}\" nicename=\"{$term->slug}\">" . wxr_cdata( $term->name ) . "</category>\n";
}
}
/**
* @param bool $return_me
* @param string $meta_key
* @return bool
*/
function wxr_filter_postmeta( $return_me, $meta_key ) {
if ( '_edit_lock' === $meta_key ) {
$return_me = true;
}
return $return_me;
}
add_filter( 'wxr_export_skip_postmeta', 'wxr_filter_postmeta', 10, 2 );
echo '<?xml version="1.0" encoding="' . get_bloginfo( 'charset' ) . "\" ?>\n";
?>
<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->
<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!-- on the site. For each author, you may choose to map to an -->
<!-- existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!-- contained in this file into your site. -->
<?php the_generator( 'export' ); ?>
<rss version="2.0"
xmlns:excerpt="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/excerpt/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:wp="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/"
>
<channel>
<title><?php bloginfo_rss( 'name' ); ?></title>
<link><?php bloginfo_rss( 'url' ); ?></link>
<description><?php bloginfo_rss( 'description' ); ?></description>
<pubDate><?php echo gmdate( 'D, d M Y H:i:s +0000' ); ?></pubDate>
<language><?php bloginfo_rss( 'language' ); ?></language>
<wp:wxr_version><?php echo WXR_VERSION; ?></wp:wxr_version>
<wp:base_site_url><?php echo wxr_site_url(); ?></wp:base_site_url>
<wp:base_blog_url><?php bloginfo_rss( 'url' ); ?></wp:base_blog_url>
<?php wxr_authors_list( $post_ids ); ?>
<?php foreach ( $cats as $c ) : ?>
<wp:category>
<wp:term_id><?php echo intval( $c->term_id ); ?></wp:term_id>
<wp:category_nicename><?php echo wxr_cdata( $c->slug ); ?></wp:category_nicename>
<wp:category_parent><?php echo wxr_cdata( $c->parent ? $cats[ $c->parent ]->slug : '' ); ?></wp:category_parent>
<?php
wxr_cat_name( $c );
wxr_category_description( $c );
wxr_term_meta( $c );
?>
</wp:category>
<?php endforeach; ?>
<?php foreach ( $tags as $t ) : ?>
<wp:tag>
<wp:term_id><?php echo intval( $t->term_id ); ?></wp:term_id>
<wp:tag_slug><?php echo wxr_cdata( $t->slug ); ?></wp:tag_slug>
<?php
wxr_tag_name( $t );
wxr_tag_description( $t );
wxr_term_meta( $t );
?>
</wp:tag>
<?php endforeach; ?>
<?php foreach ( $terms as $t ) : ?>
<wp:term>
<wp:term_id><?php echo intval( $t->term_id ); ?></wp:term_id>
<wp:term_taxonomy><?php echo wxr_cdata( $t->taxonomy ); ?></wp:term_taxonomy>
<wp:term_slug><?php echo wxr_cdata( $t->slug ); ?></wp:term_slug>
<wp:term_parent><?php echo wxr_cdata( $t->parent ? $terms[ $t->parent ]->slug : '' ); ?></wp:term_parent>
<?php
wxr_term_name( $t );
wxr_term_description( $t );
wxr_term_meta( $t );
?>
</wp:term>
<?php endforeach; ?>
<?php
if ( 'all' === $args['content'] ) {
wxr_nav_menu_terms();}
?>
<?php
/** This action is documented in wp-includes/feed-rss2.php */
do_action( 'rss2_head' );
?>
<?php
if ( $post_ids ) {
/**
* @global WP_Query $wp_query WordPress Query object.
*/
global $wp_query;
// Fake being in the loop.
$wp_query->in_the_loop = true;
// Fetch 20 posts at a time rather than loading the entire table into memory.
while ( $next_posts = array_splice( $post_ids, 0, 20 ) ) {
$where = 'WHERE ID IN (' . join( ',', $next_posts ) . ')';
$posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" );
// Begin Loop.
foreach ( $posts as $post ) {
setup_postdata( $post );
/** This filter is documented in wp-includes/feed.php */
$title = apply_filters( 'the_title_rss', $post->post_title );
/**
* Filters the post content used for WXR exports.
*
* @since 2.5.0
*
* @param string $post_content Content of the current post.
*/
$content = wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) );
/**
* Filters the post excerpt used for WXR exports.
*
* @since 2.6.0
*
* @param string $post_excerpt Excerpt for the current post.
*/
$excerpt = wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) );
$is_sticky = is_sticky( $post->ID ) ? 1 : 0;
?>
<item>
<title><?php echo $title; ?></title>
<link><?php the_permalink_rss(); ?></link>
<pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate>
<dc:creator><?php echo wxr_cdata( get_the_author_meta( 'login' ) ); ?></dc:creator>
<guid isPermaLink="false"><?php the_guid(); ?></guid>
<description></description>
<content:encoded><?php echo $content; ?></content:encoded>
<excerpt:encoded><?php echo $excerpt; ?></excerpt:encoded>
<wp:post_id><?php echo intval( $post->ID ); ?></wp:post_id>
<wp:post_date><?php echo wxr_cdata( $post->post_date ); ?></wp:post_date>
<wp:post_date_gmt><?php echo wxr_cdata( $post->post_date_gmt ); ?></wp:post_date_gmt>
<wp:comment_status><?php echo wxr_cdata( $post->comment_status ); ?></wp:comment_status>
<wp:ping_status><?php echo wxr_cdata( $post->ping_status ); ?></wp:ping_status>
<wp:post_name><?php echo wxr_cdata( $post->post_name ); ?></wp:post_name>
<wp:status><?php echo wxr_cdata( $post->post_status ); ?></wp:status>
<wp:post_parent><?php echo intval( $post->post_parent ); ?></wp:post_parent>
<wp:menu_order><?php echo intval( $post->menu_order ); ?></wp:menu_order>
<wp:post_type><?php echo wxr_cdata( $post->post_type ); ?></wp:post_type>
<wp:post_password><?php echo wxr_cdata( $post->post_password ); ?></wp:post_password>
<wp:is_sticky><?php echo intval( $is_sticky ); ?></wp:is_sticky>
<?php if ( 'attachment' === $post->post_type ) : ?>
<wp:attachment_url><?php echo wxr_cdata( wp_get_attachment_url( $post->ID ) ); ?></wp:attachment_url>
<?php endif; ?>
<?php wxr_post_taxonomy(); ?>
<?php
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
foreach ( $postmeta as $meta ) :
/**
* Filters whether to selectively skip post meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 3.3.0
*
* @param bool $skip Whether to skip the current post meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
?>
<wp:postmeta>
<wp:meta_key><?php echo wxr_cdata( $meta->meta_key ); ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:postmeta>
<?php
endforeach;
$_comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
$comments = array_map( 'get_comment', $_comments );
foreach ( $comments as $c ) :
?>
<wp:comment>
<wp:comment_id><?php echo intval( $c->comment_ID ); ?></wp:comment_id>
<wp:comment_author><?php echo wxr_cdata( $c->comment_author ); ?></wp:comment_author>
<wp:comment_author_email><?php echo wxr_cdata( $c->comment_author_email ); ?></wp:comment_author_email>
<wp:comment_author_url><?php echo esc_url_raw( $c->comment_author_url ); ?></wp:comment_author_url>
<wp:comment_author_IP><?php echo wxr_cdata( $c->comment_author_IP ); ?></wp:comment_author_IP>
<wp:comment_date><?php echo wxr_cdata( $c->comment_date ); ?></wp:comment_date>
<wp:comment_date_gmt><?php echo wxr_cdata( $c->comment_date_gmt ); ?></wp:comment_date_gmt>
<wp:comment_content><?php echo wxr_cdata( $c->comment_content ); ?></wp:comment_content>
<wp:comment_approved><?php echo wxr_cdata( $c->comment_approved ); ?></wp:comment_approved>
<wp:comment_type><?php echo wxr_cdata( $c->comment_type ); ?></wp:comment_type>
<wp:comment_parent><?php echo intval( $c->comment_parent ); ?></wp:comment_parent>
<wp:comment_user_id><?php echo intval( $c->user_id ); ?></wp:comment_user_id>
<?php
$c_meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) );
foreach ( $c_meta as $meta ) :
/**
* Filters whether to selectively skip comment meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 4.0.0
*
* @param bool $skip Whether to skip the current comment meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( apply_filters( 'wxr_export_skip_commentmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
?>
<wp:commentmeta>
<wp:meta_key><?php echo wxr_cdata( $meta->meta_key ); ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:commentmeta>
<?php endforeach; ?>
</wp:comment>
<?php endforeach; ?>
</item>
<?php
}
}
}
?>
</channel>
</rss>
<?php
}
|
{
"pile_set_name": "Github"
}
|
{
"jsonSchemaSemanticVersion": "1.0.0",
"imports": [
{
"corpusPath": "cdm:/foundations.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Common.cdm.json",
"moniker": "base_Common"
},
{
"corpusPath": "/core/operationsCommon/DataEntityView.cdm.json",
"moniker": "base_DataEntityView"
},
{
"corpusPath": "/core/operationsCommon/Tables/SupplyChain/SalesAndMarketing/Group/DlvTerm.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Tables/SupplyChain/Transportation/Main/TMSRoute.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Tables/SupplyChain/Transportation/WorksheetLine/TMSRouteSegment.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Tables/SupplyChain/Inventory/WorksheetHeader/WHSShipmentTable.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Tables/Finance/Ledger/Main/CompanyInfo.cdm.json"
}
],
"definitions": [
{
"entityName": "TMSRouteSegmentShipment",
"extendsEntity": "base_Common/Common",
"exhibitsTraits": [
{
"traitReference": "is.CDM.entityVersion",
"arguments": [
{
"name": "versionNumber",
"value": "1.1"
}
]
}
],
"hasAttributes": [
{
"name": "ActualWeight",
"dataType": "TMSActualWeight",
"isNullable": true,
"description": ""
},
{
"name": "BillOfLadingId",
"dataType": "WHSBillOfLadingId",
"isNullable": true,
"description": ""
},
{
"name": "DestinationPostalCode",
"dataType": "TMSPostalCode",
"isNullable": true,
"description": ""
},
{
"name": "DlvTermId",
"dataType": "DlvTermId",
"isNullable": true,
"description": ""
},
{
"name": "Id",
"dataType": "WHSShipmentId",
"description": ""
},
{
"name": "OriginPostalCode",
"dataType": "TMSPostalCode",
"isNullable": true,
"description": ""
},
{
"name": "ProNum",
"dataType": "WHSProNum",
"isNullable": true,
"description": ""
},
{
"name": "RouteCode",
"dataType": "TMSRouteCode",
"description": ""
},
{
"name": "Sequence",
"dataType": "TMSSequence",
"description": ""
},
{
"name": "StopNum",
"dataType": "TMSStopNum",
"isNullable": true,
"description": ""
},
{
"name": "WayBill",
"dataType": "TMSWayBill",
"isNullable": true,
"description": ""
},
{
"name": "DataAreaId",
"dataType": "string",
"isReadOnly": true
},
{
"entity": {
"entityReference": "DlvTerm"
},
"name": "Relationship_DlvTermRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "TMSRoute"
},
"name": "Relationship_TMSRouteRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "TMSRouteSegment"
},
"name": "Relationship_TMSRouteSegmentRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "WHSShipmentTable"
},
"name": "Relationship_WHSShipmentTableRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
},
{
"entity": {
"entityReference": "CompanyInfo"
},
"name": "Relationship_CompanyRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
}
],
"displayName": "Route Segment Shipment"
},
{
"dataTypeName": "TMSActualWeight",
"extendsDataType": "decimal"
},
{
"dataTypeName": "WHSBillOfLadingId",
"extendsDataType": "string"
},
{
"dataTypeName": "TMSPostalCode",
"extendsDataType": "string"
},
{
"dataTypeName": "DlvTermId",
"extendsDataType": "string"
},
{
"dataTypeName": "WHSShipmentId",
"extendsDataType": "string"
},
{
"dataTypeName": "WHSProNum",
"extendsDataType": "string"
},
{
"dataTypeName": "TMSRouteCode",
"extendsDataType": "string"
},
{
"dataTypeName": "TMSSequence",
"extendsDataType": "integer"
},
{
"dataTypeName": "TMSStopNum",
"extendsDataType": "integer"
},
{
"dataTypeName": "TMSWayBill",
"extendsDataType": "string"
}
]
}
|
{
"pile_set_name": "Github"
}
|
{
"name": "sleepwatcher",
"full_name": "sleepwatcher",
"oldname": null,
"aliases": [
],
"versioned_formulae": [
],
"desc": "Monitors sleep, wakeup, and idleness of a Mac",
"license": null,
"homepage": "https://www.bernhard-baehr.de/",
"versions": {
"stable": "2.2.1",
"head": null,
"bottle": true
},
"urls": {
"stable": {
"url": "https://www.bernhard-baehr.de/sleepwatcher_2.2.1.tgz",
"tag": null,
"revision": null
}
},
"revision": 0,
"version_scheme": 0,
"bottle": {
"stable": {
"rebuild": 0,
"cellar": ":any_skip_relocation",
"prefix": "/home/linuxbrew/.linuxbrew",
"root_url": "https://linuxbrew.bintray.com/bottles",
"files": {
"catalina": {
"url": "https://linuxbrew.bintray.com/bottles/sleepwatcher-2.2.1.catalina.bottle.tar.gz",
"sha256": "45c9c42ac76f9e9f85b0dbc2cb2251fe74448322196ac0ba10b93c416121db2a"
},
"mojave": {
"url": "https://linuxbrew.bintray.com/bottles/sleepwatcher-2.2.1.mojave.bottle.tar.gz",
"sha256": "eb160c23f9d92aed8d4bdfa24607a5bb343ad65dd487cb7a8570ac479bd05dd7"
},
"high_sierra": {
"url": "https://linuxbrew.bintray.com/bottles/sleepwatcher-2.2.1.high_sierra.bottle.tar.gz",
"sha256": "2c050aa5845cdf24b06f17bc1b4191941e4cf57cf1092f17fe35fe0e7f28159a"
},
"sierra": {
"url": "https://linuxbrew.bintray.com/bottles/sleepwatcher-2.2.1.sierra.bottle.tar.gz",
"sha256": "0cecea617ee9334f717a2e2e0424b944dedcc7cd403776c1cf6ff67352b96f4c"
}
}
}
},
"keg_only": false,
"bottle_disabled": false,
"options": [
],
"build_dependencies": [
],
"dependencies": [
],
"recommended_dependencies": [
],
"optional_dependencies": [
],
"uses_from_macos": [
],
"requirements": [
{
"name": "macos",
"cask": null,
"download": null,
"version": null,
"contexts": [
]
}
],
"conflicts_with": [
],
"caveats": "For SleepWatcher to work, you will need to read the following:\n\n $(brew --prefix)/Cellar/sleepwatcher/2.2.1/ReadMe.rtf\n\nIgnore information about installing the binary and man page,\nbut read information regarding setup of the launchd files which\nare installed here:\n\n \n\nThese are the examples provided by the author.\n",
"installed": [
],
"linked_keg": null,
"pinned": false,
"outdated": false,
"deprecated": false,
"disabled": false
}
|
{
"pile_set_name": "Github"
}
|
/* This is a compiled file, you should be editing the file in the templates directory */
.pace {
-webkit-pointer-events: none;
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
z-index: 2000;
width: 100%;
height: 12px;
background: #fff;
}
.pace-inactive {
display: none;
}
.pace .pace-progress {
background-color: #FF0000;
position: fixed;
top: 0;
right: 100%;
width: 100%;
height: 12px;
overflow: hidden;
-webkit-border-radius: 0 0 4px 0;
-moz-border-radius: 0 0 4px 0;
-o-border-radius: 0 0 4px 0;
border-radius: 0 0 4px 0;
-webkit-box-shadow: inset -1px 0 #AF0000, inset 0 -1px #AF0000, inset 0 2px rgba(255, 255, 255, 0.5), inset 0 6px rgba(255, 255, 255, .3);
-moz-box-shadow: inset -1px 0 #AF0000, inset 0 -1px #AF0000, inset 0 2px rgba(255, 255, 255, 0.5), inset 0 6px rgba(255, 255, 255, .3);
-o-box-shadow: inset -1px 0 #AF0000, inset 0 -1px #AF0000, inset 0 2px rgba(255, 255, 255, 0.5), inset 0 6px rgba(255, 255, 255, .3);
box-shadow: inset -1px 0 #AF0000, inset 0 -1px #AF0000, inset 0 2px rgba(255, 255, 255, 0.5), inset 0 6px rgba(255, 255, 255, .3);
}
.pace .pace-activity {
position: fixed;
top: 0;
left: 0;
right: -28px;
bottom: 0;
-webkit-background-image: radial-gradient(rgba(255, 255, 255, .65) 0%, rgba(255, 255, 255, .15) 100%);
-moz-background-image: radial-gradient(rgba(255, 255, 255, .65) 0%, rgba(255, 255, 255, .15) 100%);
-o-background-image: radial-gradient(rgba(255, 255, 255, .65) 0%, rgba(255, 255, 255, .15) 100%);
background-image: radial-gradient(rgba(255, 255, 255, .65) 0%, rgba(255, 255, 255, .15) 100%);
-webkit-background-size: 28px 100%;
-moz-background-size: 28px 100%;
-o-background-size: 28px 100%;
background-size: 28px 100%;
-webkit-animation: pace-theme-mac-osx-motion 500ms linear infinite;
-moz-animation: pace-theme-mac-osx-motion 500ms linear infinite;
-ms-animation: pace-theme-mac-osx-motion 500ms linear infinite;
-o-animation: pace-theme-mac-osx-motion 500ms linear infinite;
animation: pace-theme-mac-osx-motion 500ms linear infinite;
}
@-webkit-keyframes pace-theme-mac-osx-motion {
0% { -webkit-transform: none; transform: none; }
100% { -webkit-transform: translate(-28px, 0); transform: translate(-28px, 0); }
}
@-moz-keyframes pace-theme-mac-osx-motion {
0% { -moz-transform: none; transform: none; }
100% { -moz-transform: translate(-28px, 0); transform: translate(-28px, 0); }
}
@-o-keyframes pace-theme-mac-osx-motion {
0% { -o-transform: none; transform: none; }
100% { -o-transform: translate(-28px, 0); transform: translate(-28px, 0); }
}
@-ms-keyframes pace-theme-mac-osx-motion {
0% { -ms-transform: none; transform: none; }
100% { -ms-transform: translate(-28px, 0); transform: translate(-28px, 0); }
}
@keyframes pace-theme-mac-osx-motion {
0% { transform: none; transform: none; }
100% { transform: translate(-28px, 0); transform: translate(-28px, 0); }
}
|
{
"pile_set_name": "Github"
}
|
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <tice.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fileioc.h>
/* Declare some variables */
const char *appvarName = "AppVar";
typedef struct {
char name[15];
uint8_t var1;
uint8_t var2;
} data_t;
data_t data;
#define VAR1_VALUE 10
#define VAR2_VALUE 20
/* Function prototypes */
void printText(int8_t xpos, int8_t ypos, const char *text);
/* Main Function */
void main(void) {
char nameBuffer[10];
ti_var_t myAppVar;
int x;
/* Clear the homescreen */
os_ClrHome();
/* Declare some variable values */
strcpy(data.name, "My Data");
data.var1 = VAR1_VALUE;
data.var2 = VAR2_VALUE;
/* Close any files that may be open already */
ti_CloseAll();
/* Open a new variable; deleting it if it already exists */
myAppVar = ti_Open(appvarName, "w");
/* Make sure we opened okay */
if (!myAppVar) goto err;
/* Write the structure to the appvar */
if (ti_Write(&data, sizeof(data_t), 1, myAppVar) != 1) goto err;
/* Go back to the start of the file */
if (ti_Rewind(myAppVar) == EOF) goto err;
/* Let's read it just to make sure we wrote it correctly */
if (ti_Read(&data, sizeof(data_t), 1, myAppVar) != 1) goto err;
/* Make sure we read these variables correctly too */
if (data.var1 != VAR1_VALUE && data.var2 != VAR2_VALUE) goto err;
/* Ensure the name of the AppVar is correct */
ti_GetName(nameBuffer, myAppVar);
printText(0, 0, "Appvar: ");
printText(8, 0, nameBuffer);
printText(0, 1, "Read was successful");
goto noerr;
err:
printText(0, 0, "An error occured");
noerr:
/* Pause */
while (!os_GetCSC());
/* Close all open files */
ti_CloseAll();
}
/* Draw text on the homescreen at the given X/Y location */
void printText(int8_t xpos, int8_t ypos, const char *text) {
os_SetCursorPos(ypos, xpos);
os_PutStrFull(text);
}
|
{
"pile_set_name": "Github"
}
|
Initializing a Network
=======================
In nimblenet, a neural network is configured according to a dict of parameters specified upon initialization.
.. code:: python
from nimblenet.neuralnet import NeuralNet
network = NeuralNet({
"n_inputs" : 2,
"layers" : [ (1, sigmoid_function) ],
})
.. important::
The final tuple in the layers list always describe the number of output signals.
Parameters
------------
The two dict keys ``n_inputs`` and ``layers`` are required. However, the network is further customizable through specifying any of the following dict parameters:
* ``n_inputs`` the number of input signals
* ``layers`` the topology of the network
* ``initial_bias_value`` the input signal from the bias node will be initialized to this value
* ``weights_low`` the lower bound on weight value during the random initialization
* ``weights_high`` the upper bound on weight value during the random initialization
Example
---------
.. code:: python
from nimblenet.neuralnet import NeuralNet
settings = {
# Required settings
"n_inputs" : 2, # Number of network input signals
"layers" : [ (3, sigmoid_function), (1, sigmoid_function) ],
# [ (number_of_neurons, activation_function) ]
# The last pair in the list dictate the number of output signals
# Optional settings
"initial_bias_value" : 0.0,
"weights_low" : -0.1, # Lower bound on the initial weight value
"weights_high" : 0.1, # Upper bound on the initial weight value
}
network = NeuralNet( settings )
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.