answer stringlengths 15 1.25M |
|---|
goog.provide('ol.DrawEvent');
goog.provide('ol.DrawEventType');
goog.provide('ol.interaction.Draw');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('ol.Collection');
goog.require('ol.Coordinate');
goog.require('ol.Feature');
goog.require('ol.FeatureOverlay');
goog.require('ol.MapBrowserEvent');
goog.require('ol.MapBrowserEvent.EventType');
goog.require('ol.Object');
goog.require('ol.events.condition');
goog.require('ol.geom.Circle');
goog.require('ol.geom.GeometryType');
goog.require('ol.geom.LineString');
goog.require('ol.geom.MultiLineString');
goog.require('ol.geom.MultiPoint');
goog.require('ol.geom.MultiPolygon');
goog.require('ol.geom.Point');
goog.require('ol.geom.Polygon');
goog.require('ol.interaction.InteractionProperty');
goog.require('ol.interaction.Pointer');
goog.require('ol.source.Vector');
goog.require('ol.style.Style');
/**
* @enum {string}
*/
ol.DrawEventType = {
/**
* Triggered upon feature draw start
* @event ol.DrawEvent#drawstart
* @api stable
*/
DRAWSTART: 'drawstart',
/**
* Triggered upon feature draw end
* @event ol.DrawEvent#drawend
* @api stable
*/
DRAWEND: 'drawend'
};
/**
* @classdesc
* Events emitted by {@link ol.interaction.Draw} instances are instances of
* this type.
*
* @constructor
* @extends {goog.events.Event}
* @implements {oli.DrawEvent}
* @param {ol.DrawEventType} type Type.
* @param {ol.Feature} feature The feature drawn.
*/
ol.DrawEvent = function(type, feature) {
goog.base(this, type);
/**
* The feature being drawn.
* @type {ol.Feature}
* @api stable
*/
this.feature = feature;
};
goog.inherits(ol.DrawEvent, goog.events.Event);
/**
* @classdesc
* Interaction that allows drawing geometries.
*
* @constructor
* @extends {ol.interaction.Pointer}
* @fires ol.DrawEvent
* @param {olx.interaction.DrawOptions} options Options.
* @api stable
*/
ol.interaction.Draw = function(options) {
goog.base(this, {
handleDownEvent: ol.interaction.Draw.handleDownEvent_,
handleEvent: ol.interaction.Draw.handleEvent,
handleUpEvent: ol.interaction.Draw.handleUpEvent_
});
/**
* @type {ol.Pixel}
* @private
*/
this.downPx_ = null;
/**
* @type {boolean}
* @private
*/
this.freehand_ = false;
/**
* Target source for drawn features.
* @type {ol.source.Vector}
* @private
*/
this.source_ = goog.isDef(options.source) ? options.source : null;
/**
* Target collection for drawn features.
* @type {ol.Collection.<ol.Feature>}
* @private
*/
this.features_ = goog.isDef(options.features) ? options.features : null;
/**
* Pixel distance for snapping.
* @type {number}
* @private
*/
this.snapTolerance_ = goog.isDef(options.snapTolerance) ?
options.snapTolerance : 12;
/**
* The number of points that must be drawn before a polygon ring can be
* finished. The default is 3.
* @type {number}
* @private
*/
this.minPointsPerRing_ = goog.isDef(options.minPointsPerRing) ?
options.minPointsPerRing : 3;
/**
* Geometry type.
* @type {ol.geom.GeometryType}
* @private
*/
this.type_ = options.type;
/**
* Drawing mode (derived from geometry type.
* @type {ol.interaction.DrawMode}
* @private
*/
this.mode_ = ol.interaction.Draw.getMode_(this.type_);
/**
* Finish coordinate for the feature (first point for polygons, last point for
* linestrings).
* @type {ol.Coordinate}
* @private
*/
this.finishCoordinate_ = null;
/**
* Sketch feature.
* @type {ol.Feature}
* @private
*/
this.sketchFeature_ = null;
/**
* Sketch point.
* @type {ol.Feature}
* @private
*/
this.sketchPoint_ = null;
/**
* Sketch line. Used when drawing polygon.
* @type {ol.Feature}
* @private
*/
this.sketchLine_ = null;
/**
* Sketch polygon. Used when drawing polygon.
* @type {Array.<Array.<ol.Coordinate>>}
* @private
*/
this.<API key> = null;
/**
* Squared tolerance for handling up events. If the squared distance
* between a down and up event is greater than this tolerance, up events
* will not be handled.
* @type {number}
* @private
*/
this.<API key> = 4;
/**
* Draw overlay where our sketch features are drawn.
* @type {ol.FeatureOverlay}
* @private
*/
this.overlay_ = new ol.FeatureOverlay({
style: goog.isDef(options.style) ?
options.style : ol.interaction.Draw.<API key>()
});
/**
* Name of the geometry attribute for newly created features.
* @type {string|undefined}
* @private
*/
this.geometryName_ = options.geometryName;
/**
* @private
* @type {ol.events.ConditionType}
*/
this.condition_ = goog.isDef(options.condition) ?
options.condition : ol.events.condition.noModifierKeys;
/**
* @private
* @type {ol.events.ConditionType}
*/
this.freehandCondition_ = goog.isDef(options.freehandCondition) ?
options.freehandCondition : ol.events.condition.shiftKeyOnly;
goog.events.listen(this,
ol.Object.getChangeEventType(ol.interaction.InteractionProperty.ACTIVE),
this.updateState_, false, this);
};
goog.inherits(ol.interaction.Draw, ol.interaction.Pointer);
/**
* @return {ol.style.StyleFunction} Styles.
*/
ol.interaction.Draw.<API key> = function() {
var styles = ol.style.<API key>();
return function(feature, resolution) {
return styles[feature.getGeometry().getType()];
};
};
/**
* @inheritDoc
*/
ol.interaction.Draw.prototype.setMap = function(map) {
goog.base(this, 'setMap', map);
this.updateState_();
};
/**
* Handles the {@link ol.MapBrowserEvent map browser event} and may actually
* draw or finish the drawing.
* @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
* @return {boolean} `false` to stop event propagation.
* @this {ol.interaction.Draw}
* @api
*/
ol.interaction.Draw.handleEvent = function(mapBrowserEvent) {
var pass = !this.freehand_;
if (this.freehand_ &&
mapBrowserEvent.type === ol.MapBrowserEvent.EventType.POINTERDRAG) {
this.addToDrawing_(mapBrowserEvent);
pass = false;
} else if (mapBrowserEvent.type ===
ol.MapBrowserEvent.EventType.POINTERMOVE) {
pass = this.handlePointerMove_(mapBrowserEvent);
} else if (mapBrowserEvent.type === ol.MapBrowserEvent.EventType.DBLCLICK) {
pass = false;
}
return ol.interaction.Pointer.handleEvent.call(this, mapBrowserEvent) && pass;
};
/**
* @param {ol.<API key>} event Event.
* @return {boolean} Start drag sequence?
* @this {ol.interaction.Draw}
* @private
*/
ol.interaction.Draw.handleDownEvent_ = function(event) {
if (this.condition_(event)) {
this.downPx_ = event.pixel;
return true;
} else if ((this.mode_ === ol.interaction.DrawMode.LINE_STRING ||
this.mode_ === ol.interaction.DrawMode.POLYGON) &&
this.freehandCondition_(event)) {
this.downPx_ = event.pixel;
this.freehand_ = true;
if (goog.isNull(this.finishCoordinate_)) {
this.startDrawing_(event);
}
return true;
} else {
return false;
}
};
/**
* @param {ol.<API key>} event Event.
* @return {boolean} Stop drag sequence?
* @this {ol.interaction.Draw}
* @private
*/
ol.interaction.Draw.handleUpEvent_ = function(event) {
this.freehand_ = false;
var downPx = this.downPx_;
var clickPx = event.pixel;
var dx = downPx[0] - clickPx[0];
var dy = downPx[1] - clickPx[1];
var squaredDistance = dx * dx + dy * dy;
var pass = true;
if (squaredDistance <= this.<API key>) {
this.handlePointerMove_(event);
if (goog.isNull(this.finishCoordinate_)) {
this.startDrawing_(event);
} else if ((this.mode_ === ol.interaction.DrawMode.POINT ||
this.mode_ === ol.interaction.DrawMode.CIRCLE) &&
!goog.isNull(this.finishCoordinate_) ||
this.atFinish_(event)) {
this.finishDrawing();
} else {
this.addToDrawing_(event);
}
pass = false;
}
return pass;
};
/**
* Handle move events.
* @param {ol.MapBrowserEvent} event A move event.
* @return {boolean} Pass the event to other interactions.
* @private
*/
ol.interaction.Draw.prototype.handlePointerMove_ = function(event) {
if (this.mode_ === ol.interaction.DrawMode.POINT &&
goog.isNull(this.finishCoordinate_)) {
this.startDrawing_(event);
} else if (!goog.isNull(this.finishCoordinate_)) {
this.modifyDrawing_(event);
} else {
this.<API key>(event);
}
return true;
};
/**
* Determine if an event is within the snapping tolerance of the start coord.
* @param {ol.MapBrowserEvent} event Event.
* @return {boolean} The event is within the snapping tolerance of the start.
* @private
*/
ol.interaction.Draw.prototype.atFinish_ = function(event) {
var at = false;
if (!goog.isNull(this.sketchFeature_)) {
var geometry = this.sketchFeature_.getGeometry();
var potentiallyDone = false;
var <API key> = [this.finishCoordinate_];
if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
'geometry should be an ol.geom.LineString');
potentiallyDone = geometry.getCoordinates().length > 2;
} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
'geometry should be an ol.geom.Polygon');
potentiallyDone = geometry.getCoordinates()[0].length >
this.minPointsPerRing_;
<API key> = [this.<API key>[0][0],
this.<API key>[0][this.<API key>[0].length - 2]];
}
if (potentiallyDone) {
var map = event.map;
for (var i = 0, ii = <API key>.length; i < ii; i++) {
var finishCoordinate = <API key>[i];
var finishPixel = map.<API key>(finishCoordinate);
var pixel = event.pixel;
var dx = pixel[0] - finishPixel[0];
var dy = pixel[1] - finishPixel[1];
var freehand = this.freehand_ && this.freehandCondition_(event);
var snapTolerance = freehand ? 1 : this.snapTolerance_;
at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance;
if (at) {
this.finishCoordinate_ = finishCoordinate;
break;
}
}
}
}
return at;
};
/**
* @param {ol.MapBrowserEvent} event Event.
* @private
*/
ol.interaction.Draw.prototype.<API key> = function(event) {
var coordinates = event.coordinate.slice();
if (goog.isNull(this.sketchPoint_)) {
this.sketchPoint_ = new ol.Feature(new ol.geom.Point(coordinates));
this.<API key>();
} else {
var sketchPointGeom = this.sketchPoint_.getGeometry();
goog.asserts.assertInstanceof(sketchPointGeom, ol.geom.Point,
'sketchPointGeom should be an ol.geom.Point');
sketchPointGeom.setCoordinates(coordinates);
}
};
/**
* Start the drawing.
* @param {ol.MapBrowserEvent} event Event.
* @private
*/
ol.interaction.Draw.prototype.startDrawing_ = function(event) {
var start = event.coordinate;
this.finishCoordinate_ = start;
var geometry;
if (this.mode_ === ol.interaction.DrawMode.POINT) {
geometry = new ol.geom.Point(start.slice());
} else {
if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
geometry = new ol.geom.LineString([start.slice(), start.slice()]);
} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
this.sketchLine_ = new ol.Feature(new ol.geom.LineString([start.slice(),
start.slice()]));
this.<API key> = [[start.slice(), start.slice()]];
geometry = new ol.geom.Polygon(this.<API key>);
} else if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
geometry = new ol.geom.Circle(start.slice(), 0);
this.sketchLine_ = new ol.Feature(new ol.geom.LineString([start.slice(),
start.slice()]));
}
}
goog.asserts.assert(goog.isDef(geometry), 'geometry should be defined');
this.sketchFeature_ = new ol.Feature();
if (goog.isDef(this.geometryName_)) {
this.sketchFeature_.setGeometryName(this.geometryName_);
}
this.sketchFeature_.setGeometry(geometry);
this.<API key>();
this.dispatchEvent(new ol.DrawEvent(ol.DrawEventType.DRAWSTART,
this.sketchFeature_));
};
/**
* Modify the drawing.
* @param {ol.MapBrowserEvent} event Event.
* @private
*/
ol.interaction.Draw.prototype.modifyDrawing_ = function(event) {
var coordinate = event.coordinate;
var geometry = this.sketchFeature_.getGeometry();
var coordinates, last, sketchLineGeom;
if (this.mode_ === ol.interaction.DrawMode.POINT) {
goog.asserts.assertInstanceof(geometry, ol.geom.Point,
'geometry should be an ol.geom.Point');
last = geometry.getCoordinates();
last[0] = coordinate[0];
last[1] = coordinate[1];
geometry.setCoordinates(last);
} else {
if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
'geometry should be an ol.geom.LineString');
coordinates = geometry.getCoordinates();
} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
'geometry should be an ol.geom.Polygon');
coordinates = this.<API key>[0];
} else if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
goog.asserts.assertInstanceof(geometry, ol.geom.Circle,
'geometry should be an ol.geom.Circle');
coordinates = geometry.getCenter();
}
if (this.atFinish_(event)) {
// snap to finish
coordinate = this.finishCoordinate_.slice();
}
var sketchPointGeom = this.sketchPoint_.getGeometry();
goog.asserts.assertInstanceof(sketchPointGeom, ol.geom.Point,
'sketchPointGeom should be an ol.geom.Point');
sketchPointGeom.setCoordinates(coordinate);
last = coordinates[coordinates.length - 1];
last[0] = coordinate[0];
last[1] = coordinate[1];
if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
'geometry should be an ol.geom.LineString');
geometry.setCoordinates(coordinates);
} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
sketchLineGeom = this.sketchLine_.getGeometry();
goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
'sketchLineGeom should be an ol.geom.LineString');
sketchLineGeom.setCoordinates(coordinates);
goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
'geometry should be an ol.geom.Polygon');
geometry.setCoordinates(this.<API key>);
} else if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
goog.asserts.assertInstanceof(geometry, ol.geom.Circle,
'geometry should be an ol.geom.Circle');
sketchLineGeom = this.sketchLine_.getGeometry();
goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
'sketchLineGeom should be an ol.geom.LineString');
sketchLineGeom.setCoordinates([geometry.getCenter(), coordinate]);
geometry.setRadius(sketchLineGeom.getLength());
}
}
this.<API key>();
};
/**
* Add a new coordinate to the drawing.
* @param {ol.MapBrowserEvent} event Event.
* @private
*/
ol.interaction.Draw.prototype.addToDrawing_ = function(event) {
var coordinate = event.coordinate;
var geometry = this.sketchFeature_.getGeometry();
var coordinates;
if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
this.finishCoordinate_ = coordinate.slice();
goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
'geometry should be an ol.geom.LineString');
coordinates = geometry.getCoordinates();
coordinates.push(coordinate.slice());
geometry.setCoordinates(coordinates);
} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
this.<API key>[0].push(coordinate.slice());
goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
'geometry should be an ol.geom.Polygon');
geometry.setCoordinates(this.<API key>);
}
this.<API key>();
};
/**
* Stop drawing and add the sketch feature to the target layer.
* The {@link ol.DrawEventType.DRAWEND} event is dispatched before inserting
* the feature.
* @api
*/
ol.interaction.Draw.prototype.finishDrawing = function() {
var sketchFeature = this.abortDrawing_();
goog.asserts.assert(!goog.isNull(sketchFeature),
'sketchFeature should not be null');
var coordinates;
var geometry = sketchFeature.getGeometry();
if (this.mode_ === ol.interaction.DrawMode.POINT) {
goog.asserts.assertInstanceof(geometry, ol.geom.Point,
'geometry should be an ol.geom.Point');
coordinates = geometry.getCoordinates();
} else if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
'geometry should be an ol.geom.LineString');
coordinates = geometry.getCoordinates();
// remove the redundant last point
coordinates.pop();
geometry.setCoordinates(coordinates);
} else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
'geometry should be an ol.geom.Polygon');
// When we finish drawing a polygon on the last point,
// the last coordinate is duplicated as for LineString
// we force the replacement by the first point
this.<API key>[0].pop();
this.<API key>[0].push(this.<API key>[0][0]);
geometry.setCoordinates(this.<API key>);
coordinates = geometry.getCoordinates();
}
// cast multi-part geometries
if (this.type_ === ol.geom.GeometryType.MULTI_POINT) {
sketchFeature.setGeometry(new ol.geom.MultiPoint([coordinates]));
} else if (this.type_ === ol.geom.GeometryType.MULTI_LINE_STRING) {
sketchFeature.setGeometry(new ol.geom.MultiLineString([coordinates]));
} else if (this.type_ === ol.geom.GeometryType.MULTI_POLYGON) {
sketchFeature.setGeometry(new ol.geom.MultiPolygon([coordinates]));
}
// First dispatch event to allow full set up of feature
this.dispatchEvent(new ol.DrawEvent(ol.DrawEventType.DRAWEND, sketchFeature));
// Then insert feature
if (!goog.isNull(this.features_)) {
this.features_.push(sketchFeature);
}
if (!goog.isNull(this.source_)) {
this.source_.addFeature(sketchFeature);
}
};
/**
* Stop drawing without adding the sketch feature to the target layer.
* @return {ol.Feature} The sketch feature (or null if none).
* @private
*/
ol.interaction.Draw.prototype.abortDrawing_ = function() {
this.finishCoordinate_ = null;
var sketchFeature = this.sketchFeature_;
if (!goog.isNull(sketchFeature)) {
this.sketchFeature_ = null;
this.sketchPoint_ = null;
this.sketchLine_ = null;
this.overlay_.getFeatures().clear();
}
return sketchFeature;
};
/**
* @inheritDoc
*/
ol.interaction.Draw.prototype.shouldStopEvent = goog.functions.FALSE;
/**
* Redraw the sketch features.
* @private
*/
ol.interaction.Draw.prototype.<API key> = function() {
var sketchFeatures = [];
if (!goog.isNull(this.sketchFeature_)) {
sketchFeatures.push(this.sketchFeature_);
}
if (!goog.isNull(this.sketchLine_)) {
sketchFeatures.push(this.sketchLine_);
}
if (!goog.isNull(this.sketchPoint_)) {
sketchFeatures.push(this.sketchPoint_);
}
this.overlay_.setFeatures(new ol.Collection(sketchFeatures));
};
/**
* @private
*/
ol.interaction.Draw.prototype.updateState_ = function() {
var map = this.getMap();
var active = this.getActive();
if (goog.isNull(map) || !active) {
this.abortDrawing_();
}
this.overlay_.setMap(active ? map : null);
};
/**
* Get the drawing mode. The mode for mult-part geometries is the same as for
* their single-part cousins.
* @param {ol.geom.GeometryType} type Geometry type.
* @return {ol.interaction.DrawMode} Drawing mode.
* @private
*/
ol.interaction.Draw.getMode_ = function(type) {
var mode;
if (type === ol.geom.GeometryType.POINT ||
type === ol.geom.GeometryType.MULTI_POINT) {
mode = ol.interaction.DrawMode.POINT;
} else if (type === ol.geom.GeometryType.LINE_STRING ||
type === ol.geom.GeometryType.MULTI_LINE_STRING) {
mode = ol.interaction.DrawMode.LINE_STRING;
} else if (type === ol.geom.GeometryType.POLYGON ||
type === ol.geom.GeometryType.MULTI_POLYGON) {
mode = ol.interaction.DrawMode.POLYGON;
} else if (type === ol.geom.GeometryType.CIRCLE) {
mode = ol.interaction.DrawMode.CIRCLE;
}
goog.asserts.assert(goog.isDef(mode), 'mode should be defined');
return mode;
};
/**
* Draw mode. This collapses multi-part geometry types with their single-part
* cousins.
* @enum {string}
*/
ol.interaction.DrawMode = {
POINT: 'Point',
LINE_STRING: 'LineString',
POLYGON: 'Polygon',
CIRCLE: 'Circle'
}; |
import six
import json
import unittest
from unittest import TestCase
from rejson import Client, Path
rj = None
port = 6379
class ReJSONTestCase(TestCase):
def setUp(self):
global rj
rj = Client(port=port, decode_responses=True)
rj.flushdb()
def <API key>(self):
"Test basic JSONSet/Get/Del"
self.assertTrue(rj.jsonset('foo', Path.rootPath(), 'bar'))
self.assertEqual('bar', rj.jsonget('foo'))
self.assertEqual(None, rj.jsonget('baz'))
self.assertEqual(1, rj.jsondel('foo'))
self.assertFalse(rj.exists('foo'))
def <API key>(self):
"Test JSONSet's NX/XX flags"
obj = { 'foo': 'bar' }
self.assertTrue(rj.jsonset('obj', Path.rootPath(), obj))
# Test that flags prevent updates when conditions are unmet
self.assertFalse(rj.jsonset('obj', Path('foo'), 'baz', nx=True))
self.assertFalse(rj.jsonset('obj', Path('qaz'), 'baz', xx=True))
# Test that flags allow updates when conditions are met
self.assertTrue(rj.jsonset('obj', Path('foo'), 'baz', xx=True))
self.assertTrue(rj.jsonset('obj', Path('qaz'), 'baz', nx=True))
# Test that flags are mutually exlusive
with self.assertRaises(Exception) as context:
rj.jsonset('obj', Path('foo'), 'baz', nx=True, xx=True)
def <API key>(self):
"Test JSONMGet"
rj.jsonset('1', Path.rootPath(), 1)
rj.jsonset('2', Path.rootPath(), 2)
r = rj.jsonmget(Path.rootPath(), '1', '2')
e = [1, 2]
self.assertListEqual(e, r)
def <API key>(self):
"Test JSONType"
rj.jsonset('1', Path.rootPath(), 1)
self.assertEqual('integer', rj.jsontype('1'))
def <API key>(self):
"Test JSONNumIncrBy"
rj.jsonset('num', Path.rootPath(), 1)
self.assertEqual(2, rj.jsonnumincrby('num', Path.rootPath(), 1))
self.assertEqual(2.5, rj.jsonnumincrby('num', Path.rootPath(), 0.5))
self.assertEqual(1.25, rj.jsonnumincrby('num', Path.rootPath(), -1.25))
def <API key>(self):
"Test JSONNumIncrBy"
rj.jsonset('num', Path.rootPath(), 1)
self.assertEqual(2, rj.jsonnummultby('num', Path.rootPath(), 2))
self.assertEqual(5, rj.jsonnummultby('num', Path.rootPath(), 2.5))
self.assertEqual(2.5, rj.jsonnummultby('num', Path.rootPath(), 0.5))
def <API key>(self):
"Test JSONStrAppend"
rj.jsonset('str', Path.rootPath(), 'foo')
self.assertEqual(6, rj.jsonstrappend('str', 'bar', Path.rootPath()))
self.assertEqual('foobar', rj.jsonget('str', Path.rootPath()))
def <API key>(self):
"Test JSONStrLen"
rj.jsonset('str', Path.rootPath(), 'foo')
self.assertEqual(3, rj.jsonstrlen('str', Path.rootPath()))
rj.jsonstrappend('str', 'bar', Path.rootPath())
self.assertEqual(6, rj.jsonstrlen('str', Path.rootPath()))
def <API key>(self):
"Test JSONSArrAppend"
rj.jsonset('arr', Path.rootPath(), [1])
self.assertEqual(2, rj.jsonarrappend('arr', Path.rootPath(), 2))
def <API key>(self):
"Test JSONSArrIndex"
rj.jsonset('arr', Path.rootPath(), [0, 1, 2, 3, 4])
self.assertEqual(1, rj.jsonarrindex('arr', Path.rootPath(), 1))
self.assertEqual(-1, rj.jsonarrindex('arr', Path.rootPath(), 1, 2))
def <API key>(self):
"Test JSONSArrInsert"
rj.jsonset('arr', Path.rootPath(), [0, 4])
self.assertEqual(5, rj.jsonarrinsert('arr',
Path.rootPath(), 1, *[1, 2, 3, ]))
self.assertListEqual([0, 1, 2, 3, 4], rj.jsonget('arr'))
def <API key>(self):
"Test JSONSArrLen"
rj.jsonset('arr', Path.rootPath(), [0, 1, 2, 3, 4])
self.assertEqual(5, rj.jsonarrlen('arr', Path.rootPath()))
def <API key>(self):
"Test JSONSArrPop"
rj.jsonset('arr', Path.rootPath(), [0, 1, 2, 3, 4])
self.assertEqual(4, rj.jsonarrpop('arr', Path.rootPath(), 4))
self.assertEqual(3, rj.jsonarrpop('arr', Path.rootPath(), -1))
self.assertEqual(2, rj.jsonarrpop('arr', Path.rootPath()))
self.assertEqual(0, rj.jsonarrpop('arr', Path.rootPath(), 0))
self.assertListEqual([1], rj.jsonget('arr'))
def <API key>(self):
"Test JSONSArrPop"
rj.jsonset('arr', Path.rootPath(), [0, 1, 2, 3, 4])
self.assertEqual(3, rj.jsonarrtrim('arr', Path.rootPath(), 1, 3))
self.assertListEqual([1, 2, 3], rj.jsonget('arr'))
def <API key>(self):
"Test JSONSObjKeys"
obj = {'foo': 'bar', 'baz': 'qaz'}
rj.jsonset('obj', Path.rootPath(), obj)
keys = rj.jsonobjkeys('obj', Path.rootPath())
keys.sort()
exp = [k for k in six.iterkeys(obj)]
exp.sort()
self.assertListEqual(exp, keys)
def <API key>(self):
"Test JSONSObjLen"
obj = {'foo': 'bar', 'baz': 'qaz'}
rj.jsonset('obj', Path.rootPath(), obj)
self.assertEqual(len(obj), rj.jsonobjlen('obj', Path.rootPath()))
def <API key>(self):
"Test pipeline"
p = rj.pipeline()
p.jsonset('foo', Path.rootPath(), 'bar')
p.jsonget('foo')
p.jsondel('foo')
p.exists('foo')
self.assertListEqual([True, 'bar', 1, False], p.execute())
def <API key>(self):
"Test a custom encoder and decoder"
class CustomClass(object):
key = ''
val = ''
def __init__(self, k='', v=''):
self.key = k
self.val = v
class TestEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, CustomClass):
return 'CustomClass:{}:{}'.format(obj.key, obj.val)
return json.JSONEncoder.encode(self, obj)
class TestDecoder(json.JSONDecoder):
def decode(self, obj):
d = json.JSONDecoder.decode(self, obj)
if isinstance(d, six.string_types) and \
d.startswith('CustomClass:'):
s = d.split(':')
return CustomClass(k=s[1], v=s[2])
return d
rj = Client(encoder=TestEncoder(), decoder=TestDecoder(),
port=port, decode_responses=True)
rj.flushdb()
# Check a regular string
self.assertTrue(rj.jsonset('foo', Path.rootPath(), 'bar'))
self.assertEqual('string', rj.jsontype('foo', Path.rootPath()))
self.assertEqual('bar', rj.jsonget('foo', Path.rootPath()))
# Check the custom encoder
self.assertTrue(rj.jsonset('cus', Path.rootPath(),
CustomClass('foo', 'bar')))
obj = rj.jsonget('cus', Path.rootPath())
self.assertIsNotNone(obj)
self.assertEqual(CustomClass, obj.__class__)
self.assertEqual('foo', obj.key)
self.assertEqual('bar', obj.val)
def <API key>(self):
"Test the usage example"
# Create a new rejson-py client
rj = Client(host='localhost', port=port, decode_responses=True)
# Set the key `obj` to some object
obj = {
'answer': 42,
'arr': [None, True, 3.14],
'truth': {
'coord': 'out there'
}
}
rj.jsonset('obj', Path.rootPath(), obj)
# Get something
rv = rj.jsonget('obj', Path('.truth.coord'))
self.assertEqual(obj['truth']['coord'], rv)
# Delete something (or perhaps nothing), append something and pop it
value = "something"
rj.jsondel('obj', Path('.arr[0]'))
rj.jsonarrappend('obj', Path('.arr'), value)
rv = rj.jsonarrpop('obj', Path('.arr'))
self.assertEqual(value, rv)
# Update something else
value = 2.17
rj.jsonset('obj', Path('.answer'), value)
rv = rj.jsonget('obj', Path('.answer'))
self.assertEqual(value, rv)
# And use just like the regular redis-py client
jp = rj.pipeline()
jp.set('foo', 'bar')
jp.jsonset('baz', Path.rootPath(), 'qaz')
jp.execute()
rv1 = rj.get('foo')
self.assertEqual('bar', rv1)
rv2 = rj.jsonget('baz')
self.assertEqual('qaz', rv2)
if __name__ == '__main__':
unittest.main() |
from palm.base.model_factory import ModelFactory
from palm.base.model import Model
class CutoffModelFactory(ModelFactory):
"""CutoffModelFactory"""
def __init__(self):
pass
def create_model(self, parameter_set):
return CutoffModel(parameter_set)
class CutoffModel(Model):
"""CutoffModel"""
def __init__(self, parameter_set):
super(CutoffModel, self).__init__()
self.parameter_set = parameter_set
def get_parameter(self, parameter_name):
return self.parameter_set.get_parameter(parameter_name) |
<?php
namespace PhpSsrs\<API key>;
class ListDependentItems
{
/**
*
* @var string $ItemPath
* @access public
*/
public $ItemPath = null;
/**
*
* @param string $ItemPath
* @access public
*/
public function __construct($ItemPath = null)
{
$this->ItemPath = $ItemPath;
}
} |
// distance.js - Distance mixins for Paths
var _ = require('underscore');
var R = require('./constants').EARTHRADIUS;
var units = require('./units');
var flipCoords = require('./flipcoords');
// Area conversions (from sqmeters)
var convertFuncs = {
sqmeters: function (a) {
return a;
},
sqmiles: function (a) {
return units.sqMeters.toSqMiles(a);
},
acres: function (a) {
return units.sqMeters.toAcres(a);
}
};
// Calculates area in square meters
// Method taken from OpenLayers API, https://github.com/openlayers/openlayers/blob/master/lib/OpenLayers/Geometry/LinearRing.js#L270
var calcArea = function (coordArray) {
var area = 0, i, l, c1, c2;
for (i = 0, l = coordArray.length; i < l; i += 1) {
c1 = coordArray[i];
c2 = coordArray[(i + 1) % coordArray.length]; // Access next item in array until last item is i, then accesses first (0)
area = area + units.degrees.toRadians(c2[0] - c1[0]) * (2 + Math.sin(units.degrees.toRadians(c1[1])) + Math.sin(units.degrees.toRadians(c2[1])));
}
return Math.abs(area * R * R / 2);
};
var calcCenter = function (coordArray) {
var offset = coordArray[0], twiceArea = 0, x = 0, y = 0, i, l, c1, c2, f;
if (coordArray.length === 1) {
return coordArray[0];
}
for (i = 0, l = coordArray.length; i < l; i += 1) {
c1 = coordArray[i];
c2 = coordArray[(i + 1) % coordArray.length]; // Access next item in array until last item is i, then accesses first (0)
f = (c1[1] - offset[1]) * (c2[0] - offset[0]) - (c2[1] - offset[1]) * (c1[0] - offset[0]);
twiceArea = twiceArea + f;
x = x + ((c1[0] + c2[0] - 2 * offset[0]) * f);
y = y + ((c1[1] + c2[1] - 2 * offset[1]) * f);
}
f = twiceArea * 3;
return [x / f + offset[0], y / f + offset[1]];
};
module.exports = {
_internalAreaCalc: function () {
// If not set, set this._calcedArea to total area in UNITS
// Checks for cache to prevent additional unnecessary calcs
if (!this._calcedArea) {
if (this._coords.length < 3) {
this._calcedArea = 0;
} else {
this._calcedArea = calcArea(this._coords);
}
}
},
_internalCenterCalc: function () {
if (!this._calcedCenter && this._coords.length) {
this._calcedCenter = calcCenter(this._coords);
}
},
area: function (options) {
var opts = _.extend({
units: 'sqmeters'
}, options);
this._internalAreaCalc();
if (_.isFunction(convertFuncs[opts.units])) {
return convertFuncs[opts.units](this._calcedArea);
}
// TODO. Handle non-matching units
},
center: function () {
this._internalCenterCalc();
return this._options.imBackwards === true ? flipCoords(this._calcedCenter) : this._calcedCenter;
}
}; |
#ifndef SINGLETON_T_H
#define SINGLETON_T_H
#pragma once
#ifndef assert
#include <assert.h>
#endif
template <typename T,bool delay_create=true>
class CSingleTon_t
{
protected:
CSingleTon_t()
{
}
~CSingleTon_t()
{
}
public:
static T* GetInstance()
{
static T _instance;
return &_instance;
}
};
template <typename T>
class CSingleTon_t<T,false>
{
protected:
static T* m_instance;
public:
CSingleTon_t()
{
assert(m_instance==NULL);
m_instance = (T*)this;
}
~CSingleTon_t()
{
assert(m_instance==this);
m_instance = NULL;
}
static T* GetInstance()
{
return m_instance;
}
};
template <typename T> T* CSingleTon_t<T,false>::m_instance=NULL;
/*
class AObject:
public CSingleTon_t<AObject>
{
public:
void Op()
{
}
};
int _tmain(int argc, _TCHAR* argv[])
{
AObject::GetInstance()->Op();
return 0;
}
*/
#endif |
#!/usr/bin/python
import StringIO
import urllib
import urllib2
from lxml import etree
class NcaaGrabber:
def __init__(self):
self.ncaaUrl = 'http://web1.ncaa.org'
self.ncaaStatsSite = self.ncaaUrl+'/football/exec/rankingSummary'
# self.ncaaTeamList2008 = self.ncaaUrl+'/mfb/%d/Internet/ranking_summary/DIVISIONB.HTML'
# self.ncaaWeeklyBase2008 = self.ncaaUrl+'/mfb/%d/Internet/worksheets'
# self.ncaaWeekly2008 = self.ncaaWeeklyBase2008+'/DIVISIONB.HTML'
self.ncaaTeamListBase = self.ncaaUrl+'/mfb/%d/Internet/ranking_summary'
self.ncaaWeeklyBase = self.ncaaUrl+'/mfb/%d/Internet/worksheets'
self.fbsDiv = '/DIVISIONB.HTML'
self.fcsDiv = '/DIVISIONC.HTML'
def getTeams(self, division, year):
fullUrl = self.ncaaTeamListBase % year
if ( division == 'fbs' ):
fullUrl = fullUrl + self.fbsDiv
else:
fullUrl = fullUrl + self.fcsDiv
response = urllib2.urlopen(fullUrl)
responseHtml = response.read()
htmlParser = etree.HTMLParser()
htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
mainTablePaths = htmlTree.xpath('//body/table')
linkPaths = mainTablePaths[0].xpath('.//td/a')
data = {}
for link in linkPaths:
team = link.text
org = -1
linkStr = link.get('href')
linkStrArr = linkStr.split('&')
for linkStrPart in linkStrArr:
if ( linkStrPart.startswith('org=') ):
linkStrPart = linkStrPart.replace('org=', '')
if ( linkStrPart.isdigit() ):
org = linkStrPart
data[team] = org
return data
# def getTeams(self, year):
# data = {}
# data['year'] = year
# data['org'] = 8
# data['week'] = 1
# getData = urllib.urlencode(data)
# fullUrl = self.ncaaStatsSite + '?' + getData
# response = urllib2.urlopen(fullUrl)
# responseHtml = response.read()
# htmlParser = etree.HTMLParser()
# htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
# optionRows = htmlTree.xpath('/html/body/span[@class="noprint"]/select[@name="teamSelection"]/option')
# teams = {}
# for teamOption in optionRows:
# teamName = teamOption.text
# teamValue = int(teamOption.get("value"))
# if ( teamValue > -1 ):
# teams[teamName] = teamValue
# return teams
def getStats(self, team, year, week):
data = {}
data['org'] = team
data['week'] = week
data['year'] = year
getData = urllib.urlencode(data)
fullUrl = self.ncaaStatsSite + '?' + getData
response = urllib2.urlopen(fullUrl)
responseHtml = response.read()
htmlParser = etree.HTMLParser()
htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
teamTableRows = htmlTree.xpath('//table[@id="teamRankings"]/tr[position()>4]')
stats = {}
for statRow in teamTableRows:
dataCells = statRow.xpath('./td')
if ( len(dataCells) < 1 ):
continue
category = dataCells[0].xpath('./a')[0].text
value = dataCells[2].text
rank = dataCells[1].text.lstrip('T-')
stats[category] = (value, rank)
return stats
def isHomeGame(self, team, year, week):
data = {}
data['org'] = team
data['week'] = week
data['year'] = year
getData = urllib.urlencode(data)
fullUrl = self.ncaaStatsSite + '?' + getData
print(fullUrl)
response = urllib2.urlopen(fullUrl)
responseHtml = response.read()
htmlParser = etree.HTMLParser()
htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
scheduleTableRows = htmlTree.xpath('//table[@id="schedule"]/tr/td[position()=1]/a/../../td[position()=2]')
lastScheduleRow = scheduleTableRows[-1]
isHome = False
if ( lastScheduleRow is not None ):
if ( lastScheduleRow.text is None ):
linkElement = lastScheduleRow.xpath('./a')[0]
gameLocation = linkElement.text
if ( gameLocation.isupper() and gameLocation.find("@") < 0 ):
if ( gameLocation.find("^") < 0 ):
isHome = 1
else:
isHome = 2
else:
isHome = 0
else:
gameLocation = lastScheduleRow.text
if ( gameLocation.isupper() and gameLocation.find("@") < 0 ):
if ( gameLocation.find("^") < 0 ):
isHome = 1
else:
isHome = 2
else:
isHome = 0
return isHome
def getNumWeeks(self, division, year):
fullUrl = self.ncaaWeeklyBase % year
if ( division == 'fbs' ):
fullUrl = fullUrl + self.fbsDiv
else:
fullUrl = fullUrl + self.fcsDiv
response = urllib2.urlopen(fullUrl)
responseHtml = response.read()
htmlParser = etree.HTMLParser()
htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
tableRowArr = htmlTree.xpath('//body/table/tr')
count = len(tableRowArr) - 1
return count
def processWeekly(self, year, week, teams):
return self.processWeekly("fbs", year, week, team)
def processWeekly(self, division, year, week, teams):
schedule = []
week = week - 1
fullUrl = self.ncaaWeeklyBase % year
if ( division == 'fbs' ):
fullUrl = fullUrl + self.fbsDiv
else:
fullUrl = fullUrl + self.fcsDiv
response = urllib2.urlopen(fullUrl)
responseHtml = response.read()
htmlParser = etree.HTMLParser()
htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
tableRowArr = htmlTree.xpath('//body/table/tr')
weekRow = tableRowArr[week+1]
weekLinkCol = weekRow.find('td')
weekLink = weekLinkCol.find('a')
weekUrl = (self.ncaaWeeklyBase + '/' + weekLink.values()[0]) % year
response = urllib2.urlopen(weekUrl)
responseHtml = response.read()
htmlTree = etree.parse(StringIO.StringIO(responseHtml), htmlParser)
trList = htmlTree.xpath('//body/table[@width="80%"]/tr')
for tr in trList[1:]:
tds = tr.findall('td')
if(len(tds) > 2):
team1 = tds[0].find('a').text
team2 = tds[1].text
result = ""
if ( len(tds) > 3 ):
result = tds[3].text
if ( team1 not in teams ):
continue
org1 = teams[team1]
org2 = None
if ( team2 in teams ):
org2 = teams[team2]
schedule.append((org1, org2, result))
return schedule |
from <API key> import <API key>
class SurveyInstance(object):
def __init__(self, survey_object, **kwargs):
self._survey = survey_object
self.kwargs = kwargs #not sure what might be passed to this
#does the survey object provide a way to get the key dicts?
self._keys = [c.name for c in self._survey.children]
self._name = self._survey.name
self._id = self._survey.id_string
# get xpaths
# - prep for xpaths.
self._survey.xml()
self._xpaths = self._survey._xpath.values()
#see "answers(self):" below for explanation of this dict
self._answers = {}
self._orphan_answers = {}
def keys(self):
return self._keys
def xpaths(self):
#originally thought of having this method get the xpath stuff
#but survey doesn't like when xml() is called multiple times.
return self._xpaths
def answer(self, name=None, value=None):
if name is None:
raise Exception("In answering, name must be given")
#ahh. this is horrible, but we need the xpath dict in survey to be up-to-date
#...maybe
# self._survey.xml()
if name in self._survey._xpath.keys():
self._answers[name] = value
else:
self._orphan_answers[name] = value
def to_json_dict(self):
children = []
for k, v in self._answers.items():
children.append({'node_name':k, 'value':v})
return {
'node_name': self._name,
'id': self._id,
'children': children
}
def to_xml(self):
"""
A horrible way to do this, but it works (until we need the attributes pumped out in order, etc)
"""
open_str = """<?xml version='1.0' ?><%s id="%s">""" % (self._name, self._id)
close_str = % self._name
vals = ""
for k, v in self._answers.items():
vals += "<%s>%s</%s>" % (k, str(v), k)
output = open_str + vals + close_str
return output
def answers(self):
"""
This returns "_answers", which is a dict with the key-value
responses for this given instance. This could be pumped to xml
or returned as a dict for maximum convenience (i.e. testing.)
"""
return self._answers
def import_from_xml(self, <API key>):
import os.path
if os.path.isfile(<API key>):
xml_str = open(<API key>).read()
else:
xml_str = <API key>
key_val_dict = <API key>(xml_str)
for k, v in key_val_dict.items():
self.answer(name=k, value=v)
def __unicode__(self):
orphan_count = len(self._orphan_answers.keys())
placed_count = len(self._answers.keys())
answer_count = orphan_count + placed_count
return "<Instance (%d answers: %d placed. %d orphans)>" % (answer_count, placed_count, orphan_count) |
Accuracy of exchange prices
1) Accuracy of all exchange prices
select cast(1/odds*100 as int) as predicted_prob,(cast(sum(cast(win_flag as int)) as real)/COUNT(*))*100 as true_prob,COUNT(*) as sample_size
from dbo.betfair_data group by cast(1/odds*100 as int) order by predicted_prob
2) Accuracy of starting prices
Get starting market prices
select * from (select *, row_number() over (partition by event_id,selection_id order by latest_taken desc) as row from betfair_data) A where row=1
Get accuracy of prices
select cast(1/odds*100 as int) as predicted_prob,(cast(sum(cast(win_flag as int)) as real)/COUNT(*))*100 as true_prob,COUNT(*) as sample_size
from (select price.* from market_prices() price) A
group by cast(1/odds*100 as int) order by predicted_prob |
"""
Script to fetch historical data (since 2011) for matches (global, public).
Gives results in a chronological order (ascending), as they happened.
"""
from __future__ import print_function
from dota2py import api
from time import sleep as wait_for_next_fetch
def <API key>(<API key>=None, matches_requested=500,
fetch_delay=1, debug=True, **kwargs):
"""
Returns list of most recent public matches according to given kwargs
Rate limits the API requests according to `fetch_delay` (in seconds)
Output : <API key>, <API key>, match_history
"""
# tracking variables
matches_fetched = 0
last_match_seq_num = <API key>
<API key> = 1
match_history = []
<API key> = "Fetch successful"
while <API key> == 1 and matches_fetched < matches_requested:
cur_response = api.<API key>(
<API key>=last_match_seq_num, **kwargs
)
<API key> = cur_response['result']['status']
if not <API key> == 1:
# unsuccessful query
if not 'statusDetail' in cur_response['result']:
<API key> = "Unknown error"
else:
<API key> = cur_response['result']['statusDetail']
break
else:
# successful data fetch
cur_matches = cur_response['result']['matches']
if len(cur_response['result']['matches']) >= 1:
if not match_history:
# very first fetch
match_history.extend(cur_matches)
matches_fetched += len(cur_matches)
else:
# 2nd fetch onwards, ignore the first common match
match_history.extend(cur_matches[1:])
matches_fetched += len(cur_matches) - 1
if len(cur_matches) == 1 and cur_matches[0]['match_id'] == last_match_id:
break
else:
break
last_match_seq_num = cur_matches[-1]['match_seq_num']
if debug:
print("Matches fetched - #{}...".format(matches_fetched))
wait_for_next_fetch(fetch_delay)
if debug:
print("{0}: {1}".format(<API key>, <API key>))
return {'status':<API key>, 'statusDetail':<API key>,
'matches':match_history} |
#include <fstream>
#include <memory>
#include <unordered_set>
#include <vector>
#include <string>
#include <random>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <string>
// libbf
#include "BaseBloomFilter.hpp"
#include "KBF1.hpp"
#include "KBF2.hpp"
#include "KBFSparse.hpp"
#include "KBFSparseRelaxed.hpp"
#include "KBFUtil.hpp"
#include "JellyfishUtil.h"
using namespace std;
// query a set of test kmers and write out results
void queryKmers(vector<kmer_t> & test_kmers, unordered_set<kmer_t> & true_kmers, BaseBloomFilter & sbf, const string & out_fname) {
vector<bool> states;
// time this part
auto start = std::chrono::system_clock::now();
for (auto qk : test_kmers) {
bool state = sbf.contains(qk);
states.push_back(state);
}
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "query time: " << elapsed_seconds.count() << " s" << endl;
// end the timing here
// write states and true answers to file
ofstream f_out(out_fname);
f_out << "kmer\tBF_state\ttrue_state" << endl;
for (int i = 0; i < states.size(); i++)
f_out << test_kmers[i] << "\t" <<
states[i] << "\t" <<
(true_kmers.find(test_kmers[i]) != true_kmers.end() ) << endl;
f_out.close();
}
// Sample a subset of the kmers
vector<kmer_t> sample_kmers(unordered_set<kmer_t> & kmer_set, int const set_size, const int K, bool TP=false) {
vector<kmer_t> query_kmers;
// store the kmer set in a vector so that can sample from it
vector<kmer_t> kmer_vec;
for(auto km : kmer_set) kmer_vec.push_back(km);
// set up a random number gen
std::random_device rd;
std::mt19937 gen(rd());
std::<API key><> sample_dis(0, kmer_set.size() - 1);
std::<API key><> shift_dis(0,K-1);
std::<API key><> base_dis(0,3);
const char base_table[4] = { 'A', 'C', 'G', 'T' };
//sample the input kmers
int i = query_kmers.size();
while (i < set_size) {
auto r = sample_dis(gen);
assert(r < kmer_set.size());
kmer_t sample_kmer = kmer_vec[r];
// mutate the sampled kmer
if(!TP){
string string_kmer = <API key>(sample_kmer, K);
auto base = base_table[base_dis(gen)];
auto ind = shift_dis(gen);
while(string_kmer[ind] == base){
base = base_table[base_dis(gen)];
}
string_kmer[ind] = base;
sample_kmer = <API key>(string_kmer.c_str(),K);
}
query_kmers.push_back(sample_kmer);
i++;
}
return query_kmers;
}
// main
// Usage:
//./kbf <input fasta> <query fasta> <k> [outfile prefix = 'test'] [# queries = 1000000] [use all TP = false]
int main(int argc, char* argv[]) {
cerr << "==============================" << endl;
cerr << "Starting Sequence Bloom Filter" << endl;
cerr << "==============================" << endl;
if (argc < 3) {
cerr << "\tMissing required arguments." << endl;
cerr << "\tUsage:" << endl;
cerr << "\tkbf <reads.fa> <k> [outfile prefix = 'test'] [# queries = 1M] [use all TP = 'false']" << endl;
exit(1);
}
string input_fasta = argv[1];
int K = stoi(argv[2]);
unsigned long query_set_size = 1000000;
string prefix = "test";
bool TP = false;
if(argc > 3){
prefix = argv[3];
}
if (argc > 4) {
query_set_size = stoi(argv[4]);
}
if(argc > 5) {
string TP_string = argv[5];
if (TP_string.compare("true") == 0)
TP = true;
else
assert(TP_string.compare("false") == 0);
}
unordered_set<kmer_t> read_kmers;
// parse input reads -- will build a kmer set from that
cerr << "Parsing input fasta " << input_fasta << endl;
auto start = std::chrono::system_clock::now();
vector<string> reads = parseFasta(input_fasta);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "Parsing: " << elapsed_seconds.count() << " s" << endl;
cerr << "Getting kmers... " << endl;
start = std::chrono::system_clock::now();
read_kmers = getKmers(reads, K);
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
cerr << "Input kmers: " << read_kmers.size() << endl;
cerr << "Getting kmers: " << elapsed_seconds.count() << " s" << endl;
// parse test reads and count the test kmers
cerr << "Generating test kmers..." << endl;
vector<kmer_t> query_kmers = sample_kmers(read_kmers, query_set_size,K,TP);
{
// Test the classic bloom filter
cerr << "
auto start = std::chrono::system_clock::now();
BaseBloomFilter b(K,read_kmers.size(),10);
b.populate(read_kmers);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "Build and populate Classic Bloom filter: " << elapsed_seconds.count() << " s" << endl;
queryKmers(query_kmers, read_kmers, b, prefix+"_classic.txt");
}
{
// Test KBF1
cerr << "
auto start = std::chrono::system_clock::now();
KBF1 kbf1(K,read_kmers,1);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "Build and populate KBF1: " << elapsed_seconds.count() << " s" << endl;
queryKmers(query_kmers, read_kmers, kbf1, prefix+"_kbf1.txt");
}
{
// Test KBF2
unordered_set<kmer_t> edge_kmers;
read_kmers.clear();
cerr << "
auto start = std::chrono::system_clock::now();
<API key>(reads, K, 1, read_kmers, edge_kmers);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "Parse fasta, get kmers, potential edge kmers for KBF2: " << elapsed_seconds.count() << " s" << endl;
cerr << "Potential edge kmers: " << edge_kmers.size() << endl;
start = std::chrono::system_clock::now();
KBF2 kbf2(K, read_kmers, edge_kmers, 1);
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
cerr << "Build and populate KBF2: " << elapsed_seconds.count() << " s" << endl;
queryKmers(query_kmers, read_kmers, kbf2, prefix+"_kbf2.txt");
}
{
// Test sparse KBF - single sequence only
// Uncomment for single sequence input fasta
unordered_set<kmer_t> sparse_kmers;
unordered_set<kmer_t> edge_kmers;
cerr << "
auto start = std::chrono::system_clock::now();
<API key>(reads,K,1,sparse_kmers,edge_kmers);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "Parse fasta, get kmers, and potential edge kmers for single sequence sparse KBF: " << elapsed_seconds.count() << " s" << endl;
cerr << "Potential edge kmers: " << edge_kmers.size() << endl;
start = std::chrono::system_clock::now();
KBFSparse kbfs(K, sparse_kmers, edge_kmers,1,10);
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
cerr << "Build and populate single sequence sparse KBF: " << elapsed_seconds.count() << " s" << endl;
queryKmers(query_kmers, read_kmers, kbfs, prefix+"_kbfs_singleseq.txt");
}
{
// Test sparse KBF - best fit kmers
unordered_set<kmer_t> sparse_kmers;
unordered_set<kmer_t> edge_kmers;
cerr << "
auto start = std::chrono::system_clock::now();
<API key>(reads,K,1,sparse_kmers,edge_kmers);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cerr << "Parse fasta, get kmers, and potential edge kmers for best fit sparse KBF: " << elapsed_seconds.count() << " s" << endl;
cerr << "Potential edge kmers: " << edge_kmers.size() << endl;
start = std::chrono::system_clock::now();
KBFSparse kbfs(K, sparse_kmers, edge_kmers, 1, 10);
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
cerr << "Build and populate bestfit sparse KBF: " << elapsed_seconds.count() << " s" << endl;
queryKmers(query_kmers, read_kmers, kbfs, prefix+"_kbfs_bestfit.txt");
}
} |
<!DOCTYPE HTML PUBLIC "-
<html>
<head>
<title>org.gradle.language.jvm.plugins (Gradle API 2.1)</title>
<meta name="keywords" content="org.gradle.language.jvm.plugins package">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" title="Style">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
<script type="text/javascript">
function windowTitle()
{
parent.document.title="org.gradle.language.jvm.plugins (Gradle API 2.1)";
}
</script>
<noscript>
</noscript>
</head>
<body class="center" onload="windowTitle();">
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<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="../../../../../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="../../../../../index.html?org/gradle/language/jvm/plugins/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
</div>
<div class="header">
<h1 class="title">Package org.gradle.language.jvm.plugins</h1>
</div>
<div class="header">
<h2 title=" Base plugins that add language support for JVM resources.
@Incubating
" class="title"> Base plugins that add language support for JVM resources.
@Incubating
</h2>
</div>
<div class="contentContainer">
<div class="summary">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Class Summary">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tbody>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr class="altColor">
<td class="colOne">
<strong><a href="JvmResourcesPlugin.html" title="class in org/gradle/language/jvm/plugins">
JvmResourcesPlugin
</a></strong>
</td>
<td>Plugin for packaging JVM resources. </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</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="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">
<div>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
</div>
<div class="aboutLanguage"><em>Gradle API 2.1</em></div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html> |
package com.github.ansell.dwca;
import org.xml.sax.Attributes;
import com.github.ansell.dwca.<API key>.CoreOrExtension;
public class DarwinCoreField implements ConstraintChecked, Comparable<DarwinCoreField> {
// Constants for compareTo method
private static final int BEFORE = -1;
private static final int AFTER = 1;
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DarwinCoreField [");
if (index != null) {
builder.append("index=");
builder.append(index);
builder.append(", ");
}
if (term != null) {
builder.append("term=");
builder.append(term);
builder.append(", ");
}
if (defaultValue != null) {
builder.append("defaultValue=");
builder.append(defaultValue);
builder.append(", ");
}
if (vocabulary != null) {
builder.append("vocabulary=");
builder.append(vocabulary);
}
if (delimitedBy != null) {
builder.append("delimitedBy=");
builder.append(delimitedBy);
}
builder.append("]");
return builder.toString();
}
private Integer index;
private String term;
private String defaultValue;
private String vocabulary;
private String delimitedBy;
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
if (this.index != null) {
throw new <API key>("Cannot specify multiple indexes for a field: " + this.toString());
}
this.index = index;
}
public boolean hasTerm() {
return this.term != null;
}
public String getTerm() {
if (this.term == null) {
throw new <API key>("Term was required for field, but was not set: " + this.toString());
}
return term;
}
public void setTerm(String term) {
if (this.term != null && !this.term.equals(term)) {
throw new <API key>("Cannot specify multiple terms for a field: " + this.toString());
}
this.term = term;
}
public boolean hasDefault() {
return defaultValue != null;
}
public String getDefault() {
return defaultValue;
}
public void setDefault(String defaultValue) {
if (this.defaultValue != null && !this.defaultValue.equals(defaultValue)) {
throw new <API key>("Cannot specify multiple default values for a field: " + this.toString());
}
this.defaultValue = defaultValue;
}
public String getVocabulary() {
return vocabulary;
}
public void setVocabulary(String vocabularyUri) {
if (this.vocabulary != null && !this.vocabulary.equals(vocabularyUri)) {
throw new <API key>("Cannot specify multiple vocabularies for a field: " + this.toString());
}
this.vocabulary = vocabularyUri;
}
public String getDelimitedBy() {
return delimitedBy;
}
public void setDelimitedBy(String delimitedBy) {
if (this.delimitedBy != null && !this.delimitedBy.equals(delimitedBy)) {
throw new <API key>(
"Cannot specify multiple delimitedBy values for a field: " + this.toString());
}
this.delimitedBy = delimitedBy;
}
public static DarwinCoreField fromAttributes(Attributes attributes) {
DarwinCoreField result = new DarwinCoreField();
for (int i = 0; i < attributes.getLength(); i++) {
// String namespace = attributes.getURI(i);
String localName = attributes.getLocalName(i);
if (<API key>.INDEX.equals(localName)) {
result.setIndex(Integer.parseInt(attributes.getValue(i)));
} else if (<API key>.TERM.equals(localName)) {
result.setTerm(attributes.getValue(i));
} else if (<API key>.DEFAULT.equals(localName)) {
result.setDefault(attributes.getValue(i));
} else if (<API key>.VOCABULARY.equals(localName)) {
result.setVocabulary(attributes.getValue(i));
} else if (<API key>.DELIMITED_BY.equals(localName)) {
result.setDelimitedBy(attributes.getValue(i));
} else {
System.out.println("Found unrecognised Darwin Core attribute for field, skipping : " + localName);
}
}
return result;
}
@Override
public void checkConstraints() {
if (getTerm() == null) {
throw new <API key>("All fields must have term set: " + this.toString());
}
if (getIndex() == null && getDefault() == null) {
throw new <API key>(
"Fields that do not have indexes must have default values set: " + this.toString());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
result = prime * result + ((delimitedBy == null) ? 0 : delimitedBy.hashCode());
result = prime * result + ((index == null) ? 0 : index.hashCode());
result = prime * result + ((term == null) ? 0 : term.hashCode());
result = prime * result + ((vocabulary == null) ? 0 : vocabulary.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof DarwinCoreField)) {
return false;
}
DarwinCoreField other = (DarwinCoreField) obj;
if (defaultValue == null) {
if (other.defaultValue != null) {
return false;
}
} else if (!defaultValue.equals(other.defaultValue)) {
return false;
}
if (delimitedBy == null) {
if (other.delimitedBy != null) {
return false;
}
} else if (!delimitedBy.equals(other.delimitedBy)) {
return false;
}
if (index == null) {
if (other.index != null) {
return false;
}
} else if (!index.equals(other.index)) {
return false;
}
if (term == null) {
if (other.term != null) {
return false;
}
} else if (!term.equals(other.term)) {
return false;
}
if (vocabulary == null) {
if (other.vocabulary != null) {
return false;
}
} else if (!vocabulary.equals(other.vocabulary)) {
return false;
}
return true;
}
/**
* Compares DarwinCoreFields that are contained within a single
* {@link CoreOrExtension}. It assumes that indexes are never reused, and
* that if the indexes are not available, that a unique term name will be
* used as a tie-breaker.
*/
@Override
public int compareTo(DarwinCoreField o) {
// Ensure we only compare valid objects
this.checkConstraints();
o.checkConstraints();
if (this.getIndex() == null) {
if (o.getIndex() == null) {
return this.getTerm().compareTo(o.getTerm());
} else {
return AFTER;
}
} else if (o.getIndex() == null) {
return BEFORE;
} else {
return this.getIndex().compareTo(o.getIndex());
}
}
} |
ROOT=../..
FLAGS_COMMON= #-test.v
# Actually, we should've used -test.parallel=1 here, but for some reason
# it doesn't work. Instead, we use the undocumented flag -p=1, see
# for details.
FLAGS_INTEGRATION=-p=1
DCFLAGS=
V=@
ifeq ("$(VERBOSE)","1")
V=
endif
.PHONY: all up down unit-tests integration-tests
all: unit-tests integration-tests
up:
docker-compose $(DCFLAGS) build && docker-compose $(DCFLAGS) up -d
down:
docker-compose $(DCFLAGS) down
integration-tests: export GM_POSTGRES_URL=postgres://geekmarks-test:geekmarks-test@localhost:6001/geekmarks-test?sslmode=disable
integration-tests: up
$(V) echo "Integration tests:"
$(V) go test -race -tags integration_tests $(ROOT)/... $(FLAGS_COMMON) $(FLAGS_INTEGRATION)
unit-tests:
$(V) echo "Unit tests:"
$(V) go test -race -tags="unit_tests" $(ROOT)/... $(FLAGS_COMMON) |
class Hh < Formula
desc "Bash and zsh history suggest box"
homepage "https://github.com/dvorka/hstr"
url "https://github.com/dvorka/hstr/archive/1.21.tar.gz"
sha256 "<SHA256-like>"
head "https://github.com/dvorka/hstr.git"
bottle do
cellar :any
sha256 "<SHA256-like>" => :sierra
sha256 "<SHA256-like>" => :el_capitan
sha256 "<SHA256-like>" => :yosemite
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "readline"
def install
system "autoreconf", "-fvi"
system "./configure", "--<API key>",
"--prefix=#{prefix}"
system "make", "install"
end
test do
ENV["HISTFILE"] = testpath/".hh_test"
(testpath/".hh_test").write("test\n")
assert_equal "test", shell_output("#{bin}/hh -n").chomp
end
end |
#include "config.h"
#if ENABLE(MATHML)
#include "MathMLSpaceElement.h"
#include "RenderMathMLSpace.h"
namespace WebCore {
using namespace MathMLNames;
MathMLSpaceElement::MathMLSpaceElement(const QualifiedName& tagName, Document& document)
: MathMLElement(tagName, document)
{
}
Ref<MathMLSpaceElement> MathMLSpaceElement::create(const QualifiedName& tagName, Document& document)
{
return adoptRef(*new MathMLSpaceElement(tagName, document));
}
const MathMLElement::Length& MathMLSpaceElement::width()
{
return cachedMathMLLength(MathMLNames::widthAttr, m_width);
}
const MathMLElement::Length& MathMLSpaceElement::height()
{
return cachedMathMLLength(MathMLNames::heightAttr, m_height);
}
const MathMLElement::Length& MathMLSpaceElement::depth()
{
return cachedMathMLLength(MathMLNames::depthAttr, m_depth);
}
void MathMLSpaceElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == widthAttr)
m_width.dirty = true;
else if (name == heightAttr)
m_height.dirty = true;
else if (name == depthAttr)
m_depth.dirty = true;
MathMLElement::parseAttribute(name, value);
}
RenderPtr<RenderElement> MathMLSpaceElement::<API key>(RenderStyle&& style, const RenderTreePosition&)
{
ASSERT(hasTagName(MathMLNames::mspaceTag));
return createRenderer<RenderMathMLSpace>(*this, WTFMove(style));
}
}
#endif // ENABLE(MATHML) |
<!DOCTYPE HTML PUBLIC "-
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<html>
<head>
<!-- Generated by groovydoc (2.3.6) on Mon Nov 24 10:51:33 CET 2014 -->
<title>JvmLibrarySpec (Gradle API 2.2.1)</title>
<meta name="date" content="2014-11-24">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<body class="center">
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="JvmLibrarySpec (Gradle API 2.2.1)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../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">
<div>
<ul class="navList">
<li><a href="../../../index.html?org/gradle/jvm/JvmLibrarySpec" target="_top">Frames</a></li>
<li><a href="JvmLibrarySpec.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field Method
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field Method
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">Package: <strong>org.gradle.jvm</strong></div>
<h2 title="[Java] Interface JvmLibrarySpec" class="title">[Java] Interface JvmLibrarySpec</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><ul class="inheritance"></ul></li><li><ul class="inheritance"></ul></li><li><ul class="inheritance"></ul></li><li><ul class="inheritance"></ul></li><li><ul class="inheritance"></ul></li><li>org.gradle.jvm.JvmLibrarySpec
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href='../../../org/gradle/platform/base/<API key>.html'><API key></a>, <a href='../../../org/gradle/platform/base/ComponentSpec.html'>ComponentSpec</a>, <a href='../../../org/gradle/platform/base/LibrarySpec.html'>LibrarySpec</a>, <a href='../../../org/gradle/jvm/JvmComponentSpec.html'>JvmComponentSpec</a>, <a href='../../../org/gradle/api/Named.html'>Named</a></dd>
</dl>
<p> Definition of a JVM library component that is to be built by Gradle.
</p>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="method_summary"></a>
<h3>Inherited Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited Methods Summary table">
<caption><span>Inherited Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Methods inherited from class</th>
<th class="colLast" scope="col">Name</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface <a href='../../../org/gradle/platform/base/<API key>.html'><API key></a></strong></code></td>
<td class="colLast"><code><a href='../../../org/gradle/platform/base/<API key>.html#getTargetPlatforms()'>getTargetPlatforms</a>, <a href='../../../org/gradle/platform/base/<API key>.html#targetPlatform(java.lang.String)'>targetPlatform</a></code></td>
</tr>
</table>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../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">
<div>
<ul class="navList">
<li><a href="../../../index.html?org/gradle/jvm/JvmLibrarySpec" target="_top">Frames</a></li>
<li><a href="JvmLibrarySpec.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field Method
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field Method
</ul>
</div>
<p>Gradle API 2.2.1</p>
<a name="skip-navbar_bottom">
</a>
</div>
</div>
</body>
</html> |
from llvmlite import binding as ll
from llvmlite import ir
from warnings import warn
from numba.core import config, serialize
from numba.core.codegen import Codegen, CodeLibrary
from numba.core.errors import <API key>
from .cudadrv import devices, driver, nvvm
import ctypes
import numpy as np
import os
import subprocess
import tempfile
CUDA_TRIPLE = 'nvptx64-nvidia-cuda'
def disassemble_cubin(cubin):
# nvdisasm only accepts input from a file, so we need to write out to a
# temp file and clean up afterwards.
fd = None
fname = None
try:
fd, fname = tempfile.mkstemp()
with open(fname, 'wb') as f:
f.write(cubin)
try:
cp = subprocess.run(['nvdisasm', fname], check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except FileNotFoundError as e:
if e.filename == 'nvdisasm':
msg = ("nvdisasm is required for SASS inspection, and has not "
"been found.\n\nYou may need to install the CUDA "
"toolkit and ensure that it is available on your "
"PATH.\n")
raise RuntimeError(msg)
return cp.stdout.decode('utf-8')
finally:
if fd is not None:
os.close(fd)
if fname is not None:
os.unlink(fname)
class CUDACodeLibrary(serialize.ReduceMixin, CodeLibrary):
"""
The CUDACodeLibrary generates PTX, SASS, cubins for multiple different
compute capabilities. It also loads cubins to multiple devices (via
get_cufunc), which may be of different compute capabilities.
"""
def __init__(self, codegen, name, entry_name=None, max_registers=None,
nvvm_options=None):
"""
codegen:
Codegen object.
name:
Name of the function in the source.
entry_name:
Name of the kernel function in the binary, if this is a global
kernel and not a device function.
max_registers:
The maximum register usage to aim for when linking.
nvvm_options:
Dict of options to pass to NVVM.
"""
super().__init__(codegen, name)
# The llvmlite module for this library.
self._module = None
# CodeLibrary objects that will be "linked" into this library. The
# modules within them are compiled from NVVM IR to PTX along with the
# IR from this module - in that sense they are "linked" by NVVM at PTX
# generation time, rather than at link time.
self._linking_libraries = set()
# Files to link with the generated PTX. These are linked using the
# Driver API at link time.
self._linking_files = set()
# Maps CC -> PTX string
self._ptx_cache = {}
# Maps CC -> cubin
self._cubin_cache = {}
# Maps CC -> linker info output for cubin
self._linkerinfo_cache = {}
# Maps Device numeric ID -> cufunc
self._cufunc_cache = {}
self._max_registers = max_registers
if nvvm_options is None:
nvvm_options = {}
self._nvvm_options = nvvm_options
self._entry_name = entry_name
def get_llvm_str(self):
return str(self._module)
def get_asm_str(self, cc=None):
return self._join_ptxes(self._get_ptxes(cc=cc))
def _get_ptxes(self, cc=None):
if not cc:
ctx = devices.get_context()
device = ctx.device
cc = device.compute_capability
ptxes = self._ptx_cache.get(cc, None)
if ptxes:
return ptxes
arch = nvvm.get_arch_option(*cc)
options = self._nvvm_options.copy()
options['arch'] = arch
if not nvvm.NVVM().is_nvvm70:
# Avoid enabling debug for NVVM 3.4 as it has various issues. We
# need to warn the user that we're doing this if any of the
# functions that they're compiling have `debug=True` set, which we
# can determine by checking the NVVM options.
for lib in self.linking_libraries:
if lib._nvvm_options.get('debug'):
msg = ("debuginfo is not generated for CUDA versions "
f"< 11.2 (debug=True on function: {lib.name})")
warn(<API key>(msg))
options['debug'] = False
irs = [str(mod) for mod in self.modules]
if options.get('debug', False):
# If we're compiling with debug, we need to compile modules with
# NVVM one at a time, because it does not support multiple modules
# with debug enabled:
ptxes = [nvvm.llvm_to_ptx(ir, **options) for ir in irs]
else:
# Otherwise, we compile all modules with NVVM at once because this
# results in better optimization than separate compilation.
ptxes = [nvvm.llvm_to_ptx(irs, **options)]
# Sometimes the result from NVVM contains trailing whitespace and
# nulls, which we strip so that the assembly dump looks a little
# tidier.
ptxes = [x.decode().strip('\x00').strip() for x in ptxes]
if config.DUMP_ASSEMBLY:
print(("ASSEMBLY %s" % self._name).center(80, '-'))
print(self._join_ptxes(ptxes))
print('=' * 80)
self._ptx_cache[cc] = ptxes
return ptxes
def _join_ptxes(self, ptxes):
return "\n\n".join(ptxes)
def get_cubin(self, cc=None):
if cc is None:
ctx = devices.get_context()
device = ctx.device
cc = device.compute_capability
cubin = self._cubin_cache.get(cc, None)
if cubin:
return cubin
linker = driver.Linker(max_registers=self._max_registers, cc=cc)
ptxes = self._get_ptxes(cc=cc)
for ptx in ptxes:
linker.add_ptx(ptx.encode())
for path in self._linking_files:
linker.add_file_guess_ext(path)
cubin_buf, size = linker.complete()
# We take a copy of the cubin because it's owned by the linker
cubin_ptr = ctypes.cast(cubin_buf, ctypes.POINTER(ctypes.c_char))
cubin = bytes(np.ctypeslib.as_array(cubin_ptr, shape=(size,)))
self._cubin_cache[cc] = cubin
self._linkerinfo_cache[cc] = linker.info_log
return cubin
def get_cufunc(self):
if self._entry_name is None:
msg = "Missing entry_name - are you trying to get the cufunc " \
"for a device function?"
raise RuntimeError(msg)
ctx = devices.get_context()
device = ctx.device
cufunc = self._cufunc_cache.get(device.id, None)
if cufunc:
return cufunc
cubin = self.get_cubin(cc=device.compute_capability)
module = ctx.create_module_image(cubin)
# Load
cufunc = module.get_function(self._entry_name)
# Populate caches
self._cufunc_cache[device.id] = cufunc
return cufunc
def get_linkerinfo(self, cc):
try:
return self._linkerinfo_cache[cc]
except KeyError:
raise KeyError(f'No linkerinfo for CC {cc}')
def get_sass(self, cc=None):
return disassemble_cubin(self.get_cubin(cc=cc))
def add_ir_module(self, mod):
self._raise_if_finalized()
if self._module is not None:
raise RuntimeError('CUDACodeLibrary only supports one module')
self._module = mod
def add_linking_library(self, library):
library._ensure_finalized()
# We don't want to allow linking more libraries in after finalization
# won't be able to finalize again after adding new ones
self._raise_if_finalized()
self._linking_libraries.add(library)
def add_linking_file(self, filepath):
self._linking_files.add(filepath)
def get_function(self, name):
for fn in self._module.functions:
if fn.name == name:
return fn
raise KeyError(f'Function {name} not found')
@property
def modules(self):
return [self._module] + [mod for lib in self._linking_libraries
for mod in lib.modules]
@property
def linking_libraries(self):
# Libraries we link to may link to other libraries, so we recursively
# traverse the linking libraries property to build up a list of all
# linked libraries.
libs = []
for lib in self._linking_libraries:
libs.extend(lib.linking_libraries)
libs.append(lib)
return libs
def finalize(self):
# Unlike the CPUCodeLibrary, we don't invoke the binding layer here -
# we only adjust the linkage of functions. Global kernels (with
# external linkage) have their linkage untouched. Device functions are
# set linkonce_odr to prevent them appearing in the PTX.
self._raise_if_finalized()
# Note in-place modification of the linkage of functions in linked
# libraries. This presently causes no issues as only device functions
# are shared across code libraries, so they would always need their
# linkage set to linkonce_odr. If in a future scenario some code
# libraries require linkonce_odr linkage of functions in linked
# modules, and another code library requires another linkage, each code
# library will need to take its own private copy of its linked modules.
# See also discussion on PR #890:
# We don't adjust the linkage of functions when compiling for debug -
# because the device functions are in separate modules, we need them to
# be externally visible.
for library in self._linking_libraries:
for mod in library.modules:
for fn in mod.functions:
if not fn.is_declaration:
if self._nvvm_options.get('debug', False):
fn.linkage = 'weak_odr'
else:
fn.linkage = 'linkonce_odr'
self._finalized = True
def _reduce_states(self):
"""
Reduce the instance for serialization. We retain the PTX and cubins,
but loaded functions are discarded. They are recreated when needed
after deserialization.
"""
if self._linking_files:
msg = ('cannot pickle CUDACodeLibrary function with additional '
'libraries to link against')
raise RuntimeError(msg)
return dict(
codegen=self._codegen,
name=self.name,
entry_name=self._entry_name,
module=self._module,
linking_libraries=self._linking_libraries,
ptx_cache=self._ptx_cache,
cubin_cache=self._cubin_cache,
linkerinfo_cache=self._linkerinfo_cache,
max_registers=self._max_registers,
nvvm_options=self._nvvm_options
)
@classmethod
def _rebuild(cls, codegen, name, entry_name, module, linking_libraries,
ptx_cache, cubin_cache, linkerinfo_cache, max_registers,
nvvm_options):
"""
Rebuild an instance.
"""
instance = cls.__new__(cls)
super(cls, instance).__init__(codegen, name)
instance._entry_name = entry_name
instance._module = module
instance._linking_libraries = linking_libraries
instance._linking_files = set()
instance._ptx_cache = ptx_cache
instance._cubin_cache = cubin_cache
instance._linkerinfo_cache = linkerinfo_cache
instance._cufunc_cache = {}
instance._max_registers = max_registers
instance._nvvm_options = nvvm_options
class JITCUDACodegen(Codegen):
"""
This codegen implementation for CUDA only generates optimized LLVM IR.
Generation of PTX code is done separately (see numba.cuda.compiler).
"""
_library_class = CUDACodeLibrary
def __init__(self, module_name):
self._data_layout = nvvm.default_data_layout
self._target_data = ll.create_target_data(self._data_layout)
def <API key>(self, name):
ir_module = ir.Module(name)
ir_module.triple = CUDA_TRIPLE
if self._data_layout:
ir_module.data_layout = self._data_layout
nvvm.add_ir_version(ir_module)
return ir_module
def _add_module(self, module):
pass |
Lou Jost's
[diversity](http://dx.doi.org/10.1111/j.2006.0030-1299.14714.x)
[measures](http:
found in the **Diversity.Jost** package.
# Usage
Accessing the main functionality in the package is simple:
julia_skip
using Diversity.Jost
# Load community to study
diversities = jostβ(community, [0, 1, 2])
@contents
@autodocs
Modules = [Diversity.Jost]
Private = false
@index |
## Allure
 |
<md-input-container class="term-selector">
<md-select ng-model="tvm.selectedTermAbbrev" ng-change="tvm.changeTerm()" aria-label="Select Term">
<md-option ng-repeat="term in tvm.terms" ng-selected="tvm.termIsSelected(term)" value="{{term.abbrev}}">
{{term.name}}
</md-option>
</md-select>
</md-input-container> |
title: Vue definePropertyProxy
date: 2020-07-20 10:01:37
tags:
- Vue
categories:
-
-
- Vue
# Vue defineProperty Proxy
vue2
vue3
## vue2 defineProperty
ts
interface Props {
// true
// false
configurable: boolean;
// true
// false
enumerable: false;
// true
// false
value: any;
// trueassignment operator
// false
writable: boolean;
// getter getter undefined
// undefined
get?: () => any;
// setter setter undefined
// undefined
set?:(value)=>void
}
/**
* @params obj:
* @params key:
* @params Props:
*/
Object.defineProperties(obj,key, props: Props)
| | configurable | enumerable | value | writable | get | set |
|
| | | | | | | |
| | | | | | | |
example
js
var data = {
name: '',
}
var p = defineReactive(data)
function defineReactive(data) {
var result = data
Object.keys(data).forEach((key) => {
var value = data[key]
Object.defineProperty(result, key, {
enumerable: true,
configurable: true,
set(val) {
console.log(`set`, key, val)
value = val
},
get() {
console.log(`get`, key, value)
return value
},
})
})
return result
}
console.log(p.name)
p.name = ''
console.log(p.name)
console

`Object.defineProperty` key `get``set``key``get``set``$set`
vue2
`key` 01...`Object.defineProperty``get``set``vue2`
1. key `Object.defineProperty``$set`
2. `unshift``get``set`
js
var data = ['', '', '']
var p = defineReactive(data)
function defineReactive(data) {
var result = data
Object.keys(data).forEach((key) => {
var value = data[key]
Object.defineProperty(result, key, {
enumerable: true,
configurable: true,
set(val) {
console.log(`set`, key, val)
value = val
},
get() {
console.log(`get`, key, value)
return value
},
})
})
return result
}
p.unshift('')
console

```get`,`set``` 3 3 `Object.defineProperty` 3 `get``set``set`,`console.dir(p)``get``get 3 `
vue2
> node_modules/vue/src/core/observer/array.js
ts
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse',
]
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator(...args) {
const result = original.apply(this, args)
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
`Object.defineProperty`
push
`set``get```,`vue``data``window``jquery`
## vue3 Proxy
ts
interface Handler {
get: Function
set: Function
}
/**
* @params target
* @params handler
*/
const p = new Proxy(target:object, handler:Handler)
example
js
var data = {
name: '',
}
var p = defineReactive(data)
function defineReactive(data) {
var result = data
p = new Proxy(result, {
set(obj, prop, value) {
console.log(`set`, prop, value)
obj[prop] = value
},
get(obj, prop) {
console.log(`get`, prop, obj[prop])
return obj[prop]
},
})
return p
}
p.name = ''
p.name
console


vue3 vue2
Proxy data key key get set Proxy get set
`p.name.first=""` set
js
var data = {
name: {
first: '',
content: '',
},
}
var p = defineReactive(data)
function defineReactive(data) {
var result = data
p = new Proxy(result, {
set(obj, prop, value) {
console.log(`set`, prop, value)
obj[prop] = value
},
get(obj, prop) {
console.log(`get`, prop, obj[prop])
return obj[prop]
},
})
return p
}
p.name.first = ''
console

console data name get set Proxy
Proxy Data get
js
var data = {
name: {
first: '',
content: '',
},
}
var p = defineReactive(data)
function defineReactive(data) {
var result = data
p = new Proxy(result, {
set(obj, prop, value) {
console.log(`set`, prop, value)
obj[prop] = value
},
get(obj, prop) {
console.log(`get`, prop, obj[prop])
return defineReactive(obj[prop])
},
})
return p
}
p.name.first = ''
console

p.name.first set
vue3
js
var data = ['', '', '']
var p = defineReactive(data)
function defineReactive(data) {
var result = data
p = new Proxy(result, {
set(obj, prop, value) {
console.log(`set`, prop, value)
obj[prop] = value
},
get(obj, prop) {
console.log(`get`, prop, obj[prop])
return obj[prop]
},
})
return p
}
console.dir(p[1])
console

data `unshift`
js
var data = ['', '', '']
var p = defineReactive(data)
function defineReactive(data) {
var result = data
p = new Proxy(result, {
set(obj, prop, value) {
console.log(`set`, prop, value)
obj[prop] = value
return true
},
get(obj, prop) {
var val = obj[prop]
if (typeof obj[prop] === 'object') {
val = defineReactive(obj[prop])
}
return val
},
})
return p
}
p.unshift('')
console

vue3 Proxy set
vue3
js
function reactive(data) {
if (typeof data !== 'object' || data == null) {
return data
}
const observed = new Proxy(data, {
get(target, key, receiver) {
let result = Reflect.get(target, key, receiver)
return typeof result !== 'object' ? result : reactive(result)
},
set(target, key, value, receiver) {
effective()
const ret = Refect.set(target, key, value, receiver)
return ret
},
deleteProperty(target, key) {
const ret = Refect.deleteProperty(target, key)
return ret
},
})
return observed
} |
#ifndef TEST_H_
#define TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <h8sdk/unit_test.h>
#if defined(TEST_SOUND) || defined(TEST_MUSIC)
#if SOUND_MAX_PRONOUNCE < 3
#error "Please define the SOUND_MAX_PRONOUNCE >= 3."
#endif
#endif
#define TEST_FAILURE(x) _printf("*** Failed: %s\r\n", (x));
void main(void);
static char* test_sci();
static char* test_stdio();
static char* test_stdlib();
static char* test_string();
static char* test_assert();
static char* test_ioctl();
static char* test_led();
static char* test_lcd();
static char* test_push_switch();
static char* test_adc();
static char* test_ps2();
static char* test_sound();
static char* test_music();
static char* test_ssrp();
static char* test_run(const UTEST_Func* test_list, _UWORD num);
static const UTEST_Func test_basic_drivers_[] = {
test_ioctl,
test_led,
test_sci
};
static const UTEST_Func test_drivers_[] = {
#ifdef TEST_ASSERT
test_assert,
#endif /* TEST_ASSERT */
#ifdef TEST_STDC
test_stdio,
test_stdlib,
test_string,
#endif /* TEST_STDC */
#ifdef TEST_LCD
test_lcd,
#endif /* TEST_PS2 */
#ifdef TEST_PUSH_SWITCH
test_push_switch,
#endif /* TEST_PUSH_SWITCH */
#ifdef TEST_ADC
test_adc,
#endif /* TEST_ADC */
#ifdef TEST_PS2
test_ps2,
#endif /* TEST_PS2 */
#ifdef TEST_SOUND
test_sound
#endif /* TEST_SOUND */
};
static const UTEST_Func test_modules_[] = {
#ifdef TEST_MUSIC
test_music,
#endif /* TEST_MUSIC */
#ifdef TEST_SSRP
test_ssrp
#endif /* TEST_SSRP */
};
#ifdef __cplusplus
}
#endif
#endif /* TEST_H_ */ |
#include "unittest.hpp"
#include "rice/global_function.hpp"
using namespace Rice;
TESTSUITE(GlobalFunction);
SETUP(GlobalFunction)
{
ruby_init();
}
namespace {
bool <API key> = false;
void method_to_wrap(Object self) {
<API key> = true;
}
int <API key>;
void method_with_args(Object self, int arg) {
<API key> = arg;
}
}
TESTCASE(<API key>)
{
<API key>("method_to_wrap", &method_to_wrap);
Module m = Module(rb_mKernel);
m.call("method_to_wrap");
ASSERT(<API key>);
}
TESTCASE(<API key>)
{
<API key>("method_with_args", &method_with_args);
Module m = Module(rb_mKernel);
m.call("method_with_args", 10);
ASSERT_EQUAL(10, <API key>);
} |
#ifndef MEMORY_INCLUDED
#define MEMORY_INCLUDED
extern void *compat_malloc(size_t size);
extern void *compat_calloc(size_t nelem, size_t size);
extern void *compat_realloc(void *ptr, size_t size);
#ifndef NDEBUG
#include <stdlib.h>
#include <assert.h>
#define mem_init memory_init()
#define mem_done memory_done()
#define mem_list_allocated <API key>()
#define mem_malloc(x) memory_malloc((x), __FILE__, __LINE__)
#define mem_calloc(x, y) \
memory_calloc((x), (y), __FILE__, \
__LINE__)
#define mem_realloc(p, x) \
memory_realloc((p), (x), __FILE__, \
__LINE__)
#define mem_free(p) memory_free((p), __FILE__, __LINE__)
#define mem_hexdump(p) memory_hexdump((p), __FILE__, __LINE__)
#define mem_hexdump_alien(p, x) <API key>((p), (x))
extern void memory_init(void);
extern void memory_done(void);
extern void *memory_malloc(size_t size, const char *srcname, int line);
extern void *memory_calloc(size_t nelem, size_t size, const char *srcname,
int line);
extern void *memory_realloc(void *ptr, size_t size, const char *srcname,
int line);
extern void memory_free(void *ptr, const char *srcname, int line);
extern void <API key>(void);
extern void memory_hexdump(void *ptr, const char *srcname, int srcline);
extern void <API key>(void *ptr, size_t len);
#else
#define mem_init
#define mem_done
#define mem_dump_allocated
#define mem_malloc(x) compat_malloc((x))
#define mem_calloc(x, y) compat_calloc((x), (y))
#define mem_realloc(p, x) compat_realloc((p), (x))
#define mem_free(p) free((p))
#define mem_hexdump(p)
#define mem_hexdump_alien(p, x)
#endif
#endif |
//this files contains the information about the each application of aws
module.exports={
cloudfront: {
player: "We use JWPlayer as the embeded video player and you can change to another",
bucket: "This directory is where your uploaded video file been distributed by cloudfront",
bbucket: "This directory is original S3 bucket we used for backup video playing in case of the time inteval of cloudfront and original s3 file",
logo: "a JPG file,to show the pic when there is no screenshot,acutally in current version, the thumbnail is forced"
},
transcode: {
default_role: 'arn of your default transcode role',
presetId: 'the default transcode present id',
pipelineId:'the pipeline ID you created you process the job',
},
s3: {
vbucket: "the name of bucket where you store your video file in",
},
dynamodb: {
}
} |
#! /usr/bin/env phantomjs
// Convenience function: wait for some value from lookup fn, call ready
// callback with value when available.
function waitFor(lookup, ready) {
var result, interval;
interval = setInterval(function() {
result = lookup();
if (result !== undefined && result !== null) {
clearInterval(interval);
ready(result);
}
}, 100);
};
var server = require('webserver').create();
server.listen(4001, function(request, response) {
response.statusCode = 200;
response.write('<!DOCTYPE html><html><body></body></html>');
response.close();
});
var page = require('webpage').create();
page.settings.<API key> = true;
page.settings.webSecurityEnabled = false;
page.onConsoleMessage = function(x) {
console.log(x);
};
page.open('http://localhost:4001/', function(status) {
page.injectJs(phantom.args[0]);
// Wait for tests to complete, then exit with appropriate error code.
waitFor(
function() {
return page.evaluate(function() {
if (typeof cljs_rest !== 'undefined') {
var val = cljs_rest.runner.complete();
if (val) {
return cljs.core.clj__GT_js(val);
}
}
});
},
function(result) {
var success = result.fail === 0 && result.error === 0;
var exitCode = success ? 0 : 1;
page.close();
phantom.exit(exitCode);
}
);
// Run tests.
page.evaluate(function() {
if (typeof cljs_rest !== 'undefined') {
cljs_rest.runner.run();
}
});
}); |
package pointer
import "time"
func DefaultBool(value *bool, defaultValue bool) *bool {
if value == nil {
return &defaultValue
}
return value
}
func DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration {
if value == nil {
return &defaultValue
}
return value
}
func DefaultFloat64(value *float64, defaultValue float64) *float64 {
if value == nil {
return &defaultValue
}
return value
}
func DefaultInt(value *int, defaultValue int) *int {
if value == nil {
return &defaultValue
}
return value
}
func DefaultString(value *string, defaultValue string) *string {
if value == nil {
return &defaultValue
}
return value
}
func DefaultStringArray(value *[]string, defaultValue []string) *[]string {
if value == nil {
return &defaultValue
}
return value
}
func DefaultTime(value *time.Time, defaultValue time.Time) *time.Time {
if value == nil {
return &defaultValue
}
return value
} |
package org.mapfish.print.processor;
import org.mapfish.print.output.Values;
import org.mapfish.print.processor.AbstractProcessor.Context;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Contains information shared across all nodes being executed.
*
*/
public final class <API key> {
private final Values values;
private final IdentityHashMap<Processor, Void> runningProcessors = new IdentityHashMap<>();
private final IdentityHashMap<Processor, Void> executedProcessors =
new IdentityHashMap<>();
private final Lock processorLock = new ReentrantLock();
private final Context context;
/**
* Constructor.
*
* @param values the values object.
*/
public <API key>(final Values values) {
this.values = values;
this.context = new Context(values.getString(Values.JOB_ID_KEY));
}
public Values getValues() {
return this.values;
}
/**
* Try to start the node of a processor.
* <p>
* In case the processor is already running, has already finished or if not all requirements have
* finished, the processor can not start. If the above conditions are fulfilled, the processor is added to
* the list of running processors, and is expected to be started from the caller.
*
* @param processorGraphNode the node that should start.
* @return if the node of the processor can be started.
*/
@SuppressWarnings("unchecked")
public boolean tryStart(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
final boolean canStart;
try {
if (isRunning(processorGraphNode) || isFinished(processorGraphNode) ||
!allAreFinished(processorGraphNode.getRequirements())) {
canStart = false;
} else {
started(processorGraphNode);
canStart = true;
}
} finally {
this.processorLock.unlock();
}
return canStart;
}
/**
* Flag that the processor has started execution.
*
* @param processorGraphNode the node that has started.
*/
private void started(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
this.runningProcessors.put(processorGraphNode.getProcessor(), null);
} finally {
this.processorLock.unlock();
}
}
/**
* Return true if the processor of the node is currently being executed.
*
* @param processorGraphNode the node to test.
*/
public boolean isRunning(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
return this.runningProcessors.containsKey(processorGraphNode.getProcessor());
} finally {
this.processorLock.unlock();
}
}
/**
* Return true if the processor of the node has previously been executed.
*
* @param processorGraphNode the node to test.
*/
public boolean isFinished(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
return this.executedProcessors.containsKey(processorGraphNode.getProcessor());
} finally {
this.processorLock.unlock();
}
}
/**
* Flag that the processor has completed execution.
*
* @param processorGraphNode the node that has finished.
*/
public void finished(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
try {
this.runningProcessors.remove(processorGraphNode.getProcessor());
this.executedProcessors.put(processorGraphNode.getProcessor(), null);
} finally {
this.processorLock.unlock();
}
}
/**
* Verify that all processors have finished executing atomically (within the same lock as {@link
* #finished(ProcessorGraphNode)} and {@link #isFinished(ProcessorGraphNode)} is within.
*
* @param processorNodes the node to check for completion.
*/
public boolean allAreFinished(final Set<ProcessorGraphNode<?, ?>> processorNodes) {
this.processorLock.lock();
try {
for (ProcessorGraphNode<?, ?> node: processorNodes) {
if (!isFinished(node)) {
return false;
}
}
return true;
} finally {
this.processorLock.unlock();
}
}
/**
* Set a {@code cancel} flag.
* <p>
* All processors are supposed to check this flag frequently and terminate the execution if requested.
*/
public void cancel() {
this.context.cancel();
}
public Context getContext() {
return this.context;
}
public String getJobId() {
return this.context.getJobId();
}
} |
class Toot < Formula
include Language::Python::Virtualenv
desc "Mastodon CLI & TUI"
homepage "https://toot.readthedocs.io/en/latest/index.html"
url "https://files.pythonhosted.org/packages/0f/80/<API key>/toot-0.28.0.tar.gz"
sha256 "<SHA256-like>"
license "GPL-3.0-only"
revision 1
head "https://github.com/ihabunek/toot.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, big_sur: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, catalina: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, mojave: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, x86_64_linux: "<SHA256-like>"
end
depends_on "python@3.10"
resource "beautifulsoup4" do
url "https://files.pythonhosted.org/packages/a1/69/<API key>/beautifulsoup4-4.10.0.tar.gz"
sha256 "<SHA256-like>"
end
resource "certifi" do
url "https://files.pythonhosted.org/packages/6d/78/<API key>/certifi-2021.5.30.tar.gz"
sha256 "<SHA256-like>"
end
resource "charset-normalizer" do
url "https://files.pythonhosted.org/packages/eb/7f/<API key>/<API key>.0.6.tar.gz"
sha256 "<SHA256-like>"
end
resource "idna" do
url "https://files.pythonhosted.org/packages/cb/38/<API key>/idna-3.2.tar.gz"
sha256 "<SHA256-like>"
end
resource "requests" do
url "https://files.pythonhosted.org/packages/e7/01/<API key>/requests-2.26.0.tar.gz"
sha256 "<SHA256-like>"
end
resource "soupsieve" do
url "https://files.pythonhosted.org/packages/c8/3f/<API key>/soupsieve-2.2.1.tar.gz"
sha256 "<SHA256-like>"
end
resource "urllib3" do
url "https://files.pythonhosted.org/packages/80/be/<API key>/urllib3-1.26.7.tar.gz"
sha256 "<SHA256-like>"
end
resource "urwid" do
url "https://files.pythonhosted.org/packages/94/3f/<API key>/urwid-2.1.2.tar.gz"
sha256 "<SHA256-like>"
end
resource "wcwidth" do
url "https://files.pythonhosted.org/packages/89/38/<API key>/wcwidth-0.2.5.tar.gz"
sha256 "<SHA256-like>"
end
def install
<API key>
end
test do
assert_match version.to_s, shell_output("#{bin}/toot")
assert_match "You are not logged in to any accounts", shell_output("#{bin}/toot auth")
end
end |
using UnityEngine;
namespace EA4S.Assessment
{
public interface IAnswer
{
<summary>
Access the GameObject of this answer
</summary>
GameObject gameObject { get; }
<summary>
Is this a correct answer?
</summary>
bool IsCorrect();
<summary>
Compare content of the answer
</summary>
<param name="other"> other answer content</param>
bool Equals( IAnswer other);
<summary>
The data of the living letter
</summary>
ILivingLetterData Data();
}
} |
#ifndef HC_H_
#define HC_H_
#include <assert.h>
#include <vector>
#include <utility>
using namespace std;
enum Command {
MOVE_W,
MOVE_E,
MOVE_SW,
MOVE_SE,
ROT_C,
ROT_CC,
};
#define PF(p) p.x, p.y
struct Pos {
int x, y;
Pos() : x(-1), y(-1) {}
Pos(int x0, int y0) : x(x0), y(y0) {}
explicit Pos(pair<int, int> p) : x(p.first), y(p.second) {}
bool operator<(const Pos& p) const {
if (x < p.x)
return true;
if (x > p.x)
return false;
return y < p.y;
}
bool operator>(const Pos& p) const {
if (x > p.x)
return true;
if (x < p.x)
return false;
return y > p.y;
}
static void CheckEq(Pos a, Pos b, const char* f, int l) {
if (a != b) {
fprintf(stderr, "%s:%d: (%d,%d) vs (%d,%d)\n",
f, l, a.x, a.y, b.x, b.y);
}
}
static void Test() {
#if 0
#define CHECK_EQ(a, b) CheckEq(a, b, __FILE__, __LINE__)
CHECK_EQ(Pos(0, 0).Rotate(0, 0, Pos(0, 0)), Pos(0, 0));
CHECK_EQ(Pos(1, 0).Rotate(0, 0, Pos(0, 0)), Pos(1, 0));
CHECK_EQ(Pos(1, 0).Rotate(0, 1, Pos(0, 0)), Pos(0, 1));
CHECK_EQ(Pos(1, 0).Rotate(0, 2, Pos(0, 0)), Pos(-1, 1));
CHECK_EQ(Pos(1, 0).Rotate(0, 3, Pos(0, 0)), Pos(-1, 0));
CHECK_EQ(Pos(1, 0).Rotate(0, 4, Pos(0, 0)), Pos(-1, -1));
CHECK_EQ(Pos(1, 0).Rotate(0, 5, Pos(0, 0)), Pos(0, -1));
CHECK_EQ(Pos(1, 0).Rotate(1, 0, Pos(0, 0)), Pos(1, 0));
CHECK_EQ(Pos(1, 0).Rotate(1, 1, Pos(0, 0)), Pos(1, 1));
CHECK_EQ(Pos(1, 0).Rotate(1, 2, Pos(0, 0)), Pos(0, 1));
CHECK_EQ(Pos(1, 0).Rotate(1, 3, Pos(0, 0)), Pos(-1, 0));
CHECK_EQ(Pos(1, 0).Rotate(1, 4, Pos(0, 0)), Pos(0, -1));
CHECK_EQ(Pos(1, 0).Rotate(1, 5, Pos(0, 0)), Pos(1, -1));
CHECK_EQ(Pos(2, 0).Rotate(0, 0, Pos(1, 1)), Pos(2, 0));
CHECK_EQ(Pos(2, 0).Rotate(0, 1, Pos(1, 1)), Pos(2, 1));
CHECK_EQ(Pos(2, 0).Rotate(0, 2, Pos(1, 1)), Pos(2, 2));
CHECK_EQ(Pos(2, 0).Rotate(0, 3, Pos(1, 1)), Pos(1, 2));
CHECK_EQ(Pos(2, 0).Rotate(0, 4, Pos(1, 1)), Pos(0, 1));
CHECK_EQ(Pos(2, 0).Rotate(0, 5, Pos(1, 1)), Pos(1, 0));
CHECK_EQ(Pos(0, 1).Rotate(0, 0, Pos(0, 0)), Pos(0, 1));
CHECK_EQ(Pos(0, 1).Rotate(0, 0, Pos(1, 1)), Pos(0, 1));
CHECK_EQ(Pos(0, 0).Rotate(3, 1, Pos(0, 0)), Pos(0, 0));
CHECK_EQ(Pos(0, 1).Rotate(3, 1, Pos(0, 0)), Pos(0, 1));
CHECK_EQ(Pos(0, 2).Rotate(3, 1, Pos(0, 0)), Pos(-1, 1));
#undef CHECK_EQ
#endif
}
bool operator==(Pos p) const {
return x == p.x && y == p.y;
}
bool operator!=(Pos p) const {
return !operator==(p);
}
void operator+=(Pos p) {
x += p.x;
y += p.y;
}
double GetGeomX(int cy) const {
return x + ((y + cy) & 1) * 0.5;
}
Pos MoveSW() const {
return Pos(x - 1 + y % 2, y + 1);
}
Pos MoveSE() const {
return Pos(x + y % 2, y + 1);
}
Pos MoveNW() const {
return Pos(x - 1 + y % 2, y - 1);
}
Pos MoveNE() const {
return Pos(x + y % 2, y - 1);
}
Pos StepSW(int n) const {
return Pos(x - n / 2 + (y % 2 - 1) * (n % 2), y + n);
}
Pos StepSE(int n) const {
return Pos(x + n / 2 + (y % 2) * (n % 2), y + n);
}
Pos StepNW(int n) const {
return Pos(x - n / 2 + (y % 2 - 1) * (n % 2), y - n);
}
Pos StepNE(int n) const {
return Pos(x + n / 2 + (y % 2) * (n % 2), y - n);
}
Pos Rotate(/*int cy, */int r, Pos p) {
// E, SE, SW, W, NW, NE
int moves[6] = {};
Pos m = Pos(p.x, p.y);
if (y >= p.y) {
int se_cnt = y - p.y;
m = m.StepSE(se_cnt);
moves[1] = se_cnt;
} else {
int ne_cnt = p.y - y;
m = m.StepNE(ne_cnt);
moves[5] = ne_cnt;
}
if (x >= m.x) {
moves[0] = x - m.x;
} else {
moves[3] = m.x - x;
}
int rmoves[6];
for (int i = 0; i < 6; i++) {
int v = moves[i];
rmoves[(i + r) % 6] = v;
}
m = Pos(p.x, p.y);
m.x += rmoves[0];
m.x -= rmoves[3];
m = m.StepSE(rmoves[1]);
m = m.StepSW(rmoves[2]);
m = m.StepNW(rmoves[4]);
m = m.StepNE(rmoves[5]);
Pos ret = Pos(m.x, m.y);
#if 0
//if (r == 0 && *this != ret || true) {
if (r == 0 && *this != ret) {
fprintf(stderr, "Rotate (%d,%d) pivot=(%d,%d) rot=%d => (%d,%d)\n",
x, y, p.x, p.y, r, ret.x, ret.y);
fprintf(stderr, "moves={%d,%d,%d,%d,%d,%d} rmoves={%d,%d,%d,%d,%d,%d}\n",
moves[0], moves[1], moves[2], moves[3], moves[4], moves[5],
rmoves[0], rmoves[1], rmoves[2],
rmoves[3], rmoves[4], rmoves[5]);
}
#endif
return ret;
#if 0
fprintf(stderr, "Rotate (%d,%d) pivot=(%d,%d) rot=%d y=%d\n",
x, y, p.x, p.y, r, cy);
double dy = sqrt(1-0.5*0.5);
double pgx = p.GetGeomX(cy);
double gx = GetGeomX(cy) - pgx;
double gy = (y - p.y) * dy;
double gr = M_PI * 2 * r / 6;
double nx = gx * cos(gr) - gy * sin(gr);
double ny = gx * sin(gr) + gy * cos(gr);
int iy = round(ny / dy) + p.y;
int ix = round(nx + pgx - ((iy + cy) & 1) * 0.5);
//int ix = ceil(nx + pgx);
//int ix = round(nx + pgx - ((iy + cy) % 2) * 0.5);
//int ix = round(nx + pgx - (iy % 2) * 0.5);
fprintf(stderr, "(%f,%f) => (%f,%f) %d,%d\n", gx, gy, nx, ny, ix, iy);
return Pos(ix, iy);
#endif
#if 0
int dx = x - p.x;
int dy = y - p.y;
int nx = 0;
int ny = 0;
int odd = (y + cy) & 1;
switch (r) {
case 0:
return *this;
case 1: {
}
case 2:
case 3:
case 4:
case 5:
default:
assert(false);
}
#endif
}
};
struct Decision {
Decision(int x0, int y0, int r0)
: x(x0), y(y0), r(r0) {
}
Decision(Pos p, int r0)
: x(p.x), y(p.y), r(r0) {
}
Decision()
: x(-1), y(-1), r(-1) {
}
Pos pos() const {
return Pos(x, y);
}
static void Test() {
#define CHECK_EQ(a, b) Pos::CheckEq(a, b, __FILE__, __LINE__)
#if 0
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
CHECK_EQ(Decision(x, y, 0).Apply(Pos(0, 0), Pos(0, 0)), Pos(x, y));
}
}
#endif
CHECK_EQ(Decision(-1, 1, 0).Apply(Pos(0, 0), Pos(0, 0)), Pos(-1, 1));
#undef CHECK_EQ
}
Decision Move(Command cmd) {
switch (cmd) {
case MOVE_W:
return Decision(x - 1, y, r);
case MOVE_E:
return Decision(x + 1, y, r);
case MOVE_SW:
return Decision(pos().MoveSW(), r);
case MOVE_SE:
return Decision(pos().MoveSE(), r);
case ROT_C:
return Decision(x, y, (r + 1) % 6);
case ROT_CC:
return Decision(x, y, (r + 5) % 6);
default:
assert(false);
}
}
Pos Apply(Pos p, Pos pivot) const {
#if 0
#define VERBOSE_APPLY
#ifdef VERBOSE_APPLY
fprintf(stderr, "Apply (%d,%d) pivot=(%d,%d) x=%d y=%d rot=%d\n",
p.x, p.y, pivot.x, pivot.y, x, y, r);
#endif
static const double kDeltaY = sqrt(1-0.5*0.5);
double gy = p.y * kDeltaY;
double gx = p.GetGeomX(y);
double pgy = pivot.y * kDeltaY;
double pgx = pivot.GetGeomX(y);
double dy = gy - pgy;
double dx = gx - pgx;
double gr = M_PI * 2 * r / 6;
double ndx = dx * cos(gr) - dy * sin(gr);
double ndy = dx * sin(gr) + dy * cos(gr);
#ifdef VERBOSE_APPLY
fprintf(stderr, "d=(%f,%f) => nd=(%f,%f)\n", dx, dy, ndx, ndy);
#endif
double ngx = pgx + ndx;
double ngy = pgy + ndy;
int dxa = int(round(ngy / kDeltaY)) % 2;
ngy += y * kDeltaY;
int dxb = int(round(ngy / kDeltaY)) % 2;
int iy = round(ngy / kDeltaY);
fprintf(stderr, "dxa=%d dxb=%d\n", dxa, dxb);
//int ix = round(ngx + x + (dxb - dxa) * 0.5);
int ix = round(ngx + x + (dxa - dxb) * 0.5);
#ifdef VERBOSE_APPLY
fprintf(stderr, "(%f,%f) => (%f,%f)\n", gx, gy, ngx, ngy);
#endif
return Pos(ix, iy);
#else
int nx = p.x + x;
int ny = p.y + y;
if (p.y % 2)
nx += 1 - (ny & 1);
int npx = pivot.x + x;
int npy = pivot.y + y;
if (pivot.y % 2)
npx += 1 - (npy & 1);
return Pos(nx, ny).Rotate(r, Pos(npx, npy));
#if 0
Pos np = p.Rotate(y, r, pivot);
int nx = x + np.x;
int ny = y + np.y;
int dx = 0;
if (np.y % 2)
dx = 1 - ny % 2;
//int dx = np.y % 2 - ny % 2;
//fprintf(stderr, "np=(%d,%d) %d %d %d\n", np.x, np.y, nx, ny, dx);
return Pos(nx + dx, ny);
#endif
#endif
}
bool operator==(Decision d) const {
return x == d.x && y == d.y && r == d.r;
}
bool operator!=(Decision d) const {
return !operator==(d);
}
bool operator<(Decision d) const {
if (x < d.x)
return true;
if (x > d.x)
return false;
if (y < d.y)
return true;
if (y > d.y)
return false;
return r < d.r;
}
int x, y, r;
};
class Unit {
public:
Unit(const vector<Pos>& members, Pos pivot, int width)
: members_(members), pivot_(pivot) {
int min_x = width;
int max_x = 0;
for (const Pos& p : members) {
min_x = min(min_x, p.x);
max_x = max(max_x, p.x);
}
base_x_ = (width - (max_x - min_x + 1)) / 2 - min_x; // min_x is not always 0, therefore have to minus min_x.
}
const vector<Pos>& members() const { return members_; }
Pos pivot() const { return pivot_; }
Decision origin() const { return Decision(base_x_, 0, 0); }
int base_x() const { return base_x_; }
private:
vector<Pos> members_;
Pos pivot_;
int base_x_;
};
#endif |
require 'json'
f = File.read("#{File.dirname(__FILE__)}/../../public/context.json")
RELATORS ||= JSON.parse(f)['@context'].select { |k,v| (v['@id'] || '').start_with? 'mrel:' }.keys |
<?php
// Hindi
return [
'code' => 'hi',
'iso2' => 'hi',
'iso3' => 'hin',
'timezone' => 'Asia/Calcutta',
'title' => 'Hindi',
]; |
#ifndef TREE_CHECK
#error "This file should only be included by treecheck.c"
#endif
// TODO: big comment explaining what's going on
ROOT(program, module);
RULE(program,
IS_SCOPE // path -> PACKAGE
HAS_DATA // program_t
ZERO_OR_MORE(package),
TK_PROGRAM);
RULE(package,
IS_SCOPE // name -> entity
HAS_DATA // package_t
ZERO_OR_MORE(module)
OPTIONAL(string), // Package doc string
TK_PACKAGE);
RULE(module,
IS_SCOPE // name -> PACKAGE | entity
HAS_DATA // source_t
OPTIONAL(string)
ZERO_OR_MORE(use)
ZERO_OR_MORE(class_def),
TK_MODULE);
RULE(use,
HAS_DATA // Included package (unaliased use package commands only)
CHILD(id, none)
CHILD(ffidecl, string)
CHILD(expr, ifdef_cond, none), // Guard
TK_USE);
RULE(ffidecl,
IS_SCOPE
CHILD(id, string)
CHILD(type_args) // Return type
CHILD(params, none)
CHILD(none) // Named params
CHILD(question, none),
TK_FFIDECL);
RULE(class_def,
IS_SCOPE // name -> TYPEPARAM | FVAR | FVAL | EMBED | method
//HAS_DATA // Type checking state
CHILD(id)
CHILD(type_params, none)
CHILD(cap, none)
CHILD(provides, none)
CHILD(members, none)
CHILD(at, none)
CHILD(string, none), // Doc
TK_TYPE, TK_INTERFACE, TK_TRAIT, TK_PRIMITIVE, TK_STRUCT, TK_CLASS,
TK_ACTOR);
RULE(provides, ONE_OR_MORE(type), TK_PROVIDES);
RULE(members,
ZERO_OR_MORE(field)
ZERO_OR_MORE(method),
TK_MEMBERS);
RULE(field,
HAS_TYPE(type)
CHILD(id)
CHILD(type, none) // Field type
CHILD(expr, none),
TK_FLET, TK_FVAR, TK_EMBED);
RULE(method,
IS_SCOPE // name -> TYPEPARAM | PARAM
HAS_DATA // Body donor type
CHILD(cap, none)
CHILD(id)
CHILD(type_params, none)
CHILD(params, none)
CHILD(type, none) // Return type
CHILD(question, none)
CHILD(rawseq, none) // Body
CHILD(string, none)
CHILD(rawseq, none), // Guard (case methods only)
TK_FUN, TK_NEW, TK_BE);
RULE(type_params, ONE_OR_MORE(type_param), TK_TYPEPARAMS);
RULE(type_param,
CHILD(id)
CHILD(type, none) // Constraint
CHILD(type, none), // Default
TK_TYPEPARAM);
RULE(type_args, ONE_OR_MORE(type), TK_TYPEARGS);
RULE(params,
ONE_OR_MORE(param)
OPTIONAL(ellipsis),
TK_PARAMS);
RULE(param,
HAS_TYPE(type)
CHILD(id, expr)
CHILD(type, none)
CHILD(expr, none),
TK_PARAM);
RULE(seq,
IS_SCOPE // name -> local ID node
HAS_TYPE(type)
ONE_OR_MORE(jump, intrinsic, compile_error, expr, semi),
TK_SEQ);
RULE(rawseq,
HAS_TYPE(type)
ONE_OR_MORE(jump, intrinsic, compile_error, expr, semi),
TK_SEQ);
RULE(jump,
HAS_TYPE(type)
CHILD(rawseq, none),
TK_RETURN, TK_BREAK, TK_CONTINUE, TK_ERROR);
RULE(intrinsic,
HAS_TYPE(type)
CHILD(none),
<API key>);
RULE(compile_error,
HAS_TYPE(type)
CHILD(rawseq),
TK_COMPILE_ERROR);
GROUP(expr,
local, infix, asop, tuple, consume, recover, prefix, dot, tilde,
qualify, call, ffi_call, match_capture,
if_expr, ifdef, whileloop, repeat, for_loop, with, match, try_expr, lambda,
array_literal, object_literal, int_literal, float_literal, string,
bool_literal, id, rawseq, package_ref, location,
this_ref, ref, fun_ref, type_ref, flet_ref, field_ref, local_ref);
RULE(local,
HAS_TYPE(type)
CHILD(id)
CHILD(type, none),
TK_LET, TK_VAR);
RULE(match_capture,
HAS_TYPE(type)
CHILD(id)
CHILD(type),
TK_MATCH_CAPTURE);
RULE(infix,
HAS_TYPE(type)
// RHS first for TK_ASSIGN, to handle init tracking
// LHS first for all others
CHILD(expr)
CHILD(expr),
TK_PLUS, TK_MINUS, TK_MULTIPLY, TK_DIVIDE, TK_MOD, TK_LSHIFT, TK_RSHIFT,
TK_PLUS_TILDE, TK_MINUS_TILDE, TK_MULTIPLY_TILDE, TK_DIVIDE_TILDE,
TK_MOD_TILDE, TK_LSHIFT_TILDE, TK_RSHIFT_TILDE,
TK_EQ, TK_NE, TK_LT, TK_LE, TK_GT, TK_GE, TK_IS, TK_ISNT,
TK_EQ_TILDE, TK_NE_TILDE, TK_LT_TILDE, TK_LE_TILDE, TK_GT_TILDE, TK_GE_TILDE,
TK_AND, TK_OR, TK_XOR, TK_ASSIGN);
RULE(asop,
HAS_TYPE(type)
CHILD(expr)
CHILD(type),
TK_AS);
RULE(tuple,
HAS_TYPE(type)
ONE_OR_MORE(rawseq),
TK_TUPLE);
RULE(consume,
HAS_TYPE(type)
CHILD(cap, aliased, none)
CHILD(expr),
TK_CONSUME);
RULE(recover,
HAS_TYPE(type)
CHILD(cap, none)
CHILD(seq),
TK_RECOVER);
RULE(prefix,
HAS_TYPE(type)
CHILD(expr),
TK_NOT, TK_UNARY_MINUS, <API key>, TK_ADDRESS, TK_DIGESTOF);
RULE(dot,
HAS_TYPE(type)
CHILD(expr)
CHILD(id, int_literal, type_args),
TK_DOT);
RULE(tilde,
HAS_TYPE(type)
CHILD(expr)
CHILD(id),
TK_TILDE);
RULE(qualify,
CHILD(expr)
CHILD(type_args),
TK_QUALIFY);
RULE(call,
HAS_TYPE(type)
CHILD(positional_args, none)
CHILD(named_args, none)
CHILD(expr), // Note that receiver comes last
TK_CALL);
RULE(ffi_call,
HAS_TYPE(type)
HAS_DATA // FFI declaration to use.
CHILD(id, string)
CHILD(type_args, none)
CHILD(positional_args, none)
CHILD(named_args, none)
CHILD(question, none),
TK_FFICALL);
RULE(positional_args, ONE_OR_MORE(rawseq), TK_POSITIONALARGS);
RULE(named_args, ONE_OR_MORE(named_arg), TK_NAMEDARGS);
RULE(named_arg,
CHILD(id)
CHILD(rawseq),
TK_NAMEDARG, TK_UPDATEARG);
RULE(ifdef,
IS_SCOPE
HAS_TYPE(type)
CHILD(expr, ifdef_cond) // Then expression
CHILD(seq) // Then body
CHILD(seq, ifdef, none) // Else body
CHILD(none, ifdef_cond), // Else expression
TK_IFDEF);
GROUP(ifdef_cond,
ifdef_infix, ifdef_not, ifdef_flag);
RULE(ifdef_infix,
CHILD(ifdef_cond)
CHILD(ifdef_cond),
TK_IFDEFAND, TK_IFDEFOR);
RULE(ifdef_not,
CHILD(ifdef_cond),
TK_IFDEFNOT);
RULE(ifdef_flag,
CHILD(id),
TK_IFDEFFLAG);
RULE(if_expr,
IS_SCOPE
HAS_TYPE(type)
CHILD(rawseq) // Condition
CHILD(seq) // Then body
CHILD(seq, if_expr, none), // Else body
TK_IF);
RULE(whileloop,
IS_SCOPE
HAS_TYPE(type)
CHILD(rawseq) // Condition
CHILD(seq) // Loop body
CHILD(seq, none), // Else body
TK_WHILE);
RULE(repeat,
IS_SCOPE
HAS_TYPE(type)
CHILD(seq) // Loop body
CHILD(rawseq) // Condition
CHILD(seq, none), // Else body
TK_REPEAT);
RULE(for_loop,
HAS_TYPE(type)
CHILD(expr) // Iterator declaration
CHILD(rawseq) // Iterator value
CHILD(rawseq) // Loop body
CHILD(seq, none), // Else body
TK_FOR);
RULE(with,
HAS_TYPE(type)
CHILD(expr) // With variable(s)
CHILD(rawseq) // Body
CHILD(rawseq, none), // Else
TK_WITH);
RULE(match,
IS_SCOPE
HAS_TYPE(type)
CHILD(rawseq)
CHILD(cases, none)
CHILD(seq, none), // Else body
TK_MATCH);
RULE(cases,
IS_SCOPE // Cases is a scope to simplify branch consolidation.
HAS_TYPE(type) // Union of case types or "TK_CASES"
ZERO_OR_MORE(match_case),
TK_CASES);
RULE(match_case,
IS_SCOPE
CHILD(expr, no_case_expr)
CHILD(rawseq, none) // Guard
CHILD(rawseq, none), // Body
TK_CASE);
RULE(no_case_expr, HAS_TYPE(dontcare_type), TK_NONE);
RULE(try_expr,
HAS_TYPE(type)
CHILD(seq) // Try body
CHILD(seq, none) // Else body
CHILD(seq, none), // Then body. LLVMValueRef for the indirectbr instruction.
TK_TRY, TK_TRY_NO_CHECK);
RULE(lambda,
HAS_TYPE(type)
CHILD(cap, none) // Receiver cap
CHILD(id, none)
CHILD(type_params, none)
CHILD(params, none)
CHILD(lambda_captures, none)
CHILD(type, none) // Return
CHILD(question, none)
CHILD(rawseq)
CHILD(cap, none, question), // Type reference cap (? indicates old syntax)
TK_LAMBDA);
RULE(lambda_captures, ONE_OR_MORE(lambda_capture), TK_LAMBDACAPTURES);
RULE(lambda_capture,
CHILD(id)
CHILD(type, none)
CHILD(expr, none),
TK_LAMBDACAPTURE);
RULE(array_literal,
CHILD(type, none)
ONE_OR_MORE(rawseq),
TK_ARRAY);
RULE(object_literal,
HAS_DATA // Nice name to use for anonymous type, optional.
CHILD(cap, none)
CHILD(provides, none)
CHILD(members),
TK_OBJECT);
RULE(ref,
HAS_TYPE(type)
CHILD(id),
TK_REFERENCE, TK_PARAMREF);
RULE(package_ref,
CHILD(id),
TK_PACKAGEREF);
RULE(fun_ref,
HAS_TYPE(type)
CHILD(expr)
CHILD(id, type_args),
TK_FUNREF, TK_BEREF, TK_NEWREF, TK_NEWBEREF);
RULE(type_ref,
HAS_TYPE(type)
CHILD(expr)
OPTIONAL(id, type_args),
TK_TYPEREF);
RULE(field_ref,
HAS_TYPE(type)
CHILD(expr)
CHILD(id),
TK_FVARREF, TK_EMBEDREF);
RULE(flet_ref,
HAS_TYPE(type)
CHILD(expr)
CHILD(id, int_literal), // Int for tuple element access
TK_FLETREF);
RULE(local_ref,
HAS_TYPE(type)
CHILD(expr)
OPTIONAL(id),
TK_VARREF, TK_LETREF);
GROUP(type,
type_infix, type_tuple, type_arrow, type_this, cap, nominal,
type_param_ref, dontcare_type, fun_type, error_type, lambda_type,
literal_type, opliteral_type, control_type);
RULE(type_infix, ONE_OR_MORE(type), TK_UNIONTYPE, TK_ISECTTYPE);
RULE(type_tuple, ONE_OR_MORE(type), TK_TUPLETYPE);
RULE(type_arrow,
CHILD(type)
CHILD(type),
TK_ARROW);
RULE(fun_type,
CHILD(cap)
CHILD(type_params, none)
CHILD(params, none)
CHILD(type, none), // Return type
TK_FUNTYPE);
RULE(lambda_type,
CHILD(cap, none) // Apply function cap
CHILD(id, none)
CHILD(type_params, none)
CHILD(type_list, none) // Params
CHILD(type, none) // Return type
CHILD(question, none)
CHILD(cap, gencap, none) // Type reference cap
CHILD(aliased, ephemeral, none),
TK_LAMBDATYPE);
RULE(type_list, ONE_OR_MORE(type), TK_PARAMS);
RULE(nominal,
HAS_DATA // Definition of referred type
CHILD(id, none) // Package
CHILD(id) // Type
CHILD(type_args, none)
CHILD(cap, gencap, none)
CHILD(aliased, ephemeral, none)
OPTIONAL(id, none), // Original package specifier (for error reporting)
TK_NOMINAL);
RULE(type_param_ref,
HAS_DATA // Definition of referred type parameter
CHILD(id)
CHILD(cap, gencap, none)
CHILD(aliased, ephemeral, none),
TK_TYPEPARAMREF);
RULE(at, LEAF, TK_AT);
RULE(bool_literal, HAS_TYPE(type), TK_TRUE, TK_FALSE);
RULE(aliased, LEAF, TK_ALIASED);
RULE(cap, LEAF, TK_ISO, TK_TRN, TK_REF, TK_VAL, TK_BOX, TK_TAG);
RULE(control_type, LEAF, TK_IF, TK_CASES, <API key>,
TK_COMPILE_ERROR, TK_RETURN, TK_BREAK, TK_CONTINUE, TK_ERROR);
RULE(dontcare_type, LEAF, TK_DONTCARETYPE);
RULE(ellipsis, LEAF, TK_ELLIPSIS);
RULE(ephemeral, LEAF, TK_EPHEMERAL);
RULE(error_type, LEAF, TK_ERRORTYPE);
RULE(float_literal, HAS_TYPE(type), TK_FLOAT);
RULE(gencap, LEAF, TK_CAP_READ, TK_CAP_SEND, TK_CAP_SHARE, TK_CAP_ALIAS,
TK_CAP_ANY);
RULE(id, HAS_TYPE(type) HAS_DATA, TK_ID);
RULE(int_literal, HAS_TYPE(type), TK_INT);
RULE(literal_type, LEAF, TK_LITERAL, TK_LITERALBRANCH);
RULE(location, HAS_TYPE(nominal), TK_LOCATION);
RULE(none, LEAF, TK_NONE);
RULE(opliteral_type, HAS_DATA, TK_OPERATORLITERAL);
RULE(question, LEAF, TK_QUESTION);
RULE(semi, LEAF, TK_SEMI);
RULE(string, HAS_TYPE(type), TK_STRING);
RULE(this_ref, HAS_TYPE(type), TK_THIS);
RULE(type_this, LEAF, TK_THISTYPE); |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Wed May 16 11:00:29 JST 2018 -->
<title>JMTRandom 0.1.0 API</title>
<script type="text/javascript">
targetPage = "" + window.location.search;
if (targetPage != "" && targetPage != "undefined")
targetPage = targetPage.substring(1);
if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage)))
targetPage = "undefined";
function validURL(url) {
try {
url = decodeURIComponent(url);
}
catch (error) {
return false;
}
var pos = url.indexOf(".html");
if (pos == -1 || pos != url.length - 5)
return false;
var allowNumber = false;
var allowSep = false;
var seenDot = false;
for (var i = 0; i < url.length - 5; i++) {
var ch = url.charAt(i);
if ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
ch == '$' ||
ch == '_' ||
ch.charCodeAt(0) > 127) {
allowNumber = true;
allowSep = true;
} else if ('0' <= ch && ch <= '9'
|| ch == '-') {
if (!allowNumber)
return false;
} else if (ch == '/' || ch == '.') {
if (!allowSep)
return false;
allowNumber = false;
allowSep = false;
if (ch == '.')
seenDot = true;
if (ch == '/' && seenDot)
return false;
} else {
return false;
}
}
return true;
}
function loadFrames() {
if (targetPage != "" && targetPage != "undefined")
top.classFrame.location = top.targetPage;
}
</script>
</head>
<frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()">
<frame src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)">
<frame src="com/github/okamumu/jmtrandom/package-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes">
<noframes>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<h2>Frame Alert</h2>
<p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="com/github/okamumu/jmtrandom/package-summary.html">Non-frame version</a>.</p>
</noframes>
</frameset>
</html> |
#include "stdafx.h"
#include "LMCore.h"
#include "LMDebug.h"
#include "ExceptionHandling.h"
#if PLATFORM_WINDOWS
#include "<API key>.h"
#endif // PLATFORM_WINDOWS
namespace Lightmass
{
FString InstigatorUserName;
/** Crash reporter URL, as set by AutoReporter.exe after being launched by <API key>(). */
static FString GCrashReporterURL;
/**
* Returns the crash reporter URL after <API key>() has been called.
*/
const FString& <API key>()
{
return GCrashReporterURL;
}
void <API key>()
{
/** Only handle the first critical error. */
static bool <API key> = false;
if ( <API key> == false )
{
<API key> = true;
GCrashReporterURL.Empty();
// Dump the error and flush the log.
UE_LOG(LogLightmass, Error, TEXT("=== Critical error: === %s") LINE_TERMINATOR TEXT("%s"), <API key>, GErrorHist);
GLog->Flush();
// Create an AutoReporter report.
#if !UE_BUILD_DEBUG
{
TCHAR ReportDumpVersion[] = TEXT("4");
TCHAR ReportDumpFilename[] = TEXT("UE4AutoReportDump.txt");
TCHAR AutoReportExe[] = TEXT("../DotNET/AutoReporter.exe");
TCHAR IniDumpFilename[] = TEXT("<API key>.txt");
FArchive* AutoReportFile = IFileManager::Get().CreateFileWriter(ReportDumpFilename);
if (AutoReportFile != NULL)
{
TCHAR CompName[256];
FCString::Strcpy(CompName, FPlatformProcess::ComputerName());
TCHAR UserName[256];
if (InstigatorUserName.Len() > 0 && !InstigatorUserName.Contains(FPlatformProcess::UserName()) )
{
// Override the current machine's username with the instigator's username,
// So that it's easy to track crashes on remote machines back to the person launching the lighting build.
FCString::Strcpy(UserName, *InstigatorUserName);
}
else
{
FCString::Strcpy(UserName, FPlatformProcess::UserName());
}
TCHAR GameName[256];
FCString::Strcpy(GameName, TEXT("Lightmass"));
TCHAR PlatformName[32];
#if PLATFORM_WINDOWS
#if _WIN64
FCString::Strcpy(PlatformName, TEXT("PC 64-bit"));
#else
FCString::Strcpy(PlatformName, TEXT("PC 32-bit"));
#endif
#elif PLATFORM_MAC
FCString::Strcpy(PlatformName, TEXT("Mac"));
#elif PLATFORM_LINUX
FCString::Strcpy(PlatformName, TEXT("Linux"));
#endif
TCHAR LangExt[10];
FCString::Strcpy(LangExt, TEXT("English"));
TCHAR SystemTime[256];
FCString::Strcpy(SystemTime, *FDateTime::Now().ToString());
TCHAR EngineVersionStr[32];
FCString::Strcpy(EngineVersionStr, *FString::FromInt(1));
TCHAR <API key>[32];
FCString::Strcpy(<API key>, *FString::FromInt(0));
TCHAR CmdLine[2048];
FCString::Strncpy(CmdLine, FCommandLine::Get(), ARRAY_COUNT(CmdLine));
FCString::Strncat(CmdLine, TEXT(" -unattended"), ARRAY_COUNT(CmdLine));
TCHAR BaseDir[260];
FCString::Strncpy(BaseDir, FPlatformProcess::BaseDir(), ARRAY_COUNT(BaseDir));
TCHAR separator = 0;
TCHAR EngineMode[64];
FCString::Strcpy(EngineMode, TEXT("Tool"));
//build the report dump file
AutoReportFile->Serialize( ReportDumpVersion, FCString::Strlen(ReportDumpVersion) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( CompName, FCString::Strlen(CompName) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( UserName, FCString::Strlen(UserName) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( GameName, FCString::Strlen(GameName) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( PlatformName, FCString::Strlen(PlatformName) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( LangExt, FCString::Strlen(LangExt) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( SystemTime, FCString::Strlen(SystemTime) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( EngineVersionStr, FCString::Strlen(EngineVersionStr) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( <API key>, FCString::Strlen(<API key>) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( CmdLine, FCString::Strlen(CmdLine) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( BaseDir, FCString::Strlen(BaseDir) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( GErrorHist, FCString::Strlen(GErrorHist) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Serialize( EngineMode, FCString::Strlen(EngineMode) * sizeof(TCHAR) );
AutoReportFile->Serialize( &separator, sizeof(TCHAR) );
AutoReportFile->Flush();
delete AutoReportFile;
FString UserLogFile( FLightmassLog::Get()->GetLogFilename() );
//start up the auto reporting app, passing the report dump file path, the games' log file, the ini dump path and the minidump path
//protect against spaces in paths breaking them up on the commandline
FString CallingCommandLine = FString::Printf(TEXT("%d \"%s\" \"%s\" \"%s\" \"%s\" -unattended"),
(uint32)(FPlatformProcess::GetCurrentProcessId()), ReportDumpFilename, *UserLogFile, IniDumpFilename, MiniDumpFilenameW);
FProcHandle ProcHandle = FPlatformProcess::CreateProc(AutoReportExe, *CallingCommandLine, true, false, false, NULL, 0, NULL, NULL);
if ( ProcHandle.IsValid() )
{
FPlatformProcess::WaitForProc(ProcHandle);
{
// Read the URL from the crash report log file
FILE *<API key>;
#if PLATFORM_WINDOWS
if ( fopen_s( &<API key>, "AutoReportLog.txt", "r" ) == 0 )
#else
if ( ( <API key> = fopen( "AutoReportLog.txt", "r" ) ) != NULL )
#endif
{
// Read each line, looking for the URL
const uint32 LineBufferSize = 1024;
char LineBuffer[LineBufferSize];
const char* URLSearchText = "CrashReport url = ";
char* URLFoundText = NULL;
while( fgets( LineBuffer, LineBufferSize, <API key> ) != NULL )
{
if( ( URLFoundText = FCStringAnsi::Strstr( LineBuffer, URLSearchText ) ) != NULL )
{
URLFoundText += FCStringAnsi::Strlen( URLSearchText );
GCrashReporterURL = StringCast<TCHAR>(URLFoundText).Get();
break;
}
}
fclose( <API key> );
}
else
{
GCrashReporterURL = TEXT("Not found (unable to open log file)!");
}
}
}
else
{
UE_LOG(LogLightmass, Error, TEXT("Couldn't start up the Auto Reporting process!"));
}
}
}
#endif // UE_BUILD_DEBUG
}
}
} //namespace Lightmass
#if PLATFORM_WINDOWS
#include "<API key>.h"
#endif // PLATFORM_WINDOWS |
# modification, are permitted provided that the following conditions are met:
# documentation and/or other materials provided with the distribution.
# * Neither the name of Intel Corporation nor Carnegie Mellon University,
# nor the names of their contributors, may be used to endorse or
# promote products derived from this software without specific prior
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION OR CARNEGIE MELLON
# UNIVERSITY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# -*- coding: utf-8 -*-
'''An example of TSR chaining for reaching for a bottle. This example uses two TSR Chains, each of length 1, to define the allowable goal end-effector poses'''
from openravepy import *
from numpy import *
from str2num import *
from rodrigues import *
from TransformMatrix import *
from TSR import *
import time
if __name__ == "__main__":
#load the environment if it is not already loaded
try:
orEnv
except NameError:
orEnv = Environment()
# orEnv.SetViewer('qtcoin')
orEnv.Reset()
orEnv.Load('/pr/data/ormodels/environments/<API key>.env.xml')
targobject = orEnv.ReadKinBodyXMLFile('/pr/data/ormodels/objects/household/juice_bottle_model.kinbody.xml')
orEnv.AddKinBody(targobject)
T0_object = MakeTransform(mat(eye(3)),mat([-0.6398+1, 1.5826-1.36, 0.9214]).T)
targobject.SetTransform(T0_object[0:3][:,0:4])
robot = orEnv.GetRobots()[0]
#set printing, display options, and collision checker
orEnv.SetDebugLevel(DebugLevel.Info)
checker = orEnv.<API key>('ode')
orEnv.SetCollisionChecker(checker)
#create problem instances
probs_cbirrt = orEnv.CreateProblem('CBiRRT')
orEnv.LoadProblem(probs_cbirrt,'BarrettWAM')
#set up joint indices
jointdofs = range(0,11)
activedofs = range(0,7)
initdofvals = r_[-pi/2, 0, 0, pi/2, 0, 0, 0, 0, 0, 0, 0]
#start the robot in a reasonable location and configuration
Trobot = array([-0.9970, 0.0775, 0, -0.0775, -0.9970, 0, 0, 0, 1.0000, -0.8680+1.46, 0.5969-1, 0.7390]).reshape(4,3).T
robot.SetTransform(Trobot)
robot.SetActiveDOFValues(initdofvals)
#preshape the fingers
handdof = r_[(0.5*ones([1,3]))[0]];
robot.SetActiveDOFs([7, 8, 9])
robot.SetActiveDOFValues(handdof)
#set the active dof
robot.SetActiveDOFs(activedofs)
#let's define two TSR chains for this task, they differ only in the rotation of the hand
#first TSR chain
#place the first TSR's reference frame at the object's frame relative to world frame
T0_w = T0_object
#get the TSR's offset frame in w coordinates
Tw_e1 = MakeTransform(rodrigues([pi/2, 0, 0]),mat([0, 0.22, 0.1]).T)
#define bounds to only allow rotation of the hand about z axis and a small deviation in translation along the z axis
Bw = mat([0, 0, 0, 0, -0.02, 0.02, 0, 0, 0, 0, -pi, pi])
TSRstring1 = SerializeTSR(0,'NULL',T0_w,Tw_e1,Bw)
TSRChainString1 = SerializeTSRChain(0,1,0,1,TSRstring1,'NULL',[])
#now define the second TSR chain
#it is the same as the first TSR Chain except Tw_e is different (the hand is rotated by 180 degrees about its z axis)
Tw_e2 = MakeTransform(rodrigues([0, pi, 0])*rodrigues([pi/2, 0, 0]),mat([0, 0.22, 0.1]).T)
TSRstring2 = SerializeTSR(0,'NULL',T0_w,Tw_e2,Bw)
TSRChainString2 = SerializeTSRChain(0,1,0,1,TSRstring2,'NULL',[])
#call the cbirrt planner, it will generate a file with the trajectory called 'cmovetraj.txt'
#for i in range(0,5):
time.sleep(1)
numruns = 100;
runtimes = []
for i in range(numruns):
starttime = time.time();
orEnv.LockPhysics(True)
robot.SetActiveDOFValues(initdofvals[0:7])
resp = probs_cbirrt.SendCommand('RunCBiRRT psample 0.25 %s %s'%(TSRChainString1,TSRChainString2))
robot.GetEnv().LockPhysics(False)
timediff = time.time() - starttime
print('Timedif: %f'%(timediff))
runtimes.append(timediff)
avgtime = 0;
for t in runtimes:
avgtime = avgtime + t
avgtime = avgtime/numruns
print('Avgtime: %f'%(avgtime))
#probs_cbirrt.SendCommand('traj cmovetraj.txt')
#robot.GetEnv().LockPhysics(False)
#robot.WaitForController(0) |
#ifndef INCLUDE_HISTORY_H_
#define INCLUDE_HISTORY_H_
#include <common.h>
#include <graph.h>
namespace gbolt {
class History {
public:
History(int max_edges, int max_vertice) : edge_size_(0) {
edges_ = new ConstEdgePointer[max_edges + 1];
has_edges_ = new bool[max_edges + 1]();
has_vertice_ = new bool[max_vertice + 1]();
}
void build(const prev_dfs_t &start, const Graph &graph);
void build_edges(const prev_dfs_t &start, const Graph &graph);
void build_edges_min(const MinProjection &projection, const Graph &graph, int start);
void build_vertice(const prev_dfs_t &start, const Graph &graph);
void build_vertice_min(const MinProjection &projection, const Graph &graph, int start);
bool has_edges(int index) const {
return has_edges_[index];
}
bool has_vertice(int index) const {
return has_vertice_[index];
}
const edge_t *get_p_edge(int index) const {
return edges_[edge_size_ - index - 1];
}
~History() {
delete[] edges_;
delete[] has_edges_;
delete[] has_vertice_;
}
private:
typedef const edge_t * ConstEdgePointer;
ConstEdgePointer *edges_;
bool *has_edges_;
bool *has_vertice_;
int edge_size_;
};
} // namespace gbolt
#endif // INCLUDE_HISTORY_H_ |
#!/usr/bin/env bash
MASON_NAME=wagyu
MASON_VERSION=0.1.0
MASON_HEADER_ONLY=true
. ${MASON_DIR}/mason.sh
function mason_load_source {
mason_download \
https://github.com/mapbox/wagyu/archive/${MASON_VERSION}.tar.gz \
<SHA1-like>
<API key>
export MASON_BUILD_PATH=${MASON_ROOT}/.build/wagyu-${MASON_VERSION}
}
function mason_compile {
mkdir -p ${MASON_PREFIX}/include/
cp -r include/mapbox ${MASON_PREFIX}/include/mapbox
}
function mason_cflags {
echo "-I${MASON_PREFIX}/include"
}
function mason_ldflags {
:
}
mason_run "$@" |
using System;
using System.Linq;
using Saritasa.Tools.Messages.Abstractions;
namespace Saritasa.Tools.Messages.Common
{
<summary>
Message pipeline extensions.
</summary>
public static class <API key>
{
<summary>
Add middlewares to pipeline.
</summary>
<param name="pipeline">Pipeline to add middlewares.</param>
<param name="middlewares">Middlewares to add.</param>
public static void AddMiddlewares(this IMessagePipeline pipeline,
params <API key>[] middlewares)
{
if (middlewares == null)
{
throw new <API key>(nameof(middlewares));
}
if (pipeline.Middlewares == null)
{
pipeline.Middlewares = middlewares;
return;
}
var list = pipeline.Middlewares.ToList();
list.AddRange(middlewares);
pipeline.Middlewares = list.ToArray();
}
<summary>
Returns middleware in pipeline with specified id or generates <see cref="<API key>" />.
</summary>
<param name="pipeline">Pipeline to search.</param>
<param name="id">Middleware id.</param>
<returns>Found middleware.</returns>
public static <API key> GetMiddlewareById(this IMessagePipeline pipeline, string id)
{
var middleware = pipeline.Middlewares.FirstOrDefault(m => m.Id == id);
if (middleware == null)
{
throw new <API key>($"Cannot find middleware with id {id} in pipeline {pipeline}.");
}
return middleware;
}
<summary>
Replaces middleware with specific id with another one.
</summary>
<param name="pipeline">Pipeline to search.</param>
<param name="id">Middleware id to replace by.</param>
<param name="targetMiddleware">Target middleware.</param>
public static void <API key>(this IMessagePipeline pipeline, string id,
<API key> targetMiddleware)
{
var middleware = GetMiddlewareById(pipeline, id);
var middlewaresList = pipeline.Middlewares.ToList();
middlewaresList[middlewaresList.IndexOf(middleware)] = targetMiddleware;
pipeline.Middlewares = middlewaresList.ToArray();
}
<summary>
Removes middleware with specific id.
</summary>
<param name="pipeline">Pipeline to search.</param>
<param name="id">Middleware id to remove.</param>
public static void <API key>(this IMessagePipeline pipeline, string id)
{
var middleware = GetMiddlewareById(pipeline, id);
var middlewaresList = pipeline.Middlewares.ToList();
middlewaresList.Remove(middleware);
pipeline.Middlewares = middlewaresList.ToArray();
}
}
} |
package eu.matejkormuth.fbrepostbot.facebook;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.<API key>;
import org.apache.http.client.methods.<API key>;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Request {
private static final Logger log = LoggerFactory.getLogger(Request.class);
private final String method;
private final String accessToken;
private String url = "";
private List<NameValuePair> postData;
Request(String method, String accessToken) {
this.method = method;
this.accessToken = accessToken;
}
public Request url(String url) {
this.url = FacebookAPI.API_URL + url;
return this;
}
public Request data(String key, String value) {
if (this.postData == null) {
this.postData = new ArrayList<>();
}
this.postData.add(new BasicNameValuePair(key, value));
return this;
}
private void appendAccessToken() {
if (url.contains("?")) {
url += "&access_token=" + accessToken;
} else {
url += "?access_token=" + accessToken;
}
}
public JSONObject send() throws FacebookException {
try {
// Append access token to URL.
this.appendAccessToken();
// Create HttpClient.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpRequestBase request;
<API key> response = null;
// Create request.
if (this.method == "GET") {
request = new HttpGet(this.url);
} else if (this.method == "POST") {
request = new HttpPost(this.url);
((HttpPost) request).setEntity(new <API key>(this.postData, Charsets.UTF_8));
} else {
throw new <API key>("Unsupported method " + this.method);
}
// Read response.
try {
response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
String responseString = CharStreams.toString(new InputStreamReader(entity.getContent(),
Charsets.UTF_8));
JSONObject obj = new JSONObject(responseString);
// Check for errors.
if (obj.has("error")) {
JSONObject error = obj.getJSONObject("error");
throw new FacebookException("API Exception: " + error.getString("type") + ": "
+ error.getString("message"));
}
// Ensure the entity is fully consumed.
EntityUtils.consume(entity);
return obj;
} finally {
httpclient.close();
if (response != null) {
response.close();
}
}
} catch (Exception e) {
throw new FacebookException("Nested exception: ", e);
}
}
} |
var onReady = require('kwf/commonjs/on-ready');
window.$ = require('jquery'); //leak for qunit
$(function() {
$('#show').click(function() {
$('.foo').show();
onReady.callOnContentReady(document.body, { action: 'show' });
});
$('#hide').click(function() {
$('.foo').hide();
onReady.callOnContentReady(document.body, { action: 'hide' });
});
});
onReady.onShow('.foo', function(el) {
$('#log').append('show');
});
onReady.onHide('.foo', function(el) {
$('#log').append('hide');
}); |
// tipsy, facebook style tooltips for jquery
// version 1.0.0a
(function($) {
function maybeCall(thing, ctx) {
return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
}
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = true;
this.fixTitle();
}
Tipsy.prototype = {
show: function() {
var title = this.getTitle();
if (title && this.enabled) {
var $tip = this.tip();
$tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
$tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
$tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);
var pos = $.extend({}, this.$element.offset(), {
width: this.$element[0].offsetWidth || 0,
height: this.$element[0].offsetHeight || 0
});
if (typeof this.$element[0].<API key> == 'object') {
// SVG
var el = this.$element[0];
var rect = el.<API key>();
pos.width = rect.width;
pos.height = rect.height;
}
var actualWidth = $tip[0].offsetWidth,
actualHeight = $tip[0].offsetHeight,
gravity = maybeCall(this.options.gravity, this.$element[0]);
var tp;
switch (gravity.charAt(0)) {
case 'n':
tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 's':
tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'e':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
break;
case 'w':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
break;
}
if (gravity.length == 2) {
if (gravity.charAt(1) == 'w') {
tp.left = pos.left + pos.width / 2 - 15;
} else {
tp.left = pos.left + pos.width / 2 - actualWidth + 15;
}
}
$tip.css(tp).addClass('tipsy-' + gravity);
$tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
if (this.options.className) {
$tip.addClass(maybeCall(this.options.className, this.$element[0]));
}
if (this.options.fade) {
$tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
} else {
$tip.css({visibility: 'visible', opacity: this.options.opacity});
}
var t = this;
var set_hovered = function(set_hover){
return function(){
t.$tip.stop();
t.tipHovered = set_hover;
if (!set_hover){
if (t.options.delayOut === 0) {
t.hide();
} else {
setTimeout(function() {
if (t.hoverState == 'out') t.hide(); }, t.options.delayOut);
}
}
};
};
$tip.hover(set_hovered(true), set_hovered(false));
}
},
hide: function() {
if (this.options.fade) {
this.tip().stop().fadeOut(function() { $(this).remove(); });
} else {
this.tip().remove();
}
},
fixTitle: function() {
var $e = this.$element;
if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
$e.attr('original-title', $e.attr('title') || '').removeAttr('title');
}
if (typeof $e.context.<API key> == 'object'){
if ($e.children('title').length){
$e.append('<original-title>' + ($e.children('title').text() || '') + '</original-title>')
.children('title').remove();
}
}
},
getTitle: function() {
var title, $e = this.$element, o = this.options;
this.fixTitle();
if (typeof o.title == 'string') {
var title_name = o.title == 'title' ? 'original-title' : o.title;
if ($e.children(title_name).length){
title = $e.children(title_name).html();
} else{
title = $e.attr(title_name);
}
} else if (typeof o.title == 'function') {
title = o.title.call($e[0]);
}
title = ('' + title).replace(/(^\s*|\s*$)/, "");
return title || o.fallback;
},
tip: function() {
if (!this.$tip) {
this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
}
return this.$tip;
},
validate: function() {
if (!this.$element[0].parentNode) {
this.hide();
this.$element = null;
this.options = null;
}
},
enable: function() { this.enabled = true; },
disable: function() { this.enabled = false; },
toggleEnabled: function() { this.enabled = !this.enabled; }
};
$.fn.tipsy = function(options) {
if (options === true) {
return this.data('tipsy');
} else if (typeof options == 'string') {
var tipsy = this.data('tipsy');
if (tipsy) tipsy[options]();
return this;
}
options = $.extend({}, $.fn.tipsy.defaults, options);
if (options.hoverlock && options.delayOut === 0) {
options.delayOut = 100;
}
function get(ele) {
var tipsy = $.data(ele, 'tipsy');
if (!tipsy) {
tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
$.data(ele, 'tipsy', tipsy);
}
return tipsy;
}
function enter() {
var tipsy = get(this);
tipsy.hoverState = 'in';
if (options.delayIn === 0) {
tipsy.show();
} else {
tipsy.fixTitle();
setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
}
}
function leave() {
var tipsy = get(this);
tipsy.hoverState = 'out';
if (options.delayOut === 0) {
tipsy.hide();
} else {
var to = function() {
if (!tipsy.tipHovered || !options.hoverlock){
if (tipsy.hoverState == 'out') tipsy.hide();
}
};
setTimeout(to, options.delayOut);
}
}
if (options.trigger != 'manual') {
var binder = options.live ? 'live' : 'bind',
eventIn = options.trigger == 'hover' ? 'mouseenter' : 'focus',
eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
this[binder](eventIn, enter)[binder](eventOut, leave);
}
return this;
};
$.fn.tipsy.defaults = {
className: null,
delayIn: 0,
delayOut: 0,
fade: false,
fallback: '',
gravity: 'n',
html: false,
live: false,
offset: 0,
opacity: 0.8,
title: 'title',
trigger: 'hover',
hoverlock: false
};
// Overwrite this method to provide options on a per-element basis.
// For example, you could store the gravity in a 'tipsy-gravity' attribute:
// return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
// (remember - do not modify 'options' in place!)
$.fn.tipsy.elementOptions = function(ele, options) {
return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
};
$.fn.tipsy.autoNS = function() {
return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
};
$.fn.tipsy.autoWE = function() {
return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
};
/**
* yields a closure of the supplied parameters, producing a function that takes
* no arguments and is suitable for use as an autogravity function like so:
*
* @param margin (int) - distance from the viewable region edge that an
* element should be before setting its tooltip's gravity to be away
* from that edge.
* @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
* if there are no viewable region edges effecting the tooltip's
* gravity. It will try to vary from this minimally, for example,
* if 'sw' is preferred and an element is near the right viewable
* region edge, but not the top edge, it will set the gravity for
* that element's tooltip to be 'se', preserving the southern
* component.
*/
$.fn.tipsy.autoBounds = function(margin, prefer) {
return function() {
var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
boundTop = $(document).scrollTop() + margin,
boundLeft = $(document).scrollLeft() + margin,
$this = $(this);
if ($this.offset().top < boundTop) dir.ns = 'n';
if ($this.offset().left < boundLeft) dir.ew = 'w';
if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
return dir.ns + (dir.ew ? dir.ew : '');
};
};
})(jQuery); |
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
namespace <API key>
{
/** The section of the ini file we load our settings from */
static const FString SettingsSection = TEXT("SourceControl.<API key>");
}
const FString& <API key>::GetProvider() const
{
return Provider;
}
void <API key>::SetProvider(const FString& InString)
{
Provider = InString;
}
bool <API key>::<API key>() const
{
return bUseGlobalSettings;
}
void <API key>::<API key>(bool <API key>)
{
bUseGlobalSettings = <API key>;
}
void <API key>::LoadSettings()
{
// make sure we load the global ini first
const FString& GlobalIniFile = <API key>::<API key>();
GConfig->GetBool(*<API key>::SettingsSection, TEXT("UseGlobalSettings"), bUseGlobalSettings, GlobalIniFile);
TArray<FString> Tokens;
TArray<FString> Switches;
FCommandLine::Parse( FCommandLine::Get(), Tokens, Switches );
TMap<FString, FString> SwitchPairs;
for (int32 SwitchIdx = Switches.Num() - 1; SwitchIdx >= 0; --SwitchIdx)
{
FString& Switch = Switches[SwitchIdx];
TArray<FString> SplitSwitch;
if (2 == Switch.ParseIntoArray(SplitSwitch, TEXT("="), true))
{
SwitchPairs.Add(SplitSwitch[0], SplitSwitch[1].TrimQuotes());
Switches.RemoveAt(SwitchIdx);
}
}
if( SwitchPairs.Contains( TEXT("SCCProvider") ) )
{
Provider = SwitchPairs[TEXT("SCCProvider")];
}
else
{
const FString& IniFile = <API key>::GetSettingsIni();
GConfig->GetString(*<API key>::SettingsSection, TEXT("Provider"), Provider, IniFile);
}
}
void <API key>::SaveSettings() const
{
const FString& IniFile = <API key>::GetSettingsIni();
const FString& GlobalIniFile = <API key>::<API key>();
GConfig->SetString(*<API key>::SettingsSection, TEXT("Provider"), *Provider, IniFile);
GConfig->SetBool(*<API key>::SettingsSection, TEXT("UseGlobalSettings"), bUseGlobalSettings, GlobalIniFile);
} |
cask "deezer" do
version "5.10.0"
sha256 "<SHA256-like>"
url "https://www.deezer.com/desktop/download/artifact/darwin/x64/#{version}"
name "Deezer"
desc "Music player"
homepage "https:
livecheck do
url "https:
strategy :header_match
end
auto_updates true
depends_on macos: ">= :yosemite"
app "Deezer.app"
zap trash: [
"~/Library/Application Support/Caches/<API key>",
"~/Library/Application Support/deezer-desktop",
"~/Library/Logs/Deezer",
"~/Library/Preferences/ByHost/com.deezer.*",
"~/Library/Preferences/com.deezer.deezer-desktop.plist",
"~/Library/Saved Application State/com.deezer.deezer-desktop.savedState",
]
end |
#ifndef PCMP_COMMON_H
#define PCMP_COMMON_H
#define pcmp_likely(x) __builtin_expect(!!(x), 1)
#define pcmp_unlikely(x) __builtin_expect(!!(x), 0)
#if !defined(PCMP_AVX2) && defined(__AVX2__)
# define PCMP_AVX2 1
#endif
#if !defined(PCMP_SSE42) && defined(__SSE4_2__)
# define PCMP_SSE42 1
#endif
#include <stdint.h>
#ifdef __AVX2__
# include <immintrin.h>
# define PCMP_AVX2_ILP(pipeline, sz, res) \
for (; n >= 32*sz; n -= 32*sz, s1 += 32*sz, s2 += 32*sz) { \
for (int i = 0; i < sz; i++) { pipeline (i, res); } \
for (int i = 0; i < sz; i++) { \
if (res[i] != UINT32_MAX) { return 0; } \
} \
}
#endif
#ifdef __SSE4_2__
# include <nmmintrin.h>
# define PCMP_SSE42_ILP(pipeline, sz, res) \
for (; n >= 16*sz; n -= 16*sz, s1 += 16*sz, s2 += 16*sz) { \
for (int i = 0; i < sz; i++) { pipeline (i, 16, res); } \
for (int i = 0; i < sz; i++) { \
if (res[i] != 16) { return 0; } \
} \
}
#endif
#endif |
package main
import "strings"
type code_section interface {
Code() bool
}
type para string
func (para) Code() bool {
return false
}
type code string
func (code) Code() bool {
return true
}
type Article struct {
Title string
Intro []para
GoCode, ReflectCode []code_section
Uses, Tags []string
slug string
}
func (a *Article) Slug() string {
if a.slug == "" {
a.slug = strings.ToLower(strings.Replace(a.Title, " ", "-", -1))
}
return a.slug
}
type Articles []*Article
func (a *Articles) Add(ao *Article) {
*a = append(*a, ao)
}
func (a Articles) Len() int {
return len(a)
}
func (a Articles) Swap(i, j int) {
a[j], a[i] = a[i], a[j]
}
func (a Articles) Less(i, j int) bool {
return a[i].Title < a[j].Title
} |
class Smake < Formula
desc "Portable make program with automake features"
homepage "https://s-make.sourceforge.io/"
url "https://downloads.sourceforge.net/project/s-make/smake-1.2.5.tar.bz2"
sha256 "<SHA256-like>"
livecheck do
url :stable
end
bottle do
sha256 "<SHA256-like>" => :catalina
sha256 "<SHA256-like>" => :mojave
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :sierra
sha256 "<SHA256-like>" => :el_capitan
sha256 "<SHA256-like>" => :yosemite
sha256 "<SHA256-like>" => :mavericks
sha256 "<SHA256-like>" => :x86_64_linux # glibc 2.19
end
def install
# The bootstrap smake does not like -j
ENV.deparallelize
# Xcode 9 miscompiles smake if optimization is enabled
ENV.O1 if DevelopmentTools.clang_build_version >= 900
system "make", "GMAKE_NOWARN=true", "INS_BASE=#{libexec}", "INS_RBASE=#{libexec}", "install"
bin.install_symlink libexec/"bin/smake" |
// buffer.go
// Use of this source code is governed by a BSD-style
// Package buffer contains helper functions for writing and reading basic
// types into and out of byte slices.
package buffer
// Stdlib imports.
import (
"errors"
)
// Data type sizes.
const (
BYTE_SIZE = 1
UINT8_SIZE = 1
UINT16_SIZE = 2
UINT32_SIZE = 4
UINT64_SIZE = 8
)
// Common errors.
var (
errExceedBounds = errors.New(
"Index exceeds capacity of slice/array",
)
)
// LenByte returns the encoded length of a byte value.
func LenByte() int {
return BYTE_SIZE
}
// LenString returns the encoded length of a given string, including
// the extra bytes required to encode its size.
func LenString(val string) int {
return len(val) + LenUint32()
}
// LenUint8 returns the lengh of a uint32 value.
func LenUint8() int {
return UINT8_SIZE
}
// LenUint16 returns the lengh of a uint32 value.
func LenUint16() int {
return UINT16_SIZE
}
// LenUint32 returns the lengh of a uint32 value.
func LenUint32() int {
return UINT32_SIZE
}
// LenUint64 returns the encoded length of a uint64 value.
func LenUint64() int {
return UINT64_SIZE
}
// ReadByte reads 1 byte value from the given buffer, starting at
// the given offset, and increments teh supplied cursor by the length
// of the encoded value.
func ReadByte(buffer []byte, cursor *int) (byte, error) {
if *cursor + BYTE_SIZE > len(buffer) {
*cursor = len(buffer)
return 0, errExceedBounds
}
val := buffer[*cursor]
*cursor++
return val, nil
}
// ReadString reads 1 string value from the given buffer, starting at
// the given offset, and increments teh supplied cursor by the length
// of the encoded value.
func ReadString(buffer []byte, cursor *int) (string, error) {
size, err := ReadUint32(buffer, cursor)
if err != nil {
return "", err
}
if *cursor + int(size) > len(buffer) {
*cursor = len(buffer)
return "", errExceedBounds
}
val := string(buffer[*cursor:*cursor + int(size)])
*cursor += len(val)
return val, nil
}
// ReadUint32 reads 1 uint32 value from the given buffer, starting at
// the given offset, and increments teh supplied cursor by the length
// of the encoded value.
func ReadUint32(buffer []byte, cursor *int) (uint32, error) {
if *cursor + UINT32_SIZE > len(buffer) {
*cursor = len(buffer)
return 0, errExceedBounds
}
val :=
uint32(buffer[*cursor]) << 24 |
uint32(buffer[*cursor + 1]) << 16 |
uint32(buffer[*cursor + 2]) << 8 |
uint32(buffer[*cursor + 3])
*cursor += UINT32_SIZE
return val, nil
}
// ReadUint64 reads 1 uint64 value from the given buffer, starting at
// the given offset, and increments teh supplied cursor by the length
// of the encoded value.
func ReadUint64(buffer []byte, cursor *int) (uint64, error) {
if *cursor + UINT64_SIZE > len(buffer) {
*cursor = len(buffer)
return 0, errExceedBounds
}
val :=
uint64(buffer[*cursor]) << 56 |
uint64(buffer[*cursor + 1]) << 48 |
uint64(buffer[*cursor + 2]) << 40 |
uint64(buffer[*cursor + 3]) << 32 |
uint64(buffer[*cursor + 4]) << 24 |
uint64(buffer[*cursor + 5]) << 16 |
uint64(buffer[*cursor + 6]) << 8 |
uint64(buffer[*cursor + 7])
*cursor += UINT64_SIZE
return val, nil
}
// WriteByte writes the given byte value into a buffer at the given
// offset and increments the supplied cursor by the length of the encoded
// value.
func WriteByte(val byte, buffer []byte, cursor *int) {
buffer[*cursor] = val
*cursor++
}
// WriteString writes the given string value into a buffer starting at
// the given offset, and increments the supplied counter by the length
// of that encoded string.
func WriteString(val string, buffer []byte, cursor *int) {
WriteUint32(uint32(len(val)), buffer, cursor)
count := copy(buffer[*cursor:], []byte(val))
*cursor += count
}
// WriteUint32 writes the given uint32 value into a buffer at the given
// offset and increments the supplied cursor by the lengh of the encoded
// value.
func WriteUint32(val uint32, buffer []byte, cursor *int) {
buffer[*cursor] = byte(val >> 24); *cursor++
buffer[*cursor] = byte(val >> 16); *cursor++
buffer[*cursor] = byte(val >> 8); *cursor++
buffer[*cursor] = byte(val); *cursor++
}
// WriteUint64 writes the given uint64 value into a buffer at the given
// offset and increments teh supplied cursor by the length of the encoded
// value.
func WriteUint64(val uint64, buffer []byte, cursor *int) {
buffer[*cursor] = byte(val >> 56); *cursor++
buffer[*cursor] = byte(val >> 48); *cursor++
buffer[*cursor] = byte(val >> 40); *cursor++
buffer[*cursor] = byte(val >> 32); *cursor++
buffer[*cursor] = byte(val >> 24); *cursor++
buffer[*cursor] = byte(val >> 16); *cursor++
buffer[*cursor] = byte(val >> 8); *cursor++
buffer[*cursor] = byte(val); *cursor++
} |
#!/bin/bash
set -e
repo=$1
name=$2
src=$3
if [ -z "$repo" ]; then
echo "You need to supply a repository name"
exit 1
fi
if [ -z "$name" ]; then
echo "You need to supply a package name"
exit 1
fi
if [ -z "$src" ]; then
echo "You need to supply a source"
exit 1
fi
#if [ -d "src/packages/$repo/$name" ]; then
# echo "Package already installed"
# exit 1
if [ ! -d "src/packages/$repo/$name" ]; then
mkdir src/packages/$repo
git clone --recursive $src src/packages/$repo/$name
fi
(cd src/packages/$repo/$name && npm install)
node osjs config:add --name=repositories --value=$repo
node osjs build:manifest
node osjs build:package --name=$repo/$name
echo "Done :-)" |
// Dev console
var evaluateBtn = $4.id('devcon-eval-btn'),
expressionTextBox = $4.id('<API key>'),
resContainer = $4.id('devcon-res'),
helpPopWrapper = $4.id('devcon-help'),
helpBtn = $4.id('devcon-help-btn'),
helpCloseBtn = $4.id('<API key>');
var HistoryNavigate = {
historyStack: [],
historyIndex: 0,
// HistoryNavigate.next()
next: function(){
var nextStep = this.historyIndex + 1;
if(this.historyStack[nextStep]){
this.historyIndex = nextStep;
return this.historyStack[this.historyIndex];
}
},
prev: function(){
var prevStep = this.historyIndex - 1;
if(this.historyStack[prevStep]){
this.historyIndex = prevStep;
return this.historyStack[this.historyIndex];
}
},
// @param {String} code
save: function(code){
this.historyStack.push(code);
this.historyIndex = this.historyStack.length;
}
};
//var aCur = new Arifmethic2Cursor();
var exprInstance = new Expression();
exprInstance.addFunction('array', function(args){
return args;
});
exprInstance.addFunction('summ', function(args){
var summ = 0,
array = args[0];
if(Array.isArray(array)){
args[0].forEach(function(item){
summ += item;
});
}else{
summ = undefined;
}
return summ;
});
// 'map(array(1, 2, 3, 4), {x| x^2})',
// 'map(array(1, 2, 3, 4), sin)',
exprInstance.addFunction('map', function(args){
var array = args[0],
lamdaName = args[1],
res = [],
lamdaClojure = {}, // custom clojure also supported!
buf;
if(Array.isArray(array) && this.isExecutable(lamdaName)){
array.forEach(function(item){
buf = this.methodExecution(lamdaName, [item], lamdaClojure);
res.push(buf);
}.bind(this));
}else{
res = undefined;
}
return res;
});
var evaluateCode = function(){
var code = expressionTextBox.value,
res = exprInstance.evaluate(code),
warnings = '';
var resBody = '<div class="expr-row"><span class="output-c1">Expr:</span> `'+code+'`</div>' +
'<div class="expr-row"><span class="output-c2">Ans:</span> ' + res + '</div>';
exprInstance.setVariable('ans', res);
if(exprInstance.cursor.warningStack.length){
warnings = exprInstance.cursor.warningStack.join("<br/>");
resBody += '<div>Warnings:</div>';
resBody += '<div>' + warnings + '</div>';
}
var resNode = $4.cr("div", "innerHTML", resBody, 'className', 'output-container');
resContainer.appendChild(resNode);
expressionTextBox.value = "";
HistoryNavigate.save(code);
};
document.addEventListener('keydown', function(e){
if(e.srcElement == expressionTextBox){
switch(e.keyCode){
case 13:
e.preventDefault();
evaluateCode();
break;
case 38:
var prevCode = HistoryNavigate.prev();
expressionTextBox.value = prevCode;
break;
case 40:
var nextCode = HistoryNavigate.next();
expressionTextBox.value = nextCode;
break;
}
}
});
evaluateBtn.addEventListener('click', function(e){
evaluateCode();
});
helpBtn.addEventListener('click', function(e){
helpPopWrapper.style.display = '';
});
helpCloseBtn.addEventListener('click', function(e){
helpPopWrapper.style.display = 'none';
}); |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Acid (loadSet, addExperiment) where
import Control.Monad.Reader
import Control.Monad.State
import Data.Acid
import Data.SafeCopy
import Data.Time.LocalTime (ZonedTime(..))
import Data.Typeable
import qualified Data.Map as Map
import Network.ImageTrove.Main
import Network.MyTardis.RestTypes
import qualified Data.Set as Set
import Data.Set (Set)
data ExperimentSet = ExperimentSet !(Set RestExperiment) deriving (Typeable)
$(deriveSafeCopy 0 'base ''RestParameter)
$(deriveSafeCopy 0 'base ''RestSchema)
$(deriveSafeCopy 0 'base ''<API key>)
$(deriveSafeCopy 0 'base ''RestPermission)
$(deriveSafeCopy 0 'base ''RestGroup)
$(deriveSafeCopy 0 'base ''RestObjectACL)
$(deriveSafeCopy 0 'base ''RestExperiment)
$(deriveSafeCopy 0 'base ''ExperimentSet)
insertExperiment :: RestExperiment -> Update ExperimentSet ()
insertExperiment e = do
ExperimentSet s <- get
put $ ExperimentSet $ Set.insert e s
{-
isMember :: RestExperiment -> Query ExperimentSet Bool
isMember e = do
ExperimentSet s <- get
return True -- $ Set.member e s
Doesn't compile:
Acid.hs:41:24:
No instance for (MonadState ExperimentSet (Query ExperimentSet))
arising from a use of `get'
Possible fix:
add an instance declaration for
(MonadState ExperimentSet (Query ExperimentSet))
In a stmt of a 'do' block: ExperimentSet s <- get
In the expression:
do { ExperimentSet s <- get;
return True }
In an equation for `isMember':
isMember e
= do { ExperimentSet s <- get;
return True }
-}
getSetInternal :: Query ExperimentSet (Set RestExperiment)
getSetInternal = do
ExperimentSet s <- ask
return s
$(makeAcidic ''ExperimentSet ['insertExperiment, 'getSetInternal])
loadSet :: FilePath -> IO (Set RestExperiment)
loadSet fp = do
acid <- openLocalStateFrom fp (ExperimentSet Set.empty)
m <- query acid GetSetInternal
closeAcidState acid
return m
addExperiment :: FilePath -> RestExperiment -> IO ()
addExperiment fp e = do
acid <- openLocalStateFrom fp (ExperimentSet Set.empty)
_ <- update acid (InsertExperiment e)
closeAcidState acid |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.Utils.Drawing;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Drawing;
using bv.common.Core;
using ScrollOrientation = System.Windows.Forms.ScrollOrientation;
using VScrollBar = DevExpress.XtraEditors.VScrollBar;
namespace bv.winclient.Core
{
public partial class BvScrollableControl : <API key>
{
public VScrollBar m_VScroll;
private <API key> m_Container;
public BvScrollableControl()
{
<API key>.<API key> = true;
InitializeComponent();
if (Localizer.IsRtl)
{
Margin = new Padding(0);
Padding = new Padding(0);
m_VScroll = new VScrollBar
{
RightToLeft = RightToLeft.No,
Dock = DockStyle.Left,
SmallChange = 5,
Parent = this
};
VerticalScroll.Visible = false;
m_Container = new <API key>();
m_Container.Parent = this;
m_Container.Location = new Point(0, 0);
m_Container.ClientSize = ClientSize;
//m_Container.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
m_VScroll.Scroll += ScrollVertically;
//ParentChanged += SetParent;
Resize += ResizeMe;
//m_VScroll.GotFocus += ScrollGotFocus;
//m_VScroll.MouseUp += ScrollGotFocus;
m_Container.MouseWheel += OnMouseWheel;
//m_VScroll.MouseWheel += OnMouseWheel;
MouseWheel += OnMouseWheel;
}
//else
// m_Container.Visible = false;
// m_VScroll.Visible = false;
}
public int ClientWidth
{
get { return Localizer.IsRtl ? m_Container.ClientSize.Width : ClientSize.Width; }
}
private void ScrollGotFocus(object sender, EventArgs e)
{
m_Container.Select();
}
private void OnMouseWheel(object sender, MouseEventArgs e)
{
if (!m_VScroll.Visible)
return;
//Control control = sender as Control;// NEW LINE
//if (control.Bounds.Contains(e.Location)) return; //NEW LINE
DXMouseEventArgs.GetMouseArgs(e).Handled = true;
int scrollValue = m_VScroll.Value;
if (e.Delta < 0)
{
int delta = m_VScroll.Value + m_VScroll.SmallChange;
m_VScroll.Value = Math.Min(delta, m_VScroll.Maximum - m_VScroll.LargeChange + 1);
}
else
if (scrollValue < m_VScroll.SmallChange)
m_VScroll.Value = 0;
else
m_VScroll.Value -= m_VScroll.SmallChange;
ScrollVertically(m_VScroll, new ScrollEventArgs(ScrollEventType.ThumbPosition, scrollValue, m_VScroll.Value, ScrollOrientation.VerticalScroll));
}
private void SetParent(object sender, EventArgs e)
{
AutoScroll = false;
//m_VScroll.Parent = Parent;
//Parent.MouseWheel += OnMouseWheel;
}
private void ResizeMe(object sender, EventArgs e)
{
if (!m_Initialized)
return;
var showScroll = ClientSize.Height < m_Container.Height;
m_VScroll.LargeChange = ClientSize.Height;
m_VScroll.Maximum = m_Container.Height;// -m_VScroll.LargeChange + 1;
m_VScroll.Visible = showScroll;
m_Container.Left = showScroll ? m_VScroll.Width : 0;
m_Container.Width = showScroll ? Width - m_VScroll.Width : Width;
}
private void ScrollVertically(object sender, ScrollEventArgs e)
{
SuspendLayout();
m_Container.SuspendLayout();
Point p = m_Container.Location;
p.Y = 0 - e.NewValue;
m_Container.Location = p;
m_Container.ResumeLayout();
ResumeLayout();
//VerticalScroll.Value = e.NewValue;
}
private bool m_Initialized;
public void Init()
{
if (Localizer.IsRtl)
{
int bottom = 0;
m_Container.ClientSize = new Size(ClientSize.Width, ClientSize.Height);
foreach (Control ctl in Controls.Cast<Control>().ToList())
{
if (ctl == m_VScroll || ctl == m_Container)
continue;
if (bottom < ctl.Top + ctl.Height)
{
bottom = ctl.Top + ctl.Height;
}
ctl.Parent = m_Container;
}
m_Container.ClientSize = new Size(ClientSize.Width,
bottom + m_Container.Margin.Top + m_Container.Margin.Bottom +
m_Container.Padding.Top + m_Container.Padding.Bottom + 4);
m_VScroll.Value = 0;
//ResizeMe(this, EventArgs.Empty);
}
m_Initialized = true;
}
//internal bool IsCaptured = false;
//<API key> m_CapturedScrollBar = null;
//protected internal <API key> CapturedScrollBar
// get { return m_CapturedScrollBar; }
// set
// if (value == m_CapturedScrollBar) return;
// m_CapturedScrollBar = value;
//protected override void OnMouseEnter(EventArgs e)
// base.OnMouseEnter(e);
// OnScrollAction(ScrollNotifyAction.MouseMove);
//internal void OnScrollAction(ScrollNotifyAction action)
// m_VScroll.OnAction(action);
//protected override void OnMouseMove(MouseEventArgs e)
// OnScrollAction(ScrollNotifyAction.MouseMove);
// if (Capture && CapturedScrollBar != null) CapturedScrollBar.OnMouseMove(e);
// base.OnMouseMove(e);
//protected override void OnMouseUp(MouseEventArgs e)
// if (IsCaptured)
// ResetCapture();
// if (CapturedScrollBar != null)
// CapturedScrollBar.OnMouseUp(e);
// CapturedScrollBar.OnLostCapture();
// return;
// base.OnMouseUp(e);
//protected override void OnMouseDown(MouseEventArgs e)
// ResetCapture();
// base.OnMouseDown(e);
//void ResetCapture()
// if (!IsCaptured) return;
// IsCaptured = false;
// Capture = false;
//protected override void OnPaint(PaintEventArgs e)
// if (Localizer.IsRtl)
// using (GraphicsCache cache = new GraphicsCache(e))
// StyleObjectInfoArgs args = new StyleObjectInfoArgs();
// args.SetAppearance(new AppearanceObject(Appearance, DefaultAppearance));
// args.Bounds = ClientRectangle;
// ObjectPainter.DrawObject(cache, Painter, args);
// base.RaisePaintEvent(this, e);
// else
// base.OnPaint(e);
private void ScrollDown(int pos)
{
//pos passed in should be positive
using (Control c = new Control() { Parent = this, Height = 1, Top = this.ClientSize.Height + pos })
{
<API key>(c);
}
}
private void ScrollUp(int pos)
{
//pos passed in should be negative
using (Control c = new Control() { Parent = this, Height = 1, Top = pos })
{
<API key>(c);
}
}
}
//public partial class BvScrollableControl : DevExpress.XtraEditors.<API key>
// public BvScrollableControl()
// InitializeComponent();
// protected <API key> m_VScroll;
// protected override <API key> CreateVScrollBar()
// m_VScroll = base.CreateVScrollBar();
// return m_VScroll;
// protected override void SyncScrollbars()
// base.SyncScrollbars();
// if (IsHandleCreated && RightToLeft == RightToLeft.Yes)
// m_VScroll.Bounds = new Rectangle(new Point(0, 0), m_VScroll.Bounds.Size);
// m_VScroll.Invalidate();
//public class <API key> : <API key>
// public <API key>(<API key> owner)
// : base(owner)
// public override RightToLeft RightToLeft
// get
// return Localizer.IsRtl? RightToLeft.Yes : RightToLeft.No;
} |
#board {
margin-left: 20px;
margin-right: 20px;
border: 5px solid grey;
}
.pexeso-card {
display: inline-block;
margin: 5px;
border: 1px solid black;
}
.pexeso-card img {
width: 100px;
height: 100px;
}
.pexeso-card .back {
display: block;
}
.pexeso-card .front {
display: none;
}
.pexeso-card.turned .back {
display: none;
}
.pexeso-card.turned .front {
display: block;
} |
"""Defines "parency links" between two "persons", and a user interface
to manage them.
This module is probably useful in combination with
:mod:`lino_xl.lib.households`.
.. autosummary::
:toctree:
choicelists
models
"""
from lino.api import ad, _
class Plugin(ad.Plugin):
"Extends :class:`lino.core.plugin.Plugin`."
verbose_name = _("Parency links")
## settings
person_model = 'contacts.Person'
"""
A string referring to the model which represents a human in your
application. Default value is ``'contacts.Person'`` (referring to
:class:`lino_xl.lib.contacts.Person`).
"""
def on_site_startup(self, site):
self.person_model = site.models.resolve(self.person_model)
super(Plugin, self).on_site_startup(site)
def setup_explorer_menu(self, site, user_type, m):
# mg = site.plugins.contacts
mg = site.plugins[self.person_model._meta.app_label]
m = m.add_menu(mg.app_label, mg.verbose_name)
m.add_action('humanlinks.Links')
m.add_action('humanlinks.LinkTypes') |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-11-26 15:14
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('generic', '<API key>'),
migrations.<API key>(settings.AUTH_USER_MODEL),
('links', '<API key>'),
]
operations = [
migrations.CreateModel(
name='UserTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generic.Keyword')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterField(
model_name='link',
name='image',
field=models.FileField(blank=True, max_length=10000, null=True, upload_to='drum', verbose_name='image'),
),
migrations.AlterField(
model_name='link',
name='link',
field=models.URLField(blank=True, null=True, verbose_name='link'),
),
] |
require 'db/sqlite3'
require 'models/data_types'
require 'models/<API key>'
require 'simple'
require 'jdbc_common'
class SQLite3SimpleTest < Test::Unit::TestCase
include SimpleTestMethods
include <API key>
include <API key>
include DirtyAttributeTests
include <API key>
include <API key> if ar_version("3.1")
include <API key>
def <API key>
assert connection.tables.include?(Entry.table_name)
db = connection.database_name
connection.recreate_database(db)
assert ! connection.tables.include?(Entry.table_name)
self.setup # avoid teardown complaining
end
def test_execute_insert
user = User.create! :login => 'user1'
Entry.create! :title => 'E1', :user_id => user.id
assert_equal 1, Entry.count
# NOTE: AR actually returns an empty [] (not an ID) !?
id = connection.execute "INSERT INTO entries (title, content) VALUES ('Execute Insert', 'This now works with SQLite3')"
assert_equal Entry.last.id, id if defined? JRUBY_VERSION # sqlite3 returns []
assert_equal 2, Entry.count
end
def <API key>
skip('only supported since 3.7.11') if connection.send(:sqlite_version) < '3.7.11'
count = Entry.count
connection.execute "INSERT INTO entries (title, content) VALUES ('E1', 'exec insert1'), ('E2', 'exec insert2')"
assert_equal count + 2, Entry.count
end
def test_execute_update
user = User.create! :login => 'user1'
Entry.create! :title => 'E1', :user_id => user.id
affected_rows = connection.execute "UPDATE entries SET title = 'Execute Update' WHERE id = #{Entry.first.id}"
assert_equal 1, affected_rows if defined? JRUBY_VERSION # sqlite3 returns []
assert_equal 'Execute Update', Entry.first.title
end
def test_columns
cols = ActiveRecord::Base.connection.columns("entries")
assert cols.find { |col| col.name == "title" }
end
def test_remove_column
<API key> do
ActiveRecord::Schema.define do
add_column "entries", "test_remove_column", :string
end
end
cols = ActiveRecord::Base.connection.columns("entries")
assert cols.find {|col| col.name == "test_remove_column"}
#<API key> do
ActiveRecord::Schema.define do
remove_column "entries", "test_remove_column"
end
#end
cols = ActiveRecord::Base.connection.columns("entries")
assert_nil cols.find {|col| col.name == "test_remove_column"}
end
def test_rename_column
#<API key> do
ActiveRecord::Schema.define do
rename_column "entries", "title", "name"
end
#end
cols = ActiveRecord::Base.connection.columns("entries")
assert_not_nil cols.find {|col| col.name == "name"}
assert_nil cols.find {|col| col.name == "title"}
<API key> do
ActiveRecord::Schema.define do
rename_column "entries", "name", "title"
end
end
cols = ActiveRecord::Base.connection.columns("entries")
assert_not_nil cols.find {|col| col.name == "title"}
assert_nil cols.find {|col| col.name == "name"}
end
def <API key>
title = "First post!"
content = "Hello from JRuby on Rails!"
rating = 205.76
user = User.create! :login => "something"
entry = Entry.create! :title => title, :content => content, :rating => rating, :user => user
entry.reload
#assert_equal title, entry.title
#assert_equal content, entry.content
#assert_equal rating, entry.rating
ActiveRecord::Schema.define do
rename_column "entries", "title", "name"
rename_column "entries", "rating", "popularity"
end
entry = Entry.find(entry.id)
assert_equal title, entry.name
assert_equal content, entry.content
assert_equal rating, entry.popularity
end
def <API key>
assert_equal(0, connection.indexes(:entries).size)
index_name = "entries_index"
ActiveRecord::Schema.define do
add_index "entries", "title", :name => index_name
end
indexes = connection.indexes(:entries)
assert_equal(1, indexes.size)
assert_equal "entries", indexes.first.table.to_s
assert_equal index_name, indexes.first.name
assert ! indexes.first.unique
assert_equal ["title"], indexes.first.columns
ActiveRecord::Schema.define do
rename_column "entries", "title", "name"
end
indexes = connection.indexes(:entries)
assert_equal(1, indexes.size)
assert_equal "entries", indexes.first.table.to_s
assert_equal index_name, indexes.first.name
assert ! indexes.first.unique
assert_equal ["name"], indexes.first.columns
end
def test_column_default
<API key> do
ActiveRecord::Schema.define do
add_column "entries", "test_column_default", :string
end
end
columns = ActiveRecord::Base.connection.columns("entries")
assert column = columns.find{ |c| c.name == "test_column_default" }
assert_equal column.default, nil
end
def <API key>
<API key> do
ActiveRecord::Schema.define do
add_column "entries", "<API key>", :string, :default => "unchanged"
end
end
columns = ActiveRecord::Base.connection.columns("entries")
assert column = columns.find{ |c| c.name == "<API key>" }
assert_equal column.default, 'unchanged'
<API key> do
ActiveRecord::Schema.define do
<API key> "entries", "<API key>", "changed"
end
end
columns = ActiveRecord::Base.connection.columns("entries")
assert column = columns.find{ |c| c.name == "<API key>" }
assert_equal column.default, 'changed'
end
def test_change_column
<API key> do
ActiveRecord::Schema.define do
add_column "entries", "test_change_column", :string
end
end
columns = ActiveRecord::Base.connection.columns("entries")
assert column = columns.find{ |c| c.name == "test_change_column" }
assert_equal column.type, :string
<API key> do
ActiveRecord::Schema.define do
change_column "entries", "test_change_column", :integer
end
end
columns = ActiveRecord::Base.connection.columns("entries")
assert column = columns.find{ |c| c.name == "test_change_column" }
assert_equal column.type, :integer
end
def <API key>
Entry.delete_all
Entry.
connection.
change_column "entries", "rating", :decimal, :precision => 9, :scale => 7
Entry.<API key>
change_column = Entry.columns_hash["rating"]
assert_equal 9, change_column.precision
assert_equal 7, change_column.scale
end
def <API key>
Entry.delete_all
Entry.
connection.
change_column "entries", "rating", :decimal, :precision => 9, :scale => 7
Entry.<API key>
rating_column = Entry.columns_hash["rating"]
assert_equal 9, rating_column.precision
assert_equal 7, rating_column.scale
Entry.
connection.
change_column "entries", "title", :string, :null => false
Entry.<API key>
rating_column = Entry.columns_hash["rating"]
assert_equal 9, rating_column.precision
assert_equal 7, rating_column.scale
end
def test_delete_sql
ActiveRecord::Base.connection.send :delete_sql, "DELETE FROM entries"
assert Entry.all.empty?
end
# @override
def test_big_decimal
test_value = 1234567890.0 # FINE just like native adapter
db_type = DbType.create!(:big_decimal => test_value)
db_type = DbType.find(db_type.id)
assert_equal test_value, db_type.big_decimal
test_value = 1234567890_123456 # FINE just like native adapter
db_type = DbType.create!(:big_decimal => test_value)
db_type = DbType.find(db_type.id)
assert_equal test_value, db_type.big_decimal
pend 'TODO: compare and revisit how native adapter behaves'
# NOTE: this is getting f*cked up in the native adapter as well although
# differently and only when inserted manually - works with PSs (3.1+) :
test_value = <API key>.0
db_type = DbType.create!(:big_decimal => test_value)
db_type = DbType.find(db_type.id)
# TODO native gets us <API key>.0 JDBC gets us 1
#assert_equal test_value, db_type.big_decimal
#super
end
# @override SQLite3 returns FLOAT (JDBC type) for DECIMAL columns
def <API key>
model = DbType.create! :<API key> => ( decimal = BigDecimal.new('5.45') )
if ActiveRecord::VERSION::MAJOR >= 3
model = DbType.where("id = #{model.id}").select('<API key> AS custom_decimal').first
else
model = DbType.find(:first, :conditions => "id = #{model.id}", :select => '<API key> AS custom_decimal')
end
assert_equal decimal, model.custom_decimal
#assert_instance_of BigDecimal, model.custom_decimal
end
# @override SQLite3 returns String for columns created with DATETIME type
def <API key>
my_time = Time.utc 2013, 03, 15, 19, 53, 51, 0 # usec
model = DbType.create! :sample_datetime => my_time
if ActiveRecord::VERSION::MAJOR >= 3
model = DbType.where("id = #{model.id}").select('sample_datetime AS <API key>').first
else
model = DbType.find(:first, :conditions => "id = #{model.id}", :select => 'sample_datetime AS <API key>')
end
assert_match my_time.to_s(:db), model.<API key> # '2013-03-15 18:53:51.000000'
end
# @override SQLite3 JDBC returns VARCHAR type for column
def <API key>
my_date = Time.local(2000, 01, 30, 0, 0, 0, 0).to_date
model = DbType.create! :sample_date => my_date
if ActiveRecord::VERSION::MAJOR >= 3
model = DbType.where("id = #{model.id}").select('sample_date AS custom_sample_date').first
else
model = DbType.find(:first, :conditions => "id = #{model.id}", :select => 'sample_date AS custom_sample_date')
end
assert_equal my_date.to_s(:db), model.custom_sample_date
end
test 'returns correct visitor type' do
assert_not_nil visitor = connection.<API key>(:@visitor)
assert defined? Arel::Visitors::SQLite
assert_kind_of Arel::Visitors::SQLite, visitor
end if ar_version('3.0')
test "config :timeout set as busy timeout" do
conn = ActiveRecord::Base.connection
unless conn.jdbc_connection.respond_to?(:busy_timeout)
# "old" API: org.sqlite.Conn (not supported setting via JDBC)
version = conn.send(:sqlite_version).to_s
omit "setting timeout not supported on #{version}"
end
begin
with_connection :adapter => 'sqlite3', :database => ':memory:',
:timeout => 1234 do |connection|
sqlite_jdbc = connection.jdbc_connection
assert_equal 1234, sqlite_jdbc.busy_timeout
end
ensure
ActiveRecord::Base.<API key>(SQLITE3_CONFIG)
end
end if defined? JRUBY_VERSION
undef :test_truncate # not supported natively by SQLite
if defined? JRUBY_VERSION
def test_truncate_fake
Thing.create! :name => "t1"
Thing.create! :name => "t2"
Thing.create! :name => "t3"
assert Thing.count > 0
Thing.connection.truncate_fake 'things'
assert_equal 0, Thing.count
end
end
end |
# modification, are permitted provided that the following conditions are met:
# and/or other materials provided with the distribution.
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from django.conf.urls import patterns, url
from signup.views import (ActivationView, PasswordResetView,
<API key>, SigninView, SignoutView, SignupView,
<API key>)
from signup import settings
urlpatterns = patterns('',
# When the key and/or token are wrong we don't want to give any clue
# as to why that is so. Less information communicated to an attacker,
# the better.
url(r'^activate/(?P<verification_key>%s)/password/(?P<token>.+)/$'
% settings.<API key>,
<API key>.as_view(),
name='<API key>'),
url(r'^activate/(?P<verification_key>%s)/$'
% settings.<API key>,
ActivationView.as_view(), name='<API key>'),
url(r'^register/$',
SignupView.as_view(), name='<API key>'),
url(r'^login/recover/',
PasswordResetView.as_view(), name='password_reset'),
url(r'^login/',
SigninView.as_view(), name='login'),
url(r'^logout/',
SignoutView.as_view(), name='logout'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', #pylint: disable=line-too-long
<API key>.as_view(), name='<API key>'),
) |
#include "vgsasm.h"
int parse_int(struct line_data* line, int i)
{
unsigned int v;
if (line[i].toknum < 2) {
sprintf(line[i].error, "syntax error: required argument was not specified");
return -1;
}
if (2 < line[i].toknum) {
sprintf(line[i].error, "syntax error: extra argument was specified: %s", line[i].token[2]);
return -1;
}
if (check_literal(line[i].token[1], &v) || 0xff < v) {
sprintf(line[i].error, "syntax error: invalid argument was specified: %s", line[i].token[1]);
return -1;
}
line[i].op[0] = VGSCPU_OP_INT;
line[i].op[1] = v & 0xff;
line[i].oplen = 2;
return 0;
} |
# Business List for San Diego County.
This list of businesses is published by the San Diego Office of the Treasurer.
The businesses listed in the file have locations across the US, but usually have some presence in San Diego, such as a San Diego location or an owner that lives in San Diego part time. Unfortunately, there is no upstream documentation to explain why many of the business addresses are outside of San Diego. |
#include <mscorlib/System/Security/Cryptography/<API key>.h>
#include <mscorlib/System/<API key>.h>
#include <mscorlib/System/IO/<API key>.h>
#include <mscorlib/System/<API key>.h>
#include <mscorlib/System/<API key>.h>
namespace mscorlib
{
namespace System
{
namespace Security
{
namespace Cryptography
{
//Public Methods
mscorlib::System::Security::Cryptography::SHA256 SHA256::Create()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "SHA256", 0, NULL, "Create", NullMonoObject, 0, NULL, NULL, NULL);
return mscorlib::System::Security::Cryptography::SHA256(__result__);
}
mscorlib::System::Security::Cryptography::SHA256 SHA256::Create(mscorlib::System::String hashName)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(hashName).name());
__parameters__[0] = (MonoObject*)hashName;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "SHA256", 0, NULL, "Create", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Security::Cryptography::SHA256(__result__);
}
mscorlib::System::Security::Cryptography::SHA256 SHA256::Create(const char *hashName)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), hashName);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "SHA256", 0, NULL, "Create", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Security::Cryptography::SHA256(__result__);
}
//Get Set Properties Methods
// Get:<API key>
mscorlib::System::Boolean SHA256::<API key>() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "<API key>", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
// Get:CanReuseTransform
mscorlib::System::Boolean SHA256::<API key>() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "<API key>", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
// Get:Hash
std::vector<mscorlib::System::Byte*> SHA256::get_Hash() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_Hash", __native_object__, 0, NULL, NULL, NULL);
MonoArray *__array_ptr__ = (MonoArray*)__result__;
uintptr_t __array_length__ = mono_array_length(__array_ptr__);
std::vector<mscorlib::System::Byte*> __array_result__(__array_length__);
for(uintptr_t __array_index__ = 0; __array_index__ < __array_length__; __array_index__++)
{
MonoObject *__array_item__ = mono_array_get(__array_ptr__,MonoObject*,__array_index__);
__array_result__.push_back(new mscorlib::System::Byte (__array_item__));
}
return __array_result__;
}
// Get:HashSize
mscorlib::System::Int32 SHA256::get_HashSize() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_HashSize", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
// Get:InputBlockSize
mscorlib::System::Int32 SHA256::get_InputBlockSize() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_InputBlockSize", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
// Get:OutputBlockSize
mscorlib::System::Int32 SHA256::get_OutputBlockSize() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Cryptography", "HashAlgorithm", 0, NULL, "get_OutputBlockSize", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Int32*)mono_object_unbox(__result__);
}
}
}
}
} |
namespace Humidifier.KinesisFirehose
{
using System.Collections.Generic;
using DeliveryStreamTypes;
public class DeliveryStream : Humidifier.Resource
{
public static class Attributes
{
public static string Arn = "Arn" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::KinesisFirehose::DeliveryStream";
}
}
<summary>
DeliveryStreamName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Immutable
PrimitiveType: String
</summary>
public dynamic DeliveryStreamName
{
get;
set;
}
<summary>
DeliveryStreamType
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Immutable
PrimitiveType: String
</summary>
public dynamic DeliveryStreamType
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
}
namespace DeliveryStreamTypes
{
public class OrcSerDe
{
<summary>
BlockSizeBytes
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic BlockSizeBytes
{
get;
set;
}
<summary>
BloomFilterColumns
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: List
PrimitiveItemType: String
</summary>
public dynamic BloomFilterColumns
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Double
</summary>
public dynamic <API key>
{
get;
set;
}
<summary>
Compression
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Compression
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Double
</summary>
public dynamic <API key>
{
get;
set;
}
<summary>
EnablePadding
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic EnablePadding
{
get;
set;
}
<summary>
FormatVersion
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic FormatVersion
{
get;
set;
}
<summary>
PaddingTolerance
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Double
</summary>
public dynamic PaddingTolerance
{
get;
set;
}
<summary>
RowIndexStride
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic RowIndexStride
{
get;
set;
}
<summary>
StripeSizeBytes
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic StripeSizeBytes
{
get;
set;
}
}
public class <API key>
{
<summary>
IntervalInSeconds
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic IntervalInSeconds
{
get;
set;
}
<summary>
SizeInMBs
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic SizeInMBs
{
get;
set;
}
}
public class <API key>
{
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic <API key>
{
get;
set;
}
<summary>
HECEndpoint
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic HECEndpoint
{
get;
set;
}
<summary>
HECEndpointType
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>hecendpointtype
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic HECEndpointType
{
get;
set;
}
<summary>
HECToken
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic HECToken
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
RetryOptions
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: SplunkRetryOptions
</summary>
public SplunkRetryOptions RetryOptions
{
get;
set;
}
<summary>
S3BackupMode
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic S3BackupMode
{
get;
set;
}
<summary>
S3Configuration
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>s3configuration
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> S3Configuration
{
get;
set;
}
}
public class <API key>
{
<summary>
KMSEncryptionConfig
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: KMSEncryptionConfig
</summary>
public KMSEncryptionConfig KMSEncryptionConfig
{
get;
set;
}
<summary>
NoEncryptionConfig
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic NoEncryptionConfig
{
get;
set;
}
}
public class <API key>
{
<summary>
Enabled
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic Enabled
{
get;
set;
}
<summary>
LogGroupName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic LogGroupName
{
get;
set;
}
<summary>
LogStreamName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic LogStreamName
{
get;
set;
}
}
public class <API key>
{
<summary>
Deserializer
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
Type: Deserializer
</summary>
public Deserializer Deserializer
{
get;
set;
}
}
public class <API key>
{
<summary>
Enabled
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic Enabled
{
get;
set;
}
<summary>
Processors
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: List
ItemType: Processor
</summary>
public List<Processor> Processors
{
get;
set;
}
}
public class BufferingHints
{
<summary>
IntervalInSeconds
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic IntervalInSeconds
{
get;
set;
}
<summary>
SizeInMBs
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic SizeInMBs
{
get;
set;
}
}
public class ProcessorParameter
{
<summary>
ParameterName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic ParameterName
{
get;
set;
}
<summary>
ParameterValue
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic ParameterValue
{
get;
set;
}
}
public class HiveJsonSerDe
{
<summary>
TimestampFormats
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: List
PrimitiveItemType: String
</summary>
public dynamic TimestampFormats
{
get;
set;
}
}
public class Processor
{
<summary>
Parameters
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
Type: List
ItemType: ProcessorParameter
</summary>
public List<ProcessorParameter> Parameters
{
get;
set;
}
<summary>
Type
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Type
{
get;
set;
}
}
public class <API key>
{
<summary>
DurationInSeconds
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic DurationInSeconds
{
get;
set;
}
}
public class <API key>
{
<summary>
Enabled
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic Enabled
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
SchemaConfiguration
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>schemaconfiguration
Required: True
UpdateType: Mutable
Type: SchemaConfiguration
</summary>
public SchemaConfiguration SchemaConfiguration
{
get;
set;
}
}
public class KMSEncryptionConfig
{
<summary>
AWSKMSKeyARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic AWSKMSKeyARN
{
get;
set;
}
}
public class <API key>
{
<summary>
Serializer
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
Type: Serializer
</summary>
public Serializer Serializer
{
get;
set;
}
}
public class <API key>
{
<summary>
BufferingHints
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>bufferinghints
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> BufferingHints
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
DomainARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>domainarn
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic DomainARN
{
get;
set;
}
<summary>
IndexName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>indexname
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic IndexName
{
get;
set;
}
<summary>
IndexRotationPeriod
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>indexrotationperiod
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic IndexRotationPeriod
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
RetryOptions
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>retryoptions
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> RetryOptions
{
get;
set;
}
<summary>
RoleARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic RoleARN
{
get;
set;
}
<summary>
S3BackupMode
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>s3backupmode
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic S3BackupMode
{
get;
set;
}
<summary>
S3Configuration
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>s3configuration
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> S3Configuration
{
get;
set;
}
<summary>
TypeName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key><API key>.html#<API key>typename
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic TypeName
{
get;
set;
}
}
public class SchemaConfiguration
{
<summary>
CatalogId
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic CatalogId
{
get;
set;
}
<summary>
DatabaseName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic DatabaseName
{
get;
set;
}
<summary>
Region
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Region
{
get;
set;
}
<summary>
RoleARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic RoleARN
{
get;
set;
}
<summary>
TableName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic TableName
{
get;
set;
}
<summary>
VersionId
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic VersionId
{
get;
set;
}
}
public class SplunkRetryOptions
{
<summary>
DurationInSeconds
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic DurationInSeconds
{
get;
set;
}
}
public class Deserializer
{
<summary>
HiveJsonSerDe
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: HiveJsonSerDe
</summary>
public HiveJsonSerDe HiveJsonSerDe
{
get;
set;
}
<summary>
OpenXJsonSerDe
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: OpenXJsonSerDe
</summary>
public OpenXJsonSerDe OpenXJsonSerDe
{
get;
set;
}
}
public class <API key>
{
<summary>
KinesisStreamARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>kinesisstreamarn
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic KinesisStreamARN
{
get;
set;
}
<summary>
RoleARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic RoleARN
{
get;
set;
}
}
public class ParquetSerDe
{
<summary>
BlockSizeBytes
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic BlockSizeBytes
{
get;
set;
}
<summary>
Compression
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Compression
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic <API key>
{
get;
set;
}
<summary>
MaxPaddingBytes
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic MaxPaddingBytes
{
get;
set;
}
<summary>
PageSizeBytes
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Integer
</summary>
public dynamic PageSizeBytes
{
get;
set;
}
<summary>
WriterVersion
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic WriterVersion
{
get;
set;
}
}
public class Serializer
{
<summary>
OrcSerDe
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: OrcSerDe
</summary>
public OrcSerDe OrcSerDe
{
get;
set;
}
<summary>
ParquetSerDe
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: ParquetSerDe
</summary>
public ParquetSerDe ParquetSerDe
{
get;
set;
}
}
public class CopyCommand
{
<summary>
CopyOptions
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic CopyOptions
{
get;
set;
}
<summary>
DataTableColumns
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic DataTableColumns
{
get;
set;
}
<summary>
DataTableName
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic DataTableName
{
get;
set;
}
}
public class OpenXJsonSerDe
{
<summary>
CaseInsensitive
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic CaseInsensitive
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
Type: Map
PrimitiveItemType: String
</summary>
public Dictionary<string, dynamic> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
PrimitiveType: Boolean
</summary>
public dynamic <API key>
{
get;
set;
}
}
public class <API key>
{
<summary>
BucketARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic BucketARN
{
get;
set;
}
<summary>
BufferingHints
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
Type: BufferingHints
</summary>
public BufferingHints BufferingHints
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
CompressionFormat
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic CompressionFormat
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
ErrorOutputPrefix
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic ErrorOutputPrefix
{
get;
set;
}
<summary>
Prefix
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Prefix
{
get;
set;
}
<summary>
RoleARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic RoleARN
{
get;
set;
}
}
public class <API key>
{
<summary>
BucketARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic BucketARN
{
get;
set;
}
<summary>
BufferingHints
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>bufferinghints
Required: True
UpdateType: Mutable
Type: BufferingHints
</summary>
public BufferingHints BufferingHints
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
CompressionFormat
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>compressionformat
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic CompressionFormat
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
ErrorOutputPrefix
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>erroroutputprefix
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic ErrorOutputPrefix
{
get;
set;
}
<summary>
Prefix
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Prefix
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
RoleARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic RoleARN
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
S3BackupMode
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>s3backupmode
Required: False
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic S3BackupMode
{
get;
set;
}
}
public class <API key>
{
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
ClusterJDBCURL
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>clusterjdbcurl
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic ClusterJDBCURL
{
get;
set;
}
<summary>
CopyCommand
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
Type: CopyCommand
</summary>
public CopyCommand CopyCommand
{
get;
set;
}
<summary>
Password
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Password
{
get;
set;
}
<summary>
<API key>
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key><API key>
Required: False
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> <API key>
{
get;
set;
}
<summary>
RoleARN
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic RoleARN
{
get;
set;
}
<summary>
S3Configuration
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>s3configuration
Required: True
UpdateType: Mutable
Type: <API key>
</summary>
public <API key> S3Configuration
{
get;
set;
}
<summary>
Username
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#<API key>
Required: True
UpdateType: Mutable
PrimitiveType: String
</summary>
public dynamic Username
{
get;
set;
}
}
}
} |
#!/bin/bash
HIGU_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )"
DATA_DIR="$HIGU_DIR/test/data"
WORK_DIR="$( mktemp -d )"
export PYTHONPATH="$WORK_DIR/lib"
export MKDB_LIB_PATH="$WORK_DIR/lib.db"
clean() {
rm -f *.png |
/* 162 */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "euler.h"
#define N 1000
int main(int argc, char **argv)
{
char t[N] = {0};
int s, i = 0, nt = 0;
while (1)
{
s = i * (i + 1) / 2;
if (s > N)
break;
t[s] = 1;
i++;
}
char *tok, *tmp;
char *input = load_file("../files/words.txt");
tok = strtok_r(input, ",", &tmp);
while (tok != NULL)
{
tok[strlen(tok) - 1] = '\0';
tok[0] = '\0';
s = 0;
for (i = 0; i < strlen(tok + 1); i++)
s += tok[i+1] - 'A' + 1;
if (t[s])
nt++;
tok = strtok_r(NULL, ",", &tmp);
}
printf("%d\n", nt);
free(input);
return 0;
} |
#ifndef <API key>
#include "Utils.hh"
namespace Utils {
using std::string;
using std::lower_bound;
#ifdef UTILS_OS_WINDOWS
string
basename( char const * const path ) {
static char drive[100];
static char dir[1024];
static char fname[256];
static char ext[128];
errno_t e = _splitpath_s(
path,
drive, 100,
dir, 1024,
fname, 256,
ext, 128
);
UTILS_ASSERT0( e == 0, "lapack_wrapper, basename failed!\n" );
return fname;
}
#else
string
basename( char const * const path ) {
if ( path[0] == '\0' ) return string("");
string filename(path);
size_t len = filename.length();
size_t index = filename.find_last_of("/\\");
if ( index == string::npos ) return filename;
if ( index + 1 >= len ) {
--len;
index = filename.substr(0, len).find_last_of("/\\");
if ( len == 0 ) return filename;
if ( index == 0 ) return filename.substr(1, len - 1);
if ( index == string::npos ) return filename.substr(0, len);
return filename.substr(index + 1, len - index - 1);
}
return filename.substr(index + 1, len - index);
}
#endif
template <typename T_int, typename T_real>
void
searchInterval(
T_int npts,
T_real const * const X,
T_real & x,
T_int & lastInterval,
bool closed,
bool can_extend
) {
// check points
T_int n = npts-1;
UTILS_ASSERT(
npts > 1 && lastInterval >= 0 && lastInterval < n,
"In searchInterval( npts={}, X, x={}, lastInterval={}, closed={}, can_extend={})\n"
"npts musrt be >= 2 and lastInterval must be in [0,npts-2]\n",
npts, lastInterval, closed, can_extend
);
// checl range
T_real xl = X[0];
T_real xr = X[n];
if ( closed ) { // put x in range (change also its value)
T_real L = xr-xl;
x -= xl;
x = fmod( x, L );
if ( x < 0 ) x += L;
x += xl;
} else {
UTILS_ASSERT(
can_extend || (x >= xl && x <= xr),
"In searchInterval( npts={}, X, x={}, lastInterval={}, closed={}, can_extend={})\n"
"out of range: [{},{}]\n",
npts, lastInterval, closed, can_extend, xl, xr
);
}
// find the interval of the support of the B-spline
T_real const * XL = X+lastInterval;
if ( XL[1] < x ) { // x on the right
if ( x >= X[n-1] ) {
lastInterval = n-1; // last interval
} else if ( x < XL[2] ) { // x in (XL[1],XL[2])
++lastInterval;
} else { // x >= XL[2] search the right interval
T_real const * XE = X+n;
lastInterval += T_int(lower_bound( XL, XE, x )-XL);
T_real const * XX = X+lastInterval;
if ( x < XX[0] || Utils::isZero(XX[0]-XX[1]) ) --lastInterval;
}
} else if ( x < XL[0] ) { // on the left
if ( x <= X[1] ) { // x in [X[0],X[1]]
lastInterval = 0; // first interval
} else if ( XL[-1] <= x ) { // x in [XL[-1],XL[0])
--lastInterval;
} else {
lastInterval = T_int(lower_bound( X+1, XL, x )-X);
T_real const * XX = X+lastInterval;
if ( x < XX[0] || Utils::isZero(XX[0]-XX[1]) ) --lastInterval;
}
} else {
// x in the interval [ XL[0], XL[1] ] nothing to do
}
// check computed interval
UTILS_ASSERT(
lastInterval >= 0 && lastInterval < n,
"In searchInterval( npts={}, X, x={}, lastInterval={}, closed={}, can_extend={})\n"
"computed lastInterval of range: [{},{}]\n",
npts, lastInterval, closed, can_extend, xl, xr
);
}
extern template void searchInterval(
int32_t npts,
float const * const X,
float & x,
int32_t & lastInterval,
bool closed,
bool can_extend
);
template void searchInterval(
int32_t npts,
double const * const X,
double & x,
int32_t & lastInterval,
bool closed,
bool can_extend
);
template void searchInterval(
int64_t npts,
float const * const X,
float & x,
int64_t & lastInterval,
bool closed,
bool can_extend
);
template void searchInterval(
int64_t npts,
double const * const X,
double & x,
int64_t & lastInterval,
bool closed,
bool can_extend
);
}
#endif
eof: Utils.cc |
<?php
namespace MB\validators;
class Required extends \MB\Validator
{
public function isValid( $value )
{
$status = false;
if( !empty( $value ) )
{
$status = true;
}
return $status;
}
public function getErrorMessage( $fieldName )
{
return __( "%s: значение должно быть указано", $fieldName );
}
public function getClientValidator()
{
return '';
}
} |
class Syncthing < Formula
desc "Open source continuous file synchronization application"
homepage "https://syncthing.net/"
url "https://github.com/syncthing/syncthing.git",
:tag => "v1.3.3",
:revision => "<SHA1-like>"
head "https://github.com/syncthing/syncthing.git"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "<SHA256-like>" => :catalina
sha256 "<SHA256-like>" => :mojave
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :x86_64_linux
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
src = buildpath/"src/github.com/syncthing/syncthing"
src.install buildpath.children
src.cd do
system "./build.sh", "noupgrade"
bin.install "syncthing" |
#include "config.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "vtc.h"
#include "vct.h"
#include "vgz.h"
#include "vnum.h"
#include "vre.h"
#include "vtcp.h"
#define MAX_HDR 50
struct http {
unsigned magic;
#define HTTP_MAGIC 0x2f02169c
int fd;
int *sfd;
int timeout;
struct vtclog *vl;
struct vsb *vsb;
int nrxbuf;
char *rxbuf;
char *rem_ip;
char *rem_port;
int prxbuf;
char *body;
unsigned bodyl;
char bodylen[20];
char chunklen[20];
char *req[MAX_HDR];
char *resp[MAX_HDR];
int gziplevel;
int gzipresidual;
int fatal;
};
#define ONLY_CLIENT(hp, av) \
do { \
if (hp->sfd != NULL) \
vtc_log(hp->vl, 0, \
"\"%s\" only possible in client", av[0]); \
} while (0)
#define ONLY_SERVER(hp, av) \
do { \
if (hp->sfd == NULL) \
vtc_log(hp->vl, 0, \
"\"%s\" only possible in server", av[0]); \
} while (0)
/* XXX: we may want to vary this */
static const char * const nl = "\r\n";
/**********************************************************************
* Generate a synthetic body
*/
static char *
synth_body(const char *len, int rnd)
{
int i, j, k, l;
char *b;
AN(len);
i = strtoul(len, NULL, 0);
assert(i > 0);
b = malloc(i + 1L);
AN(b);
l = k = '!';
for (j = 0; j < i; j++) {
if ((j % 64) == 63) {
b[j] = '\n';
k++;
if (k == '~')
k = '!';
l = k;
} else if (rnd) {
b[j] = (random() % 95) + ' ';
} else {
b[j] = (char)l;
if (++l == '~')
l = '!';
}
}
b[i - 1] = '\n';
b[i] = '\0';
return (b);
}
/**********************************************************************
* Finish and write the vsb to the fd
*/
static void
http_write(const struct http *hp, int lvl, const char *pfx)
{
ssize_t l;
AZ(VSB_finish(hp->vsb));
vtc_dump(hp->vl, lvl, pfx, VSB_data(hp->vsb), VSB_len(hp->vsb));
l = write(hp->fd, VSB_data(hp->vsb), VSB_len(hp->vsb));
if (l != VSB_len(hp->vsb))
vtc_log(hp->vl, hp->fatal, "Write failed: (%zd vs %zd) %s",
l, VSB_len(hp->vsb), strerror(errno));
}
/**********************************************************************
* find header
*/
static char *
http_find_header(char * const *hh, const char *hdr)
{
int n, l;
char *r;
l = strlen(hdr);
for (n = 3; hh[n] != NULL; n++) {
if (strncasecmp(hdr, hh[n], l) || hh[n][l] != ':')
continue;
for (r = hh[n] + l + 1; vct_issp(*r); r++)
continue;
return (r);
}
return (NULL);
}
/**********************************************************************
* count header
*/
static int
http_count_header(char * const *hh, const char *hdr)
{
int n, l, r = 0;
l = strlen(hdr);
for (n = 3; hh[n] != NULL; n++) {
if (strncasecmp(hdr, hh[n], l) || hh[n][l] != ':')
continue;
r++;
}
return (r);
}
/**********************************************************************
* Expect
*/
static const char *
cmd_var_resolve(struct http *hp, char *spec)
{
char **hh, *hdr;
if (!strcmp(spec, "remote.ip"))
return(hp->rem_ip);
if (!strcmp(spec, "remote.port"))
return(hp->rem_port);
if (!strcmp(spec, "req.method"))
return(hp->req[0]);
if (!strcmp(spec, "req.url"))
return(hp->req[1]);
if (!strcmp(spec, "req.proto"))
return(hp->req[2]);
if (!strcmp(spec, "resp.proto"))
return(hp->resp[0]);
if (!strcmp(spec, "resp.status"))
return(hp->resp[1]);
if (!strcmp(spec, "resp.msg"))
return(hp->resp[2]);
if (!strcmp(spec, "resp.chunklen"))
return(hp->chunklen);
if (!strcmp(spec, "req.bodylen"))
return(hp->bodylen);
if (!strcmp(spec, "resp.bodylen"))
return(hp->bodylen);
if (!strcmp(spec, "resp.body"))
return(hp->body != NULL ? hp->body : spec);
if (!memcmp(spec, "req.http.", 9)) {
hh = hp->req;
hdr = spec + 9;
} else if (!memcmp(spec, "resp.http.", 10)) {
hh = hp->resp;
hdr = spec + 10;
} else
return (spec);
hdr = http_find_header(hh, hdr);
return (hdr);
}
static void
cmd_http_expect(CMD_ARGS)
{
struct http *hp;
const char *lhs, *clhs;
char *cmp;
const char *rhs, *crhs;
vre_t *vre;
const char *error;
int erroroffset;
int i, retval = -1;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AZ(strcmp(av[0], "expect"));
av++;
AN(av[0]);
AN(av[1]);
AN(av[2]);
AZ(av[3]);
lhs = cmd_var_resolve(hp, av[0]);
cmp = av[1];
rhs = cmd_var_resolve(hp, av[2]);
clhs = lhs ? lhs : "<undef>";
crhs = rhs ? rhs : "<undef>";
if (!strcmp(cmp, "~") || !strcmp(cmp, "!~")) {
vre = VRE_compile(crhs, 0, &error, &erroroffset);
if (vre == NULL)
vtc_log(hp->vl, 0, "REGEXP error: %s (@%d) (%s)",
error, erroroffset, crhs);
i = VRE_exec(vre, clhs, strlen(clhs), 0, 0, NULL, 0, 0);
retval = (i >= 0 && *cmp == '~') || (i < 0 && *cmp == '!');
VRE_free(&vre);
} else if (!strcmp(cmp, "==")) {
retval = strcmp(clhs, crhs) == 0;
} else if (!strcmp(cmp, "!=")) {
retval = strcmp(clhs, crhs) != 0;
} else if (lhs == NULL || rhs == NULL) {
// fail inequality comparisons if either side is undef'ed
retval = 0;
} else if (!strcmp(cmp, "<")) {
retval = isless(VNUM(lhs), VNUM(rhs));
} else if (!strcmp(cmp, ">")) {
retval = isgreater(VNUM(lhs), VNUM(rhs));
} else if (!strcmp(cmp, "<=")) {
retval = islessequal(VNUM(lhs), VNUM(rhs));
} else if (!strcmp(cmp, ">=")) {
retval = isgreaterequal(VNUM(lhs), VNUM(rhs));
}
if (retval == -1)
vtc_log(hp->vl, 0,
"EXPECT %s (%s) %s %s (%s) test not implemented",
av[0], clhs, av[1], av[2], crhs);
else
vtc_log(hp->vl, retval ? 4 : 0, "EXPECT %s (%s) %s \"%s\" %s",
av[0], clhs, cmp, crhs, retval ? "match" : "failed");
}
/**********************************************************************
* Split a HTTP protocol header
*/
static void
http_splitheader(struct http *hp, int req)
{
char *p, *q, **hh;
int n;
char buf[20];
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
if (req) {
memset(hp->req, 0, sizeof hp->req);
hh = hp->req;
} else {
memset(hp->resp, 0, sizeof hp->resp);
hh = hp->resp;
}
n = 0;
p = hp->rxbuf;
/* REQ/PROTO */
while (vct_islws(*p))
p++;
hh[n++] = p;
while (!vct_islws(*p))
p++;
AZ(vct_iscrlf(p));
*p++ = '\0';
/* URL/STATUS */
while (vct_issp(*p)) /* XXX: H space only */
p++;
AZ(vct_iscrlf(p));
hh[n++] = p;
while (!vct_islws(*p))
p++;
if (vct_iscrlf(p)) {
hh[n++] = NULL;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
} else {
*p++ = '\0';
/* PROTO/MSG */
while (vct_issp(*p)) /* XXX: H space only */
p++;
hh[n++] = p;
while (!vct_iscrlf(p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
assert(n == 3);
while (*p != '\0') {
assert(n < MAX_HDR);
if (vct_iscrlf(p))
break;
hh[n++] = p++;
while (*p != '\0' && !vct_iscrlf(p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
p += vct_skipcrlf(p);
assert(*p == '\0');
for (n = 0; n < 3 || hh[n] != NULL; n++) {
sprintf(buf, "http[%2d] ", n);
vtc_dump(hp->vl, 4, buf, hh[n], -1);
}
}
/**********************************************************************
* Receive another character
*/
static int
http_rxchar(struct http *hp, int n, int eof)
{
int i;
struct pollfd pfd[1];
while (n > 0) {
pfd[0].fd = hp->fd;
pfd[0].events = POLLIN;
pfd[0].revents = 0;
i = poll(pfd, 1, hp->timeout);
if (i < 0 && errno == EINTR)
continue;
if (i == 0)
vtc_log(hp->vl, hp->fatal,
"HTTP rx timeout (fd:%d %u ms)",
hp->fd, hp->timeout);
if (i < 0)
vtc_log(hp->vl, hp->fatal,
"HTTP rx failed (fd:%d poll: %s)",
hp->fd, strerror(errno));
assert(i > 0);
assert(hp->prxbuf + n < hp->nrxbuf);
i = read(hp->fd, hp->rxbuf + hp->prxbuf, n);
if (!(pfd[0].revents & POLLIN))
vtc_log(hp->vl, 4,
"HTTP rx poll (fd:%d revents: %x n=%d, i=%d)",
hp->fd, pfd[0].revents, n, i);
if (i == 0 && eof)
return (i);
if (i == 0)
vtc_log(hp->vl, hp->fatal,
"HTTP rx EOF (fd:%d read: %s)",
hp->fd, strerror(errno));
if (i < 0)
vtc_log(hp->vl, hp->fatal,
"HTTP rx failed (fd:%d read: %s)",
hp->fd, strerror(errno));
hp->prxbuf += i;
hp->rxbuf[hp->prxbuf] = '\0';
n -= i;
}
return (1);
}
static int
http_rxchunk(struct http *hp)
{
char *q;
int l, i;
l = hp->prxbuf;
do
(void)http_rxchar(hp, 1, 0);
while (hp->rxbuf[hp->prxbuf - 1] != '\n');
vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1);
i = strtoul(hp->rxbuf + l, &q, 16);
bprintf(hp->chunklen, "%d", i);
if ((q == hp->rxbuf + l) ||
(*q != '\0' && !vct_islws(*q))) {
vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %td",
*q, q - (hp->rxbuf + l));
}
assert(q != hp->rxbuf + l);
assert(*q == '\0' || vct_islws(*q));
hp->prxbuf = l;
if (i > 0) {
(void)http_rxchar(hp, i, 0);
vtc_dump(hp->vl, 4, "chunk",
hp->rxbuf + l, i);
}
l = hp->prxbuf;
(void)http_rxchar(hp, 2, 0);
if(!vct_iscrlf(hp->rxbuf + l))
vtc_log(hp->vl, hp->fatal,
"Wrong chunk tail[0] = %02x",
hp->rxbuf[l] & 0xff);
if(!vct_iscrlf(hp->rxbuf + l + 1))
vtc_log(hp->vl, hp->fatal,
"Wrong chunk tail[1] = %02x",
hp->rxbuf[l + 1] & 0xff);
hp->prxbuf = l;
hp->rxbuf[l] = '\0';
return (i);
}
/**********************************************************************
* Swallow a HTTP message body
*/
static void
http_swallow_body(struct http *hp, char * const *hh, int body)
{
char *p;
int i, l, ll;
hp->body = hp->rxbuf + hp->prxbuf;
ll = 0;
p = http_find_header(hh, "transfer-encoding");
if (p != NULL && !strcasecmp(p, "chunked")) {
while (http_rxchunk(hp) != 0)
continue;
vtc_dump(hp->vl, 4, "body", hp->body, ll);
ll = hp->rxbuf + hp->prxbuf - hp->body;
hp->bodyl = ll;
sprintf(hp->bodylen, "%d", ll);
return;
}
p = http_find_header(hh, "content-length");
if (p != NULL) {
l = strtoul(p, NULL, 10);
(void)http_rxchar(hp, l, 0);
vtc_dump(hp->vl, 4, "body", hp->body, l);
hp->bodyl = l;
bprintf(hp->bodylen, "%d", l);
return;
}
if (body) {
do {
i = http_rxchar(hp, 1, 1);
ll += i;
} while (i > 0);
vtc_dump(hp->vl, 4, "rxeof", hp->body, ll);
}
hp->bodyl = ll;
sprintf(hp->bodylen, "%d", ll);
}
/**********************************************************************
* Receive a HTTP protocol header
*/
static void
http_rxhdr(struct http *hp)
{
int i;
char *p;
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
hp->prxbuf = 0;
hp->body = NULL;
bprintf(hp->bodylen, "%s", "<undef>");
while (1) {
(void)http_rxchar(hp, 1, 0);
p = hp->rxbuf + hp->prxbuf - 1;
for (i = 0; p > hp->rxbuf; p
if (*p != '\n')
break;
if (p - 1 > hp->rxbuf && p[-1] == '\r')
p
if (++i == 2)
break;
}
if (i == 2)
break;
}
vtc_dump(hp->vl, 4, "rxhdr", hp->rxbuf, -1);
vtc_log(hp->vl, 4, "rxhdrlen = %zd", strlen(hp->rxbuf));
}
/**********************************************************************
* Receive a response
*/
static void
cmd_http_rxresp(CMD_ARGS)
{
struct http *hp;
int has_obj = 1;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_CLIENT(hp, av);
AZ(strcmp(av[0], "rxresp"));
av++;
for(; *av != NULL; av++)
if (!strcmp(*av, "-no_obj"))
has_obj = 0;
else
vtc_log(hp->vl, 0,
"Unknown http rxresp spec: %s\n", *av);
http_rxhdr(hp);
http_splitheader(hp, 0);
if (http_count_header(hp->resp, "Content-Length") > 1)
vtc_log(hp->vl, 0,
"Multiple Content-Length headers.\n");
if (!has_obj)
return;
else if (!strcmp(hp->resp[1], "200"))
http_swallow_body(hp, hp->resp, 1);
else
http_swallow_body(hp, hp->resp, 0);
vtc_log(hp->vl, 4, "bodylen = %s", hp->bodylen);
}
static void
cmd_http_rxresphdrs(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_CLIENT(hp, av);
AZ(strcmp(av[0], "rxresphdrs"));
av++;
for(; *av != NULL; av++)
vtc_log(hp->vl, 0, "Unknown http rxreq spec: %s\n", *av);
http_rxhdr(hp);
http_splitheader(hp, 0);
if (http_count_header(hp->resp, "Content-Length") > 1)
vtc_log(hp->vl, 0,
"Multiple Content-Length headers.\n");
}
/**********************************************************************
* Ungzip rx'ed body
*/
#define TRUST_ME(ptr) ((void*)(uintptr_t)(ptr))
#define OVERHEAD 64L
static void
<API key>(CMD_ARGS)
{
int i;
z_stream vz;
struct http *hp;
char *p;
unsigned l;
(void)av;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
memset(&vz, 0, sizeof vz);
AN(hp->body);
if (hp->body[0] != (char)0x1f || hp->body[1] != (char)0x8b)
vtc_log(hp->vl, hp->fatal,
"Gunzip error: Body lacks gzip magics");
vz.next_in = TRUST_ME(hp->body);
vz.avail_in = hp->bodyl;
l = hp->bodyl * 10;
p = calloc(l, 1);
AN(p);
vz.next_out = TRUST_ME(p);
vz.avail_out = l;
assert(Z_OK == inflateInit2(&vz, 31));
i = inflate(&vz, Z_FINISH);
assert(vz.total_out < l);
hp->bodyl = vz.total_out;
memcpy(hp->body, p, hp->bodyl);
free(p);
vtc_log(hp->vl, 3, "new bodylen %u", hp->bodyl);
vtc_dump(hp->vl, 4, "body", hp->body, hp->bodyl);
bprintf(hp->bodylen, "%u", hp->bodyl);
vtc_log(hp->vl, 4, "startbit = %ju %ju/%ju",
(uintmax_t)vz.start_bit,
(uintmax_t)vz.start_bit >> 3, (uintmax_t)vz.start_bit & 7);
vtc_log(hp->vl, 4, "lastbit = %ju %ju/%ju",
(uintmax_t)vz.last_bit,
(uintmax_t)vz.last_bit >> 3, (uintmax_t)vz.last_bit & 7);
vtc_log(hp->vl, 4, "stopbit = %ju %ju/%ju",
(uintmax_t)vz.stop_bit,
(uintmax_t)vz.stop_bit >> 3, (uintmax_t)vz.stop_bit & 7);
if (i != Z_STREAM_END)
vtc_log(hp->vl, hp->fatal,
"Gunzip error = %d (%s) in:%jd out:%jd",
i, vz.msg, (intmax_t)vz.total_in, (intmax_t)vz.total_out);
assert(Z_OK == inflateEnd(&vz));
hp->body[hp->bodyl] = '\0';
}
/**********************************************************************
* Create a gzip'ed body
*/
static void
gzip_body(const struct http *hp, const char *txt, char **body, int *bodylen)
{
int l, i;
z_stream vz;
memset(&vz, 0, sizeof vz);
l = strlen(txt);
*body = calloc(l + OVERHEAD, 1);
AN(*body);
vz.next_in = TRUST_ME(txt);
vz.avail_in = l;
vz.next_out = TRUST_ME(*body);
vz.avail_out = l + OVERHEAD;
assert(Z_OK == deflateInit2(&vz,
hp->gziplevel, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY));
assert(Z_STREAM_END == deflate(&vz, Z_FINISH));
i = vz.stop_bit & 7;
if (hp->gzipresidual >= 0 && hp->gzipresidual != i)
vtc_log(hp->vl, hp->fatal,
"Wrong gzip residual got %d wanted %d",
i, hp->gzipresidual);
*bodylen = vz.total_out;
vtc_log(hp->vl, 4, "startbit = %ju %ju/%ju",
(uintmax_t)vz.start_bit,
(uintmax_t)vz.start_bit >> 3, (uintmax_t)vz.start_bit & 7);
vtc_log(hp->vl, 4, "lastbit = %ju %ju/%ju",
(uintmax_t)vz.last_bit,
(uintmax_t)vz.last_bit >> 3, (uintmax_t)vz.last_bit & 7);
vtc_log(hp->vl, 4, "stopbit = %ju %ju/%ju",
(uintmax_t)vz.stop_bit,
(uintmax_t)vz.stop_bit >> 3, (uintmax_t)vz.stop_bit & 7);
assert(Z_OK == deflateEnd(&vz));
}
/**********************************************************************
* Handle common arguments of a transmited request or response
*/
static char* const *
http_tx_parse_args(char * const *av, struct vtclog *vl, struct http *hp,
char* body)
{
int bodylen = 0;
char *b, *c;
char *nullbody = NULL;
int nolen = 0;
(void)vl;
nullbody = body;
for(; *av != NULL; av++) {
if (!strcmp(*av, "-nolen")) {
nolen = 1;
} else if (!strcmp(*av, "-hdr")) {
VSB_printf(hp->vsb, "%s%s", av[1], nl);
av++;
} else
break;
}
for(; *av != NULL; av++) {
if (!strcmp(*av, "-body")) {
assert(body == nullbody);
REPLACE(body, av[1]);
AN(body);
av++;
bodylen = strlen(body);
for (b = body; *b != '\0'; b++) {
if(*b == '\\' && b[1] == '0') {
*b = '\0';
for(c = b+1; *c != '\0'; c++) {
*c = c[1];
}
b++;
bodylen
}
}
} else if (!strcmp(*av, "-bodylen")) {
assert(body == nullbody);
body = synth_body(av[1], 0);
bodylen = strlen(body);
av++;
} else if (!strcmp(*av, "-gzipresidual")) {
hp->gzipresidual = strtoul(av[1], NULL, 0);
av++;
} else if (!strcmp(*av, "-gziplevel")) {
hp->gziplevel = strtoul(av[1], NULL, 0);
av++;
} else if (!strcmp(*av, "-gziplen")) {
assert(body == nullbody);
b = synth_body(av[1], 1);
gzip_body(hp, b, &body, &bodylen);
VSB_printf(hp->vsb, "Content-Encoding: gzip%s", nl);
// vtc_hexdump(hp->vl, 4, "gzip", (void*)body, bodylen);
av++;
} else if (!strcmp(*av, "-gzipbody")) {
assert(body == nullbody);
gzip_body(hp, av[1], &body, &bodylen);
VSB_printf(hp->vsb, "Content-Encoding: gzip%s", nl);
// vtc_hexdump(hp->vl, 4, "gzip", (void*)body, bodylen);
av++;
} else
break;
}
if (body != NULL && !nolen)
VSB_printf(hp->vsb, "Content-Length: %d%s", bodylen, nl);
VSB_cat(hp->vsb, nl);
if (body != NULL) {
VSB_bcat(hp->vsb, body, bodylen);
free(body);
}
return (av);
}
/**********************************************************************
* Transmit a response
*/
static void
cmd_http_txresp(CMD_ARGS)
{
struct http *hp;
const char *proto = "HTTP/1.1";
const char *status = "200";
const char *msg = "OK";
char* body = NULL;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_SERVER(hp, av);
AZ(strcmp(av[0], "txresp"));
av++;
VSB_clear(hp->vsb);
for(; *av != NULL; av++) {
if (!strcmp(*av, "-proto")) {
proto = av[1];
av++;
} else if (!strcmp(*av, "-status")) {
status = av[1];
av++;
} else if (!strcmp(*av, "-msg")) {
msg = av[1];
av++;
continue;
} else
break;
}
VSB_printf(hp->vsb, "%s %s %s%s", proto, status, msg, nl);
/* send a "Content-Length: 0" header unless something else happens */
REPLACE(body, "");
av = http_tx_parse_args(av, vl, hp, body);
if (*av != NULL)
vtc_log(hp->vl, 0, "Unknown http txresp spec: %s\n", *av);
http_write(hp, 4, "txresp");
}
/**********************************************************************
* Receive a request
*/
static void
cmd_http_rxreq(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_SERVER(hp, av);
AZ(strcmp(av[0], "rxreq"));
av++;
for(; *av != NULL; av++)
vtc_log(hp->vl, 0, "Unknown http rxreq spec: %s\n", *av);
http_rxhdr(hp);
http_splitheader(hp, 1);
if (http_count_header(hp->req, "Content-Length") > 1)
vtc_log(hp->vl, 0,
"Multiple Content-Length headers.\n");
http_swallow_body(hp, hp->req, 0);
vtc_log(hp->vl, 4, "bodylen = %s", hp->bodylen);
}
static void
cmd_http_rxreqhdrs(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AZ(strcmp(av[0], "rxreqhdrs"));
av++;
for(; *av != NULL; av++)
vtc_log(hp->vl, 0, "Unknown http rxreq spec: %s\n", *av);
http_rxhdr(hp);
http_splitheader(hp, 1);
if (http_count_header(hp->req, "Content-Length") > 1)
vtc_log(hp->vl, 0,
"Multiple Content-Length headers.\n");
}
static void
cmd_http_rxreqbody(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_SERVER(hp, av);
AZ(strcmp(av[0], "rxreqbody"));
av++;
for(; *av != NULL; av++)
vtc_log(hp->vl, 0, "Unknown http rxreq spec: %s\n", *av);
http_swallow_body(hp, hp->req, 0);
vtc_log(hp->vl, 4, "bodylen = %s", hp->bodylen);
}
static void
cmd_http_rxrespbody(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_CLIENT(hp, av);
AZ(strcmp(av[0], "rxrespbody"));
av++;
for(; *av != NULL; av++)
vtc_log(hp->vl, 0, "Unknown http rxreq spec: %s\n", *av);
http_swallow_body(hp, hp->resp, 0);
vtc_log(hp->vl, 4, "bodylen = %s", hp->bodylen);
}
static void
cmd_http_rxchunk(CMD_ARGS)
{
struct http *hp;
int ll, i;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_CLIENT(hp, av);
i = http_rxchunk(hp);
if (i == 0) {
ll = hp->rxbuf + hp->prxbuf - hp->body;
hp->bodyl = ll;
sprintf(hp->bodylen, "%d", ll);
vtc_log(hp->vl, 4, "bodylen = %s", hp->bodylen);
}
}
/**********************************************************************
* Transmit a request
*/
static void
cmd_http_txreq(CMD_ARGS)
{
struct http *hp;
const char *req = "GET";
const char *url = "/";
const char *proto = "HTTP/1.1";
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
ONLY_CLIENT(hp, av);
AZ(strcmp(av[0], "txreq"));
av++;
VSB_clear(hp->vsb);
for(; *av != NULL; av++) {
if (!strcmp(*av, "-url")) {
url = av[1];
av++;
} else if (!strcmp(*av, "-proto")) {
proto = av[1];
av++;
} else if (!strcmp(*av, "-req")) {
req = av[1];
av++;
} else
break;
}
VSB_printf(hp->vsb, "%s %s %s%s", req, url, proto, nl);
av = http_tx_parse_args(av, vl, hp, NULL);
if (*av != NULL)
vtc_log(hp->vl, 0, "Unknown http txreq spec: %s\n", *av);
http_write(hp, 4, "txreq");
}
/**********************************************************************
* Receive N characters
*/
static void
cmd_http_recv(CMD_ARGS)
{
struct http *hp;
int i, n;
char u[32];
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
n = strtoul(av[1], NULL, 0);
while (n > 0) {
i = read(hp->fd, u, n > 32 ? 32 : n);
if (i > 0)
vtc_dump(hp->vl, 4, "recv", u, i);
else
vtc_log(hp->vl, hp->fatal, "recv() got %d (%s)", i,
strerror(errno));
n -= i;
}
}
/**********************************************************************
* Send a string
*/
static void
cmd_http_send(CMD_ARGS)
{
struct http *hp;
int i;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
vtc_dump(hp->vl, 4, "send", av[1], -1);
i = write(hp->fd, av[1], strlen(av[1]));
if (i != strlen(av[1]))
vtc_log(hp->vl, hp->fatal, "Write error in http_send(): %s",
strerror(errno));
}
/**********************************************************************
* Send a string many times
*/
static void
cmd_http_send_n(CMD_ARGS)
{
struct http *hp;
int i, n, l;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AN(av[2]);
AZ(av[3]);
n = strtoul(av[1], NULL, 0);
vtc_dump(hp->vl, 4, "send_n", av[2], -1);
l = strlen(av[2]);
while (n
i = write(hp->fd, av[2], l);
if (i != l)
vtc_log(hp->vl, hp->fatal,
"Write error in http_send(): %s",
strerror(errno));
}
}
/**********************************************************************
* Send an OOB urgent message
*/
static void
<API key>(CMD_ARGS)
{
struct http *hp;
int i;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
vtc_dump(hp->vl, 4, "send_urgent", av[1], -1);
i = send(hp->fd, av[1], strlen(av[1]), MSG_OOB);
if (i != strlen(av[1]))
vtc_log(hp->vl, hp->fatal,
"Write error in http_send_urgent(): %s", strerror(errno));
}
/**********************************************************************
* Send a hex string
*/
static void
cmd_http_sendhex(CMD_ARGS)
{
struct http *hp;
char buf[3], *q;
uint8_t *p;
int i, j, l;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
l = strlen(av[1]) / 2;
p = malloc(l);
AN(p);
q = av[1];
for (i = 0; i < l; i++) {
while (vct_issp(*q))
q++;
if (*q == '\0')
break;
memcpy(buf, q, 2);
q += 2;
buf[2] = '\0';
if (!vct_ishex(buf[0]) || !vct_ishex(buf[1]))
vtc_log(hp->vl, 0, "Illegal Hex char \"%c%c\"",
buf[0], buf[1]);
p[i] = (uint8_t)strtoul(buf, NULL, 16);
}
vtc_hexdump(hp->vl, 4, "sendhex", (void*)p, i);
j = write(hp->fd, p, i);
assert(j == i);
free(p);
}
/**********************************************************************
* Send a string as chunked encoding
*/
static void
cmd_http_chunked(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
VSB_clear(hp->vsb);
VSB_printf(hp->vsb, "%jx%s%s%s",
(uintmax_t)strlen(av[1]), nl, av[1], nl);
http_write(hp, 4, "chunked");
}
static void
cmd_http_chunkedlen(CMD_ARGS)
{
unsigned len;
unsigned u, v;
char buf[16384];
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
VSB_clear(hp->vsb);
len = atoi(av[1]);
if (len == 0) {
VSB_printf(hp->vsb, "0%s%s", nl, nl);
} else {
for (u = 0; u < sizeof buf; u++)
buf[u] = (u & 7) + '0';
VSB_printf(hp->vsb, "%x%s", len, nl);
for (u = 0; u < len; u += v) {
v = len - u;
if (v > sizeof buf)
v = sizeof buf;
VSB_bcat(hp->vsb, buf, v);
}
VSB_printf(hp->vsb, "%s", nl);
}
http_write(hp, 4, "chunked");
}
/**********************************************************************
* set the timeout
*/
static void
cmd_http_timeout(CMD_ARGS)
{
struct http *hp;
double d;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AZ(av[2]);
d = VNUM(av[1]);
if (isnan(d))
vtc_log(vl, 0, "timeout is not a number (%s)", av[1]);
hp->timeout = (int)(d * 1000.0);
}
/**********************************************************************
* expect other end to close (server only)
*/
static void
<API key>(CMD_ARGS)
{
struct http *hp;
struct pollfd fds[1];
char c;
int i;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AZ(av[1]);
vtc_log(vl, 4, "Expecting close (fd = %d)", hp->fd);
while (1) {
fds[0].fd = hp->fd;
fds[0].events = POLLIN | POLLERR;
fds[0].revents = 0;
i = poll(fds, 1, hp->timeout);
if (i < 0 && errno == EINTR)
continue;
if (i == 0)
vtc_log(vl, hp->fatal, "Expected close: timeout");
if (i != 1 || !(fds[0].revents & (POLLIN|POLLERR)))
vtc_log(vl, hp->fatal,
"Expected close: poll = %d, revents = 0x%x",
i, fds[0].revents);
i = read(hp->fd, &c, 1);
if (VTCP_Check(i))
break;
if (i == 1 && vct_islws(c))
continue;
vtc_log(vl, hp->fatal,
"Expecting close: read = %d, c = 0x%02x", i, c);
}
vtc_log(vl, 4, "fd=%d EOF, as expected", hp->fd);
}
/**********************************************************************
* close a new connection (server only)
*/
static void
cmd_http_close(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AZ(av[1]);
assert(hp->sfd != NULL);
assert(*hp->sfd >= 0);
VTCP_close(&hp->fd);
vtc_log(vl, 4, "Closed");
}
/**********************************************************************
* close and accept a new connection (server only)
*/
static void
cmd_http_accept(CMD_ARGS)
{
struct http *hp;
(void)cmd;
(void)vl;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AZ(av[1]);
assert(hp->sfd != NULL);
assert(*hp->sfd >= 0);
if (hp->fd >= 0)
VTCP_close(&hp->fd);
vtc_log(vl, 4, "Accepting");
hp->fd = accept(*hp->sfd, NULL, NULL);
if (hp->fd < 0)
vtc_log(vl, hp->fatal, "Accepted failed: %s", strerror(errno));
vtc_log(vl, 3, "Accepted socket fd is %d", hp->fd);
}
/**********************************************************************
* loop operator
*/
static void
cmd_http_loop(CMD_ARGS)
{
struct http *hp;
unsigned n, m;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AN(av[1]);
AN(av[2]);
AZ(av[3]);
n = strtoul(av[1], NULL, 0);
for (m = 1 ; m <= n; m++) {
vtc_log(vl, 4, "Loop #%u", m);
parse_string(av[2], cmd, hp, vl);
}
}
/**********************************************************************
* Control fatality
*/
static void
cmd_http_fatal(CMD_ARGS)
{
struct http *hp;
CAST_OBJ_NOTNULL(hp, priv, HTTP_MAGIC);
AZ(av[1]);
if (!strcmp(av[0], "fatal"))
hp->fatal = 0;
else if (!strcmp(av[0], "non-fatal"))
hp->fatal = -1;
else {
vtc_log(vl, 0, "XXX: fatal %s", cmd->name);
}
}
/**********************************************************************
* Execute HTTP specifications
*/
static const struct cmds http_cmds[] = {
{ "timeout", cmd_http_timeout },
{ "txreq", cmd_http_txreq },
{ "rxreq", cmd_http_rxreq },
{ "rxreqhdrs", cmd_http_rxreqhdrs },
{ "rxreqbody", cmd_http_rxreqbody },
{ "rxchunk", cmd_http_rxchunk },
{ "txresp", cmd_http_txresp },
{ "rxresp", cmd_http_rxresp },
{ "rxresphdrs", cmd_http_rxresphdrs },
{ "rxrespbody", cmd_http_rxrespbody },
{ "gunzip", <API key> },
{ "expect", cmd_http_expect },
{ "recv", cmd_http_recv },
{ "send", cmd_http_send },
{ "send_n", cmd_http_send_n },
{ "send_urgent", <API key> },
{ "sendhex", cmd_http_sendhex },
{ "chunked", cmd_http_chunked },
{ "chunkedlen", cmd_http_chunkedlen },
{ "delay", cmd_delay },
{ "sema", cmd_sema },
{ "expect_close", <API key> },
{ "close", cmd_http_close },
{ "accept", cmd_http_accept },
{ "loop", cmd_http_loop },
{ "fatal", cmd_http_fatal },
{ "non-fatal", cmd_http_fatal },
{ NULL, NULL }
};
int
http_process(struct vtclog *vl, const char *spec, int sock, int *sfd)
{
struct http *hp;
int retval;
(void)sfd;
ALLOC_OBJ(hp, HTTP_MAGIC);
AN(hp);
hp->fd = sock;
hp->timeout = vtc_maxdur * 1000 / 2;
hp->nrxbuf = 2048*1024;
hp->rxbuf = malloc(hp->nrxbuf); /* XXX */
AN(hp->rxbuf);
hp->vsb = VSB_new_auto();
AN(hp->vsb);
hp->sfd = sfd;
hp->rem_ip = malloc(VTCP_ADDRBUFSIZE);
AN(hp->rem_ip);
hp->rem_port = malloc(VTCP_PORTBUFSIZE);
AN(hp->rem_port);
hp->vl = vl;
hp->gziplevel = 0;
hp->gzipresidual = -1;
VTCP_hisname(sock, hp->rem_ip, VTCP_ADDRBUFSIZE, hp->rem_port, VTCP_PORTBUFSIZE);
parse_string(spec, http_cmds, hp, vl);
retval = hp->fd;
VSB_delete(hp->vsb);
free(hp->rxbuf);
free(hp->rem_ip);
free(hp->rem_port);
free(hp);
return (retval);
}
/**********************************************************************
* Magic test routine
*
* This function brute-forces some short strings through gzip(9) to
* find candidates for all possible 8 bit positions of the stopbit.
*
* Here is some good short output strings:
*
* 0 184 <e04c8d0fd604c>
* 1 257 <<API key>>
* 2 106 <10>
* 3 163 <a5e2e2e1c2e2>
* 4 180 <71c5d18ec5d5d1>
* 5 189 <39886d28a6d2988>
* 6 118 <80000>
* 7 151 <386811868>
*
*/
#if 0
void xxx(void);
void
xxx(void)
{
z_stream vz;
int n;
char ibuf[200];
char obuf[200];
int fl[8];
int i, j;
for (n = 0; n < 8; n++)
fl[n] = 9999;
memset(&vz, 0, sizeof vz);
for(n = 0; n < 999999999; n++) {
*ibuf = 0;
for (j = 0; j < 7; j++) {
sprintf(strchr(ibuf, 0), "%x",
(unsigned)random() & 0xffff);
vz.next_in = TRUST_ME(ibuf);
vz.avail_in = strlen(ibuf);
vz.next_out = TRUST_ME(obuf);
vz.avail_out = sizeof obuf;
assert(Z_OK == deflateInit2(&vz,
9, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY));
assert(Z_STREAM_END == deflate(&vz, Z_FINISH));
i = vz.stop_bit & 7;
if (fl[i] > strlen(ibuf)) {
printf("%d %jd <%s>\n", i, vz.stop_bit, ibuf);
fl[i] = strlen(ibuf);
}
assert(Z_OK == deflateEnd(&vz));
}
}
printf("FOO\n");
}
#endif |
chrome.extension.sendMessage({}, function(response) {
var <API key> = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(<API key>);
var seconds10 = document.getElementById("thebutton-s-10s");
seconds10.addEventListener("DOMSubtreeModified", function(){
checkRelock();
}, false);
var seconds = document.getElementById("thebutton-s-1s");
seconds.addEventListener("DOMSubtreeModified", function(){
checkRelock();
}, false);
}
}, 10);
});
function checkRelock(){
var seconds10 = document.getElementById("thebutton-s-10s");
var seconds = document.getElementById("thebutton-s-1s");
var value = parseInt(seconds10.innerText) * 10 + parseInt(seconds.innerText);
if (value >= 59)
{
var containers = document.<API key>("thebutton-container");
var lock = containers[0];
if(lock.classList.contains("active")){
lock.classList.remove("unlocked");
lock.classList.add("locked");
}
}
} |
// Package al provides a golang audio library based on OpenAL. Official OpenAL
// documentation can be found online. Just prepend "AL_" to the function
// or constants found in this package.
// These bindings were based on the OpenAL header files found at:
// Refer to the orginal header files and official OpenAL documentation for more information.
package al
// #cgo darwin LDFLAGS: -framework OpenAL
// #cgo linux LDFLAGS: -lopenal -ldl
// #cgo windows LDFLAGS: -lOpenAL32
// #include <stdlib.h>
// #if defined(__APPLE__)
// #include <dlfcn.h>
// #elif defined(_WIN32)
// #define WIN32_LEAN_AND_MEAN 1
// #include <windows.h>
// #else
// #include <dlfcn.h>
// #endif
// #ifdef _WIN32
// static HMODULE hmod = NULL;
// #elif !defined __APPLE__
// static void* plib = NULL;
// #endif
// // Helps bind function pointers to c functions.
// static void* bindMethod(const char* name) {
// #ifdef __APPLE__
// return dlsym(RTLD_DEFAULT, name);
// #elif _WIN32
// if(hmod == NULL) {
// hmod = LoadLibraryA("OpenAL32.dll");
// return GetProcAddress(hmod, (LPCSTR)name);
// #else
// if(plib == NULL) {
// plib = dlopen("libopenal.so", RTLD_LAZY);
// return dlsym(plib, name);
// #endif
// #if defined(_WIN32)
// #define AL_APIENTRY __cdecl
// #define ALC_APIENTRY __cdecl
// #else
// #define AL_APIENTRY
// #define ALC_APIENTRY
// #endif
// // AL/al.h typedefs
// typedef char ALboolean;
// typedef char ALchar;
// typedef signed char ALbyte;
// typedef unsigned char ALubyte;
// typedef unsigned short ALushort;
// typedef int ALint;
// typedef unsigned int ALuint;
// typedef int ALsizei;
// typedef int ALenum;
// typedef float ALfloat;
// typedef double ALdouble;
// typedef void ALvoid;
// #ifndef AL_API
// #define AL_API extern
// #endif
// // AL/alc.h typedefs
// typedef struct ALCdevice_struct ALCdevice;
// typedef struct ALCcontext_struct ALCcontext;
// typedef char ALCboolean;
// typedef char ALCchar;
// typedef signed char ALCbyte;
// typedef unsigned char ALCubyte;
// typedef unsigned short ALCushort;
// typedef int ALCint;
// typedef unsigned int ALCuint;
// typedef int ALCsizei;
// typedef int ALCenum;
// typedef void ALCvoid;
// #ifndef ALC_API
// #define ALC_API extern
// #endif
// // AL/al.h pointers to functions bound to the OS specific library.
// void (AL_APIENTRY *pfn_alEnable)( ALenum capability );
// void (AL_APIENTRY *pfn_alDisable)( ALenum capability );
// ALboolean (AL_APIENTRY *pfn_alIsEnabled)( ALenum capability );
// const ALchar* (AL_APIENTRY *pfn_alGetString)( ALenum param );
// void (AL_APIENTRY *pfn_alGetBooleanv)( ALenum param, ALboolean* data );
// void (AL_APIENTRY *pfn_alGetIntegerv)( ALenum param, ALint* data );
// void (AL_APIENTRY *pfn_alGetFloatv)( ALenum param, ALfloat* data );
// void (AL_APIENTRY *pfn_alGetDoublev)( ALenum param, ALdouble* data );
// ALboolean (AL_APIENTRY *pfn_alGetBoolean)( ALenum param );
// ALint (AL_APIENTRY *pfn_alGetInteger)( ALenum param );
// ALfloat (AL_APIENTRY *pfn_alGetFloat)( ALenum param );
// ALdouble (AL_APIENTRY *pfn_alGetDouble)( ALenum param );
// ALenum (AL_APIENTRY *pfn_alGetError)( void );
// ALboolean (AL_APIENTRY *<API key>)(const ALchar* extname );
// void* (AL_APIENTRY *<API key>)( const ALchar* fname );
// ALenum (AL_APIENTRY *pfn_alGetEnumValue)( const ALchar* ename );
// void (AL_APIENTRY *pfn_alListenerf)( ALenum param, ALfloat value );
// void (AL_APIENTRY *pfn_alListener3f)( ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
// void (AL_APIENTRY *pfn_alListenerfv)( ALenum param, const ALfloat* values );
// void (AL_APIENTRY *pfn_alListeneri)( ALenum param, ALint value );
// void (AL_APIENTRY *pfn_alListener3i)( ALenum param, ALint value1, ALint value2, ALint value3 );
// void (AL_APIENTRY *pfn_alListeneriv)( ALenum param, const ALint* values );
// void (AL_APIENTRY *pfn_alGetListenerf)( ALenum param, ALfloat* value );
// void (AL_APIENTRY *pfn_alGetListener3f)( ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3 );
// void (AL_APIENTRY *pfn_alGetListenerfv)( ALenum param, ALfloat* values );
// void (AL_APIENTRY *pfn_alGetListeneri)( ALenum param, ALint* value );
// void (AL_APIENTRY *pfn_alGetListener3i)( ALenum param, ALint *value1, ALint *value2, ALint *value3 );
// void (AL_APIENTRY *pfn_alGetListeneriv)( ALenum param, ALint* values );
// void (AL_APIENTRY *pfn_alGenSources)( ALsizei n, ALuint* sources );
// void (AL_APIENTRY *pfn_alDeleteSources)( ALsizei n, const ALuint* sources );
// ALboolean (AL_APIENTRY *pfn_alIsSource)( ALuint sid );
// void (AL_APIENTRY *pfn_alSourcef)( ALuint sid, ALenum param, ALfloat value);
// void (AL_APIENTRY *pfn_alSource3f)( ALuint sid, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
// void (AL_APIENTRY *pfn_alSourcefv)( ALuint sid, ALenum param, const ALfloat* values );
// void (AL_APIENTRY *pfn_alSourcei)( ALuint sid, ALenum param, ALint value);
// void (AL_APIENTRY *pfn_alSource3i)( ALuint sid, ALenum param, ALint value1, ALint value2, ALint value3 );
// void (AL_APIENTRY *pfn_alSourceiv)( ALuint sid, ALenum param, const ALint* values );
// void (AL_APIENTRY *pfn_alGetSourcef)( ALuint sid, ALenum param, ALfloat* value );
// void (AL_APIENTRY *pfn_alGetSource3f)( ALuint sid, ALenum param, ALfloat* value1, ALfloat* value2, ALfloat* value3);
// void (AL_APIENTRY *pfn_alGetSourcefv)( ALuint sid, ALenum param, ALfloat* values );
// void (AL_APIENTRY *pfn_alGetSourcei)( ALuint sid, ALenum param, ALint* value );
// void (AL_APIENTRY *pfn_alGetSource3i)( ALuint sid, ALenum param, ALint* value1, ALint* value2, ALint* value3);
// void (AL_APIENTRY *pfn_alGetSourceiv)( ALuint sid, ALenum param, ALint* values );
// void (AL_APIENTRY *pfn_alSourcePlayv)( ALsizei ns, const ALuint *sids );
// void (AL_APIENTRY *pfn_alSourceStopv)( ALsizei ns, const ALuint *sids );
// void (AL_APIENTRY *pfn_alSourceRewindv)( ALsizei ns, const ALuint *sids );
// void (AL_APIENTRY *pfn_alSourcePausev)( ALsizei ns, const ALuint *sids );
// void (AL_APIENTRY *pfn_alSourcePlay)( ALuint sid );
// void (AL_APIENTRY *pfn_alSourceStop)( ALuint sid );
// void (AL_APIENTRY *pfn_alSourceRewind)( ALuint sid );
// void (AL_APIENTRY *pfn_alSourcePause)( ALuint sid );
// void (AL_APIENTRY *<API key>)(ALuint sid, ALsizei numEntries, const ALuint *bids );
// void (AL_APIENTRY *<API key>)(ALuint sid, ALsizei numEntries, ALuint *bids );
// void (AL_APIENTRY *pfn_alGenBuffers)( ALsizei n, ALuint* buffers );
// void (AL_APIENTRY *pfn_alDeleteBuffers)( ALsizei n, const ALuint* buffers );
// ALboolean (AL_APIENTRY *pfn_alIsBuffer)( ALuint bid );
// void (AL_APIENTRY *pfn_alBufferData)( ALuint bid, ALenum format, const ALvoid* data, ALsizei size, ALsizei freq );
// void (AL_APIENTRY *pfn_alBufferf)( ALuint bid, ALenum param, ALfloat value);
// void (AL_APIENTRY *pfn_alBuffer3f)( ALuint bid, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3 );
// void (AL_APIENTRY *pfn_alBufferfv)( ALuint bid, ALenum param, const ALfloat* values );
// void (AL_APIENTRY *pfn_alBufferi)( ALuint bid, ALenum param, ALint value);
// void (AL_APIENTRY *pfn_alBuffer3i)( ALuint bid, ALenum param, ALint value1, ALint value2, ALint value3 );
// void (AL_APIENTRY *pfn_alBufferiv)( ALuint bid, ALenum param, const ALint* values );
// void (AL_APIENTRY *pfn_alGetBufferf)( ALuint bid, ALenum param, ALfloat* value );
// void (AL_APIENTRY *pfn_alGetBuffer3f)( ALuint bid, ALenum param, ALfloat* value1, ALfloat* value2, ALfloat* value3);
// void (AL_APIENTRY *pfn_alGetBufferfv)( ALuint bid, ALenum param, ALfloat* values );
// void (AL_APIENTRY *pfn_alGetBufferi)( ALuint bid, ALenum param, ALint* value );
// void (AL_APIENTRY *pfn_alGetBuffer3i)( ALuint bid, ALenum param, ALint* value1, ALint* value2, ALint* value3);
// void (AL_APIENTRY *pfn_alGetBufferiv)( ALuint bid, ALenum param, ALint* values );
// void (AL_APIENTRY *pfn_alDopplerFactor)( ALfloat value );
// void (AL_APIENTRY *<API key>)( ALfloat value );
// void (AL_APIENTRY *pfn_alSpeedOfSound)( ALfloat value );
// void (AL_APIENTRY *pfn_alDistanceModel)( ALenum distanceModel );
// // AL/al.h wrappers for the go bindings.
// AL_API void AL_APIENTRY wrap_alEnable( int capability ) { (*pfn_alEnable)( capability ); }
// AL_API void AL_APIENTRY wrap_alDisable( int capability ) { (*pfn_alDisable)( capability ); }
// AL_API unsigned int AL_APIENTRY wrap_alIsEnabled( int capability ) { return (*pfn_alIsEnabled)( capability ); }
// AL_API const char* AL_APIENTRY wrap_alGetString( int param ) { return (*pfn_alGetString)( param ); }
// AL_API void AL_APIENTRY wrap_alGetBooleanv( int param, char* data ) { (*pfn_alGetBooleanv)( param, data ); }
// AL_API void AL_APIENTRY wrap_alGetIntegerv( int param, int* data ) { (*pfn_alGetIntegerv)( param, data ); }
// AL_API void AL_APIENTRY wrap_alGetFloatv( int param, float* data ) { (*pfn_alGetFloatv)( param, data ); }
// AL_API void AL_APIENTRY wrap_alGetDoublev( int param, double* data ) { (*pfn_alGetDoublev)( param, data );}
// AL_API ALboolean AL_APIENTRY wrap_alGetBoolean( int param ) { return (*pfn_alGetBoolean)( param ); }
// AL_API ALint AL_APIENTRY wrap_alGetInteger( int param ) { return (*pfn_alGetInteger)( param ); }
// AL_API ALfloat AL_APIENTRY wrap_alGetFloat( int param ) { return (*pfn_alGetFloat)( param ); }
// AL_API ALdouble AL_APIENTRY wrap_alGetDouble( int param ) { return (*pfn_alGetDouble)( param ); }
// AL_API ALenum AL_APIENTRY wrap_alGetError( void ) { return (*pfn_alGetError)(); }
// AL_API ALboolean AL_APIENTRY <API key>( const char* extname ) { return (*<API key>)( extname ); }
// AL_API void* AL_APIENTRY <API key>( const char* fname ) { return (*<API key>)( fname ); }
// AL_API ALenum AL_APIENTRY wrap_alGetEnumValue( const char* ename ) { return (*pfn_alGetEnumValue)( ename ); }
// AL_API void AL_APIENTRY wrap_alListenerf( int param, float value ) { (*pfn_alListenerf)( param, value ); }
// AL_API void AL_APIENTRY wrap_alListener3f( int param, float value1, float value2, float value3 ) { (*pfn_alListener3f)( param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY wrap_alListenerfv( int param, const float* values ) { (*pfn_alListenerfv)( param, values ); }
// AL_API void AL_APIENTRY wrap_alListeneri( int param, int value ) { (*pfn_alListeneri)( param, value ); }
// AL_API void AL_APIENTRY wrap_alListener3i( int param, int value1, int value2, int value3 ) { (*pfn_alListener3i)( param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY wrap_alListeneriv( int param, const int* values ) { (*pfn_alListeneriv)( param, values ); }
// AL_API void AL_APIENTRY wrap_alGetListenerf( int param, float* value ) { (*pfn_alGetListenerf)( param, value ); }
// AL_API void AL_APIENTRY <API key>( int param, float *value1, float *value2, float *value3 ) { (*pfn_alGetListener3f)( param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY <API key>( int param, float* values ) { (*pfn_alGetListenerfv)( param, values ); }
// AL_API void AL_APIENTRY wrap_alGetListeneri( int param, int* value ) { (*pfn_alGetListeneri)( param, value ); }
// AL_API void AL_APIENTRY <API key>( int param, int *value1, int *value2, int *value3 ) { (*pfn_alGetListener3i)( param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY <API key>( int param, int* values ) { (*pfn_alGetListeneriv)( param, values ); }
// AL_API void AL_APIENTRY wrap_alGenSources( int n, unsigned int* sources ) { (*pfn_alGenSources)( n, sources ); }
// AL_API void AL_APIENTRY <API key>( int n, const unsigned int* sources ) { (*pfn_alDeleteSources)( n, sources ); }
// AL_API ALboolean AL_APIENTRY wrap_alIsSource( unsigned int sid ) { return (*pfn_alIsSource)( sid ); }
// AL_API void AL_APIENTRY wrap_alSourcef( unsigned int sid, int param, float value ) { (*pfn_alSourcef)( sid, param, value ); }
// AL_API void AL_APIENTRY wrap_alSource3f( unsigned int sid, int param, float value1, float value2, float value3 ) { (*pfn_alSource3f)( sid, param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY wrap_alSourcefv( unsigned int sid, int param, const float* values ) { (*pfn_alSourcefv)( sid, param, values ); }
// AL_API void AL_APIENTRY wrap_alSourcei( unsigned int sid, int param, int value ) { (*pfn_alSourcei)( sid, param, value ); }
// AL_API void AL_APIENTRY wrap_alSource3i( unsigned int sid, int param, int value1, int value2, int value3 ) { (*pfn_alSource3i)( sid, param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY wrap_alSourceiv( unsigned int sid, int param, const int* values ) { (*pfn_alSourceiv)( sid, param, values ); }
// AL_API void AL_APIENTRY wrap_alGetSourcef( unsigned int sid, int param, float* value ) { (*pfn_alGetSourcef)( sid, param, value ); }
// AL_API void AL_APIENTRY wrap_alGetSource3f( unsigned int sid, int param, float* value1, float* value2, float* value3) { (*pfn_alGetSource3f)( sid, param, value1, value2, value3); }
// AL_API void AL_APIENTRY wrap_alGetSourcefv( unsigned int sid, int param, float* values ) { (*pfn_alGetSourcefv)( sid, param, values ); }
// AL_API void AL_APIENTRY wrap_alGetSourcei( unsigned int sid, int param, int* value ) { (*pfn_alGetSourcei)( sid, param, value ); }
// AL_API void AL_APIENTRY wrap_alGetSource3i( unsigned int sid, int param, int* value1, int* value2, int* value3) { (*pfn_alGetSource3i)( sid, param, value1, value2, value3); }
// AL_API void AL_APIENTRY wrap_alGetSourceiv( unsigned int sid, int param, int* values ) { (*pfn_alGetSourceiv)( sid, param, values ); }
// AL_API void AL_APIENTRY wrap_alSourcePlayv( int ns, const unsigned int *sids ) { (*pfn_alSourcePlayv)( ns, sids ); }
// AL_API void AL_APIENTRY wrap_alSourceStopv( int ns, const unsigned int *sids ) { (*pfn_alSourceStopv)( ns, sids ); }
// AL_API void AL_APIENTRY <API key>( int ns, const unsigned int *sids ) { (*pfn_alSourceRewindv)( ns, sids ); }
// AL_API void AL_APIENTRY wrap_alSourcePausev( int ns, const unsigned int *sids ) { (*pfn_alSourcePausev)( ns, sids ); }
// AL_API void AL_APIENTRY wrap_alSourcePlay( unsigned int sid ) { (*pfn_alSourcePlay)( sid ); }
// AL_API void AL_APIENTRY wrap_alSourceStop( unsigned int sid ) { (*pfn_alSourceStop)( sid ); }
// AL_API void AL_APIENTRY wrap_alSourceRewind( unsigned int sid ) { (*pfn_alSourceRewind)( sid ); }
// AL_API void AL_APIENTRY wrap_alSourcePause( unsigned int sid ) { (*pfn_alSourcePause)( sid ); }
// AL_API void AL_APIENTRY <API key>( unsigned int sid, int numEntries, const unsigned int *bids ) { (*<API key>)( sid, numEntries, bids ); }
// AL_API void AL_APIENTRY <API key>( unsigned int sid, int numEntries, unsigned int *bids ) {(*<API key>)( sid, numEntries, bids ); }
// AL_API void AL_APIENTRY wrap_alGenBuffers( int n, unsigned int* buffers ) { (*pfn_alGenBuffers)( n, buffers ); }
// AL_API void AL_APIENTRY <API key>( int n, const unsigned int* buffers ) { (*pfn_alDeleteBuffers)( n, buffers ); }
// AL_API ALboolean AL_APIENTRY wrap_alIsBuffer( unsigned int bid ) { return (*pfn_alIsBuffer)( bid ); }
// AL_API void AL_APIENTRY wrap_alBufferData( unsigned int bid, int format, const ALvoid* data, int size, int freq ) { (*pfn_alBufferData)( bid, format, data, size, freq ); }
// AL_API void AL_APIENTRY wrap_alBufferf( unsigned int bid, int param, float value ) { (*pfn_alBufferf)( bid, param, value ); }
// AL_API void AL_APIENTRY wrap_alBuffer3f( unsigned int bid, int param, float value1, float value2, float value3 ) { (*pfn_alBuffer3f)( bid, param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY wrap_alBufferfv( unsigned int bid, int param, const float* values ) { (*pfn_alBufferfv)( bid, param, values ); }
// AL_API void AL_APIENTRY wrap_alBufferi( unsigned int bid, int param, int value ) { (*pfn_alBufferi)( bid, param, value ); }
// AL_API void AL_APIENTRY wrap_alBuffer3i( unsigned int bid, int param, int value1, int value2, int value3 ) { (*pfn_alBuffer3i)( bid, param, value1, value2, value3 ); }
// AL_API void AL_APIENTRY wrap_alBufferiv( unsigned int bid, int param, const int* values ) { (*pfn_alBufferiv)( bid, param, values ); }
// AL_API void AL_APIENTRY wrap_alGetBufferf( unsigned int bid, int param, float* value ) { (*pfn_alGetBufferf)( bid, param, value ); }
// AL_API void AL_APIENTRY wrap_alGetBuffer3f( unsigned int bid, int param, float* value1, float* value2, float* value3) { (*pfn_alGetBuffer3f)( bid, param, value1, value2, value3); }
// AL_API void AL_APIENTRY wrap_alGetBufferfv( unsigned int bid, int param, float* values ) { (*pfn_alGetBufferfv)( bid, param, values ); }
// AL_API void AL_APIENTRY wrap_alGetBufferi( unsigned int bid, int param, int* value ) { (*pfn_alGetBufferi)( bid, param, value ); }
// AL_API void AL_APIENTRY wrap_alGetBuffer3i( unsigned int bid, int param, int* value1, int* value2, int* value3) { (*pfn_alGetBuffer3i)( bid, param, value1, value2, value3); }
// AL_API void AL_APIENTRY wrap_alGetBufferiv( unsigned int bid, int param, int* values ) { (*pfn_alGetBufferiv)( bid, param, values ); }
// AL_API void AL_APIENTRY <API key>( float value ) { (*pfn_alDopplerFactor)( value ); }
// AL_API void AL_APIENTRY <API key>( float value ) { (*<API key>)( value ); }
// AL_API void AL_APIENTRY wrap_alSpeedOfSound( float value ) { (*pfn_alSpeedOfSound)( value ); }
// AL_API void AL_APIENTRY <API key>( int distanceModel ) { (*pfn_alDistanceModel)( distanceModel ); }
// // AL/alc.h pointers to functions bound to the OS specific library.
// ALCcontext * (ALC_APIENTRY *<API key>) (ALCdevice *device, const ALCint *attrlist);
// ALCboolean (ALC_APIENTRY *<API key>)( ALCcontext *context );
// void (ALC_APIENTRY *<API key>)( ALCcontext *context );
// void (ALC_APIENTRY *<API key>)( ALCcontext *context );
// void (ALC_APIENTRY *<API key>)( ALCcontext *context );
// ALCcontext * (ALC_APIENTRY *<API key>)( void );
// ALCdevice * (ALC_APIENTRY *<API key>)( ALCcontext *context );
// ALCdevice * (ALC_APIENTRY *pfn_alcOpenDevice)( const ALCchar *devicename );
// ALCboolean (ALC_APIENTRY *pfn_alcCloseDevice)( ALCdevice *device );
// ALCenum (ALC_APIENTRY *pfn_alcGetError)( ALCdevice *device );
// ALCboolean (ALC_APIENTRY *<API key>)( ALCdevice *device, const ALCchar *extname );
// void * (ALC_APIENTRY *<API key>)(ALCdevice *device, const ALCchar *funcname );
// ALCenum (ALC_APIENTRY *pfn_alcGetEnumValue)(ALCdevice *device, const ALCchar *enumname );
// const ALCchar* (ALC_APIENTRY *pfn_alcGetString)( ALCdevice *device, ALCenum param );
// void (ALC_APIENTRY *pfn_alcGetIntegerv)( ALCdevice *device, ALCenum param, ALCsizei size, ALCint *data );
// ALCdevice * (ALC_APIENTRY *<API key>)( const ALCchar *devicename, ALCuint frequency, ALCenum format, ALCsizei buffersize );
// ALCboolean (ALC_APIENTRY *<API key>)( ALCdevice *device );
// void (ALC_APIENTRY *pfn_alcCaptureStart)( ALCdevice *device );
// void (ALC_APIENTRY *pfn_alcCaptureStop)( ALCdevice *device );
// void (ALC_APIENTRY *<API key>)( ALCdevice *device, ALCvoid *buffer, ALCsizei samples );
// // AL/alc.h wrappers for the go bindings.
// ALC_API ALCcontext * ALC_APIENTRY <API key>( ALCdevice *device, const int* attrlist ) { return (*<API key>)(device, attrlist); }
// ALC_API ALCboolean ALC_APIENTRY <API key>( ALCcontext *context ) { return (*<API key>)( context ); }
// ALC_API void ALC_APIENTRY <API key>( ALCcontext *context ) { (*<API key>)( context ); }
// ALC_API void ALC_APIENTRY <API key>( ALCcontext *context ) { (*<API key>)( context ); }
// ALC_API void ALC_APIENTRY <API key>( ALCcontext *context ) { (*<API key>)( context ); }
// ALC_API ALCcontext * ALC_APIENTRY <API key>( void ) { return (*<API key>)(); }
// ALC_API ALCdevice* ALC_APIENTRY <API key>( ALCcontext *context ) { return (*<API key>)( context ); }
// ALC_API ALCdevice * ALC_APIENTRY wrap_alcOpenDevice( const char *devicename ) { return (*pfn_alcOpenDevice)( devicename ); }
// ALC_API ALCboolean ALC_APIENTRY wrap_alcCloseDevice( ALCdevice *device ) { return (*pfn_alcCloseDevice)( device ); }
// ALC_API ALCenum ALC_APIENTRY wrap_alcGetError( ALCdevice *device ) { return (*pfn_alcGetError)( device ); }
// ALC_API ALCboolean ALC_APIENTRY <API key>( ALCdevice *device, const char *extname ) { return (*<API key>)( device, extname ); }
// ALC_API void * ALC_APIENTRY <API key>( ALCdevice *device, const char *funcname ) { return (*<API key>)(device, funcname ); }
// ALC_API ALCenum ALC_APIENTRY <API key>( ALCdevice *device, const char *enumname ) { return (*pfn_alcGetEnumValue)(device, enumname ); }
// ALC_API const char * ALC_APIENTRY wrap_alcGetString( ALCdevice *device, int param ) { return (*pfn_alcGetString)( device, param ); }
// ALC_API void ALC_APIENTRY wrap_alcGetIntegerv( ALCdevice *device, int param, int size, int *data ) { (*pfn_alcGetIntegerv)( device, param, size, data ); }
// ALC_API ALCdevice* ALC_APIENTRY <API key>( const char *devicename, unsigned int frequency, int format, int buffersize ) { return (*<API key>)( devicename, frequency, format, buffersize ); }
// ALC_API ALCboolean ALC_APIENTRY <API key>( ALCdevice *device ) { return (*<API key>)( device ); }
// ALC_API void ALC_APIENTRY <API key>( ALCdevice *device ) { (*pfn_alcCaptureStart)( device ); }
// ALC_API void ALC_APIENTRY wrap_alcCaptureStop( ALCdevice *device ) { (*pfn_alcCaptureStop)( device ); }
// ALC_API void ALC_APIENTRY <API key>( ALCdevice *device, ALCvoid *buffer, int samples ) { (*<API key>)( device, buffer, samples ); }
// void al_init() {
// // AL/al.h
// pfn_alEnable = bindMethod("alEnable");
// pfn_alDisable = bindMethod("alDisable");
// pfn_alIsEnabled = bindMethod("alIsEnabled");
// pfn_alGetString = bindMethod("alGetString");
// pfn_alGetBooleanv = bindMethod("alGetBooleanv");
// pfn_alGetIntegerv = bindMethod("alGetIntegerv");
// pfn_alGetFloatv = bindMethod("alGetFloatv");
// pfn_alGetDoublev = bindMethod("alGetDoublev");
// pfn_alGetBoolean = bindMethod("alGetBoolean");
// pfn_alGetInteger = bindMethod("alGetInteger");
// pfn_alGetFloat = bindMethod("alGetFloat");
// pfn_alGetDouble = bindMethod("alGetDouble");
// pfn_alGetError = bindMethod("alGetError");
// <API key> = bindMethod("<API key>");
// <API key> = bindMethod("alGetProcAddress");
// pfn_alGetEnumValue = bindMethod("alGetEnumValue");
// pfn_alListenerf = bindMethod("alListenerf");
// pfn_alListener3f = bindMethod("alListener3f");
// pfn_alListenerfv = bindMethod("alListenerfv");
// pfn_alListeneri = bindMethod("alListeneri");
// pfn_alListener3i = bindMethod("alListener3i");
// pfn_alListeneriv = bindMethod("alListeneriv");
// pfn_alGetListenerf = bindMethod("alGetListenerf");
// pfn_alGetListener3f = bindMethod("alGetListener3f");
// pfn_alGetListenerfv = bindMethod("alGetListenerfv");
// pfn_alGetListeneri = bindMethod("alGetListeneri");
// pfn_alGetListener3i = bindMethod("alGetListener3i");
// pfn_alGetListeneriv = bindMethod("alGetListeneriv");
// pfn_alGenSources = bindMethod("alGenSources");
// pfn_alDeleteSources = bindMethod("alDeleteSources");
// pfn_alIsSource = bindMethod("alIsSource");
// pfn_alSourcef = bindMethod("alSourcef");
// pfn_alSource3f = bindMethod("alSource3f");
// pfn_alSourcefv = bindMethod("alSourcefv");
// pfn_alSourcei = bindMethod("alSourcei");
// pfn_alSource3i = bindMethod("alSource3i");
// pfn_alSourceiv = bindMethod("alSourceiv");
// pfn_alGetSourcef = bindMethod("alGetSourcef");
// pfn_alGetSource3f = bindMethod("alGetSource3f");
// pfn_alGetSourcefv = bindMethod("alGetSourcefv");
// pfn_alGetSourcei = bindMethod("alGetSourcei");
// pfn_alGetSource3i = bindMethod("alGetSource3i");
// pfn_alGetSourceiv = bindMethod("alGetSourceiv");
// pfn_alSourcePlayv = bindMethod("alSourcePlayv");
// pfn_alSourceStopv = bindMethod("alSourceStopv");
// pfn_alSourceRewindv = bindMethod("alSourceRewindv");
// pfn_alSourcePausev = bindMethod("alSourcePausev");
// pfn_alSourcePlay = bindMethod("alSourcePlay");
// pfn_alSourceStop = bindMethod("alSourceStop");
// pfn_alSourceRewind = bindMethod("alSourceRewind");
// pfn_alSourcePause = bindMethod("alSourcePause");
// <API key> = bindMethod("<API key>");
// <API key> = bindMethod("<API key>");
// pfn_alGenBuffers = bindMethod("alGenBuffers");
// pfn_alDeleteBuffers = bindMethod("alDeleteBuffers");
// pfn_alIsBuffer = bindMethod("alIsBuffer");
// pfn_alBufferData = bindMethod("alBufferData");
// pfn_alBufferf = bindMethod("alBufferf");
// pfn_alBuffer3f = bindMethod("alBuffer3f");
// pfn_alBufferfv = bindMethod("alBufferfv");
// pfn_alBufferi = bindMethod("alBufferi");
// pfn_alBuffer3i = bindMethod("alBuffer3i");
// pfn_alBufferiv = bindMethod("alBufferiv");
// pfn_alGetBufferf = bindMethod("alGetBufferf");
// pfn_alGetBuffer3f = bindMethod("alGetBuffer3f");
// pfn_alGetBufferfv = bindMethod("alGetBufferfv");
// pfn_alGetBufferi = bindMethod("alGetBufferi");
// pfn_alGetBuffer3i = bindMethod("alGetBuffer3i");
// pfn_alGetBufferiv = bindMethod("alGetBufferiv");
// pfn_alDopplerFactor = bindMethod("alDopplerFactor");
// <API key> = bindMethod("alDopplerVelocity");
// pfn_alSpeedOfSound = bindMethod("alSpeedOfSound");
// pfn_alDistanceModel = bindMethod("alDistanceModel");
// // AL/alc.h
// <API key> = bindMethod("alcCreateContext");
// <API key> = bindMethod("<API key>");
// <API key> = bindMethod("alcProcessContext");
// <API key> = bindMethod("alcSuspendContext");
// <API key> = bindMethod("alcDestroyContext");
// <API key> = bindMethod("<API key>");
// <API key> = bindMethod("<API key>");
// pfn_alcOpenDevice = bindMethod("alcOpenDevice");
// pfn_alcCloseDevice = bindMethod("alcCloseDevice");
// pfn_alcGetError = bindMethod("alcGetError");
// <API key> = bindMethod("<API key>");
// <API key> = bindMethod("alcGetProcAddress");
// pfn_alcGetEnumValue = bindMethod("alcGetEnumValue");
// pfn_alcGetString = bindMethod("alcGetString");
// pfn_alcGetIntegerv = bindMethod("alcGetIntegerv");
// <API key> = bindMethod("<API key>");
// <API key> = bindMethod("<API key>");
// pfn_alcCaptureStart = bindMethod("alcCaptureStart");
// pfn_alcCaptureStop = bindMethod("alcCaptureStop");
// <API key> = bindMethod("alcCaptureSamples");
import "C"
import "unsafe"
import "fmt"
// AL/al.h constants (with AL_ removed). Refer to the orginal header for constant documentation.
const (
FALSE = 0
TRUE = 1
NONE = 0
NO_ERROR = 0
SOURCE_RELATIVE = 0x202
CONE_INNER_ANGLE = 0x1001
CONE_OUTER_ANGLE = 0x1002
PITCH = 0x1003
POSITION = 0x1004
DIRECTION = 0x1005
VELOCITY = 0x1006
LOOPING = 0x1007
BUFFER = 0x1009
GAIN = 0x100A
MIN_GAIN = 0x100D
MAX_GAIN = 0x100E
ORIENTATION = 0x100F
SOURCE_STATE = 0x1010
INITIAL = 0x1011
PLAYING = 0x1012
PAUSED = 0x1013
STOPPED = 0x1014
BUFFERS_QUEUED = 0x1015
BUFFERS_PROCESSED = 0x1016
SEC_OFFSET = 0x1024
SAMPLE_OFFSET = 0x1025
BYTE_OFFSET = 0x1026
SOURCE_TYPE = 0x1027
STATIC = 0x1028
STREAMING = 0x1029
UNDETERMINED = 0x1030
FORMAT_MONO8 = 0x1100
FORMAT_MONO16 = 0x1101
FORMAT_STEREO8 = 0x1102
FORMAT_STEREO16 = 0x1103
REFERENCE_DISTANCE = 0x1020
ROLLOFF_FACTOR = 0x1021
CONE_OUTER_GAIN = 0x1022
MAX_DISTANCE = 0x1023
FREQUENCY = 0x2001
BITS = 0x2002
CHANNELS = 0x2003
SIZE = 0x2004
UNUSED = 0x2010
PENDING = 0x2011
PROCESSED = 0x2012
INVALID_NAME = 0xA001
INVALID_ENUM = 0xA002
INVALID_VALUE = 0xA003
INVALID_OPERATION = 0xA004
OUT_OF_MEMORY = 0xA005
VENDOR = 0xB001
VERSION = 0xB002
RENDERER = 0xB003
EXTENSIONS = 0xB004
DOPPLER_FACTOR = 0xC000
DOPPLER_VELOCITY = 0xC001
SPEED_OF_SOUND = 0xC003
DISTANCE_MODEL = 0xD000
INVERSE_DISTANCE = 0xD001
<API key> = 0xD002
LINEAR_DISTANCE = 0xD003
<API key> = 0xD004
EXPONENT_DISTANCE = 0xD005
<API key> = 0xD006
)
// AL/alc.h constants (with AL removed). Refer to the orginal header for constant documentation.
const (
C_FALSE = 0
C_TRUE = 1
C_NO_ERROR = 0
C_FREQUENCY = 0x1007
C_REFRESH = 0x1008
C_SYNC = 0x1009
C_MONO_SOURCES = 0x1010
C_STEREO_SOURCES = 0x1011
C_INVALID_DEVICE = 0xA001
C_INVALID_CONTEXT = 0xA002
C_INVALID_ENUM = 0xA003
C_INVALID_VALUE = 0xA004
C_OUT_OF_MEMORY = 0xA005
<API key> = 0x1004
C_DEVICE_SPECIFIER = 0x1005
C_EXTENSIONS = 0x1006
C_MAJOR_VERSION = 0x1000
C_MINOR_VERSION = 0x1001
C_ATTRIBUTES_SIZE = 0x1002
C_ALL_ATTRIBUTES = 0x1003
<API key> = 0x310
<API key> = 0x311
C_CAPTURE_SAMPLES = 0x312
)
// bind the methods to the function pointers
func Init() {
C.al_init()
}
// convert a uint boolean to a go bool
func cbool(albool uint) bool {
return albool == TRUE
}
// Special type mappings
type (
Context C.<API key>
Device C.<API key>
Pointer unsafe.Pointer
)
// AL/al.h go bindings
func Enable(capability int32) { C.wrap_alEnable(C.int(capability)) }
func Disable(capability int32) { C.wrap_alDisable(C.int(capability)) }
func IsEnabled(capability int32) bool { return cbool(uint(C.wrap_alIsEnabled(C.int(capability)))) }
func GetString(param int32) string { return C.GoString(C.wrap_alGetString(C.int(param))) }
func GetBooleanv(param int32, data *int8) { C.wrap_alGetBooleanv(C.int(param), (*C.char)(data)) }
func GetIntegerv(param int32, data *int32) { C.wrap_alGetIntegerv(C.int(param), (*C.int)(data)) }
func GetFloatv(param int32, data *float32) { C.wrap_alGetFloatv(C.int(param), (*C.float)(data)) }
func GetDoublev(param int32, data *float64) { C.wrap_alGetDoublev(C.int(param), (*C.double)(data)) }
func GetBoolean(param int32) bool { return cbool(uint(C.wrap_alGetBoolean(C.int(param)))) }
func GetInteger(param int32) int32 { return int32(C.wrap_alGetInteger(C.int(param))) }
func GetFloat(param int32) float32 { return float32(C.wrap_alGetFloat(C.int(param))) }
func GetDouble(param int32) float64 { return float64(C.wrap_alGetDouble(C.int(param))) }
func GetError() int32 { return int32(C.wrap_alGetError()) }
func IsExtensionPresent(extname string) bool {
cstr := C.CString(extname)
defer C.free(unsafe.Pointer(cstr))
return cbool(uint(C.<API key>(cstr)))
}
func GetProcAddress(fname string) Pointer {
cstr := C.CString(fname)
defer C.free(unsafe.Pointer(cstr))
return Pointer(C.<API key>(cstr))
}
func GetEnumValue(ename string) int32 {
cstr := C.CString(ename)
defer C.free(unsafe.Pointer(cstr))
return int32(C.wrap_alGetEnumValue(cstr))
}
func Listenerf(param int32, value float32) { C.wrap_alListenerf(C.int(param), C.float(value)) }
func Listener3f(param int32, value1, value2, value3 float32) {
C.wrap_alListener3f(C.int(param), C.float(value1), C.float(value2), C.float(value3))
}
func Listenerfv(param int32, values *float32) { C.wrap_alListenerfv(C.int(param), (*C.float)(values)) }
func Listeneri(param int32, value int32) { C.wrap_alListeneri(C.int(param), C.int(value)) }
func Listener3i(param int32, value1, value2, value3 int32) {
C.wrap_alListener3i(C.int(param), C.int(value1), C.int(value2), C.int(value3))
}
func Listeneriv(param int32, values *int32) { C.wrap_alListeneriv(C.int(param), (*C.int)(values)) }
func GetListenerf(param int32, value *float32) { C.wrap_alGetListenerf(C.int(param), (*C.float)(value)) }
func GetListener3f(param int32, value1, value2, value3 *float32) {
C.<API key>(C.int(param), (*C.float)(value1), (*C.float)(value2), (*C.float)(value3))
}
func GetListenerfv(param int32, values *float32) {
C.<API key>(C.int(param), (*C.float)(values))
}
func GetListeneri(param int32, value *int32) { C.wrap_alGetListeneri(C.int(param), (*C.int)(value)) }
func GetListener3i(param int32, value1, value2, value3 *int32) {
C.<API key>(C.int(param), (*C.int)(value1), (*C.int)(value2), (*C.int)(value3))
}
func GetListeneriv(param int32, values *int32) { C.<API key>(C.int(param), (*C.int)(values)) }
func GenSources(n int32, sources *uint32) { C.wrap_alGenSources(C.int(n), (*C.uint)(sources)) }
func DeleteSources(n int32, sources *uint32) { C.<API key>(C.int(n), (*C.uint)(sources)) }
func IsSource(sid uint32) bool { return cbool(uint(C.wrap_alIsSource(C.uint(sid)))) }
func Sourcef(sid uint32, param int32, value float32) {
C.wrap_alSourcef(C.uint(sid), C.int(param), C.float(value))
}
func Source3f(sid uint32, param int32, value1, value2, value3 float32) {
C.wrap_alSource3f(C.uint(sid), C.int(param), C.float(value1), C.float(value2), C.float(value3))
}
func Sourcefv(sid uint32, param int32, values *float32) {
C.wrap_alSourcefv(C.uint(sid), C.int(param), (*C.float)(values))
}
func Sourcei(sid uint32, param int32, value int32) {
C.wrap_alSourcei(C.uint(sid), C.int(param), C.int(value))
}
func Source3i(sid uint32, param int32, value1, value2, value3 int32) {
C.wrap_alSource3i(C.uint(sid), C.int(param), C.int(value1), C.int(value2), C.int(value3))
}
func Sourceiv(sid uint32, param int32, values *int32) {
C.wrap_alSourceiv(C.uint(sid), C.int(param), (*C.int)(values))
}
func GetSourcef(sid uint32, param int32, value *float32) {
C.wrap_alGetSourcef(C.uint(sid), C.int(param), (*C.float)(value))
}
func GetSource3f(sid uint32, param int32, value1, value2, value3 *float32) {
C.wrap_alGetSource3f(C.uint(sid), C.int(param), (*C.float)(value1), (*C.float)(value2), (*C.float)(value3))
}
func GetSourcefv(sid uint32, param int32, values *float32) {
C.wrap_alGetSourcefv(C.uint(sid), C.int(param), (*C.float)(values))
}
func GetSourcei(sid uint32, param int32, value *int32) {
C.wrap_alGetSourcei(C.uint(sid), C.int(param), (*C.int)(value))
}
func GetSource3i(sid uint32, param int32, value1, value2, value3 *int32) {
C.wrap_alGetSource3i(C.uint(sid), C.int(param), (*C.int)(value1), (*C.int)(value2), (*C.int)(value3))
}
func GetSourceiv(sid uint32, param int32, values *int32) {
C.wrap_alGetSourceiv(C.uint(sid), C.int(param), (*C.int)(values))
}
func SourcePlayv(ns int32, sids *uint32) { C.wrap_alSourcePlayv(C.int(ns), (*C.uint)(sids)) }
func SourceStopv(ns int32, sids *uint32) { C.wrap_alSourceStopv(C.int(ns), (*C.uint)(sids)) }
func SourceRewindv(ns int32, sids *uint32) { C.<API key>(C.int(ns), (*C.uint)(sids)) }
func SourcePausev(ns int32, sids *uint32) { C.wrap_alSourcePausev(C.int(ns), (*C.uint)(sids)) }
func SourcePlay(sid uint32) { C.wrap_alSourcePlay(C.uint(sid)) }
func SourceStop(sid uint32) { C.wrap_alSourceStop(C.uint(sid)) }
func SourceRewind(sid uint32) { C.wrap_alSourceRewind(C.uint(sid)) }
func SourcePause(sid uint32) { C.wrap_alSourcePause(C.uint(sid)) }
func SourceQueueBuffers(sid uint32, numEntries int32, bids *uint32) {
C.<API key>(C.uint(sid), C.int(numEntries), (*C.uint)(bids))
}
func <API key>(sid uint32, numEntries int32, bids *uint32) {
C.<API key>(C.uint(sid), C.int(numEntries), (*C.uint)(bids))
}
func GenBuffers(n int32, buffers *uint32) { C.wrap_alGenBuffers(C.int(n), (*C.uint)(buffers)) }
func DeleteBuffers(n int32, buffers *uint32) { C.<API key>(C.int(n), (*C.uint)(buffers)) }
func IsBuffer(bid uint32) bool { return cbool(uint(C.wrap_alIsBuffer(C.uint(bid)))) }
func BufferData(bid uint32, format int32, data Pointer, size int32, freq int32) {
C.wrap_alBufferData(C.uint(bid), C.int(format), unsafe.Pointer(data), C.int(size), C.int(freq))
}
func Bufferf(bid uint32, param int32, value float32) {
C.wrap_alBufferf(C.uint(bid), C.int(param), C.float(value))
}
func Buffer3f(bid uint32, param int32, value1, value2, value3 float32) {
C.wrap_alBuffer3f(C.uint(bid), C.int(param), C.float(value1), C.float(value2), C.float(value3))
}
func Bufferfv(bid uint32, param int32, values *float32) {
C.wrap_alBufferfv(C.uint(bid), C.int(param), (*C.float)(values))
}
func Bufferi(bid uint32, param int32, value int32) {
C.wrap_alBufferi(C.uint(bid), C.int(param), C.int(value))
}
func Buffer3i(bid uint32, param int32, value1, value2, value3 int32) {
C.wrap_alBuffer3i(C.uint(bid), C.int(param), C.int(value1), C.int(value2), C.int(value3))
}
func Bufferiv(bid uint32, param int32, values *int32) {
C.wrap_alBufferiv(C.uint(bid), C.int(param), (*C.int)(values))
}
func GetBufferf(bid uint32, param int32, value *float32) {
C.wrap_alGetBufferf(C.uint(bid), C.int(param), (*C.float)(value))
}
func GetBuffer3f(bid uint32, param int32, value1, value2, value3 *float32) {
C.wrap_alGetBuffer3f(C.uint(bid), C.int(param), (*C.float)(value1), (*C.float)(value2), (*C.float)(value3))
}
func GetBufferfv(bid uint32, param int32, values *float32) {
C.wrap_alGetBufferfv(C.uint(bid), C.int(param), (*C.float)(values))
}
func GetBufferi(bid uint32, param int32, value *int32) {
C.wrap_alGetBufferi(C.uint(bid), C.int(param), (*C.int)(value))
}
func GetBuffer3i(bid uint32, param int32, value1, value2, value3 *int32) {
C.wrap_alGetBuffer3i(C.uint(bid), C.int(param), (*C.int)(value1), (*C.int)(value2), (*C.int)(value3))
}
func GetBufferiv(bid uint32, param int32, values *int32) {
C.wrap_alGetBufferiv(C.uint(bid), C.int(param), (*C.int)(values))
}
func DopplerFactor(value float32) { C.<API key>(C.float(value)) }
func DopplerVelocity(value float32) { C.<API key>(C.float(value)) }
func SpeedOfSound(value float32) { C.wrap_alSpeedOfSound(C.float(value)) }
func DistanceModel(distanceModel float32) { C.<API key>(C.int(distanceModel)) }
// AL/alc.h go bindings
func CreateContext(device *Device, attrlist *int32) *Context {
return (*Context)(C.<API key>((*C.<API key>)(device), (*C.int)(attrlist)))
}
func MakeContextCurrent(context *Context) bool {
return cbool(uint(C.<API key>((*C.<API key>)(context))))
}
func ProcessContext(context *Context) {
C.<API key>((*C.<API key>)(context))
}
func SuspendContext(context *Context) {
C.<API key>((*C.<API key>)(context))
}
func DestroyContext(context *Context) {
C.<API key>((*C.<API key>)(context))
}
func GetCurrentContext() *Context { return (*Context)(C.<API key>()) }
func GetContextsDevice(context *Context) *Device {
return (*Device)(C.<API key>((*C.<API key>)(context)))
}
func OpenDevice(devicename string) *Device {
if devicename != "" {
return (*Device)(C.wrap_alcOpenDevice(nil))
}
cstr := C.CString(devicename)
defer C.free(unsafe.Pointer(cstr))
return (*Device)(C.wrap_alcOpenDevice(cstr))
}
func CloseDevice(device *Device) bool {
return cbool(uint(C.wrap_alcCloseDevice((*C.<API key>)(device))))
}
func GetDeviceError(device *Device) int32 {
return int32(C.wrap_alcGetError((*C.<API key>)(device)))
}
func <API key>(device *Device, extname string) bool {
cstr := C.CString(extname)
defer C.free(unsafe.Pointer(cstr))
return cbool(uint(C.<API key>((*C.<API key>)(device), cstr)))
}
func <API key>(device *Device, fname string) Pointer {
cstr := C.CString(fname)
defer C.free(unsafe.Pointer(cstr))
return Pointer(C.<API key>((*C.<API key>)(device), cstr))
}
func GetDeviceEnumValue(device *Device, ename string) int32 {
cstr := C.CString(ename)
defer C.free(unsafe.Pointer(cstr))
return int32(C.<API key>((*C.<API key>)(device), cstr))
}
func GetDeviceString(device *Device, param int32) string {
return C.GoString(C.wrap_alcGetString((*C.<API key>)(device), C.int(param)))
}
func GetDeviceIntegerv(device *Device, param int32, size int32, data *int32) {
C.wrap_alcGetIntegerv((*C.<API key>)(device), C.int(param), C.int(size), (*C.int)(data))
}
func CaptureOpenDevice(devicename string, frequency uint32, format int32, buffersize int32) *Device {
cstr := C.CString(devicename)
defer C.free(unsafe.Pointer(cstr))
return (*Device)(C.<API key>(cstr, C.uint(frequency), C.int(format), C.int(buffersize)))
}
func CaptureCloseDevice(device *Device) bool {
return cbool(uint(C.<API key>((*C.<API key>)(device))))
}
func CaptureStart(device *Device) { C.<API key>((*C.<API key>)(device)) }
func CaptureStop(device *Device) { C.wrap_alcCaptureStop((*C.<API key>)(device)) }
func CaptureSamples(device *Device, buffer Pointer, samples int) {
C.<API key>((*C.<API key>)(device), unsafe.Pointer(buffer), C.int(samples))
}
// Show which function pointers are bound [+] or not bound [-].
// Expected to be used as a sanity check to see if the OpenAL libraries exist.
func BindingReport() (report []string) {
report = []string{}
// AL/al.h
report = append(report, "AL")
report = append(report, isBound(unsafe.Pointer(C.pfn_alEnable), "alEnable"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alEnable), "alEnable"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alDisable), "alDisable"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alIsEnabled), "alIsEnabled"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetString), "alGetString"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBooleanv), "alGetBooleanv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetIntegerv), "alGetIntegerv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetFloatv), "alGetFloatv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetDoublev), "alGetDoublev"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBoolean), "alGetBoolean"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetInteger), "alGetInteger"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetFloat), "alGetFloat"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetDouble), "alGetDouble"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetError), "alGetError"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alGetProcAddress"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetEnumValue), "alGetEnumValue"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alListenerf), "alListenerf"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alListener3f), "alListener3f"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alListenerfv), "alListenerfv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alListeneri), "alListeneri"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alListener3i), "alListener3i"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alListeneriv), "alListeneriv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetListenerf), "alGetListenerf"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetListener3f), "alGetListener3f"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetListenerfv), "alGetListenerfv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetListeneri), "alGetListeneri"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetListener3i), "alGetListener3i"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetListeneriv), "alGetListeneriv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGenSources), "alGenSources"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alDeleteSources), "alDeleteSources"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alIsSource), "alIsSource"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcef), "alSourcef"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSource3f), "alSource3f"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcefv), "alSourcefv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcei), "alSourcei"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSource3i), "alSource3i"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourceiv), "alSourceiv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetSourcef), "alGetSourcef"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetSource3f), "alGetSource3f"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetSourcefv), "alGetSourcefv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetSourcei), "alGetSourcei"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetSource3i), "alGetSource3i"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetSourceiv), "alGetSourceiv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcePlayv), "alSourcePlayv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourceStopv), "alSourceStopv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourceRewindv), "alSourceRewindv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcePausev), "alSourcePausev"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcePlay), "alSourcePlay"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourceStop), "alSourceStop"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourceRewind), "alSourceRewind"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSourcePause), "alSourcePause"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGenBuffers), "alGenBuffers"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alDeleteBuffers), "alDeleteBuffers"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alIsBuffer), "alIsBuffer"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBufferData), "alBufferData"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBufferf), "alBufferf"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBuffer3f), "alBuffer3f"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBufferfv), "alBufferfv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBufferi), "alBufferi"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBuffer3i), "alBuffer3i"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alBufferiv), "alBufferiv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBufferf), "alGetBufferf"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBuffer3f), "alGetBuffer3f"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBufferfv), "alGetBufferfv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBufferi), "alGetBufferi"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBuffer3i), "alGetBuffer3i"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alGetBufferiv), "alGetBufferiv"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alDopplerFactor), "alDopplerFactor"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alDopplerVelocity"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alSpeedOfSound), "alSpeedOfSound"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alDistanceModel), "alDistanceModel"))
// AL/alc.h
report = append(report, "ALC")
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alcCreateContext"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alcProcessContext"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alcSuspendContext"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alcDestroyContext"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcOpenDevice), "alcOpenDevice"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcCloseDevice), "alcCloseDevice"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcGetError), "alcGetError"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alcGetProcAddress"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcGetEnumValue), "alcGetEnumValue"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcGetString), "alcGetString"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcGetIntegerv), "alcGetIntegerv"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "<API key>"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcCaptureStart), "alcCaptureStart"))
report = append(report, isBound(unsafe.Pointer(C.pfn_alcCaptureStop), "alcCaptureStop"))
report = append(report, isBound(unsafe.Pointer(C.<API key>), "alcCaptureSamples"))
return
}
// isBound returns a string that indicates if the given function
// pointer is bound.
func isBound(pfn unsafe.Pointer, fn string) string {
inc := " "
if pfn != nil {
inc = "+"
}
return fmt.Sprintf(" [%s] %s", inc, fn)
} |
\hypertarget{structmdhim__t}{\section{mdhim\-\_\-t Struct Reference}
\label{structmdhim__t}\index{mdhim\-\_\-t@{mdhim\-\_\-t}}
}
{\ttfamily \#include $<$mdhim.\-h$>$}
\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
M\-P\-I\-\_\-\-Comm \hyperlink{<API key>}{mdhim\-\_\-comm}
\item
M\-P\-I\-\_\-\-Comm \hyperlink{<API key>}{mdhim\-\_\-client\-\_\-comm}
\item
int \hyperlink{<API key>}{mdhim\-\_\-rank}
\item
int \hyperlink{<API key>}{mdhim\-\_\-comm\-\_\-size}
\item
int \hyperlink{<API key>}{key\-\_\-type}
\item
uint32\-\_\-t \hyperlink{<API key>}{num\-\_\-rangesrvs}
\item
\hyperlink{<API key>}{rangesrv\-\_\-info} $\ast$ \hyperlink{<API key>}{rangesrvs}
\item
int \hyperlink{<API key>}{rangesrv\-\_\-master}
\item
\hyperlink{structmdhim__rs__t}{mdhim\-\_\-rs\-\_\-t} $\ast$ \hyperlink{<API key>}{mdhim\-\_\-rs}
\item
pthread\-\_\-mutex\-\_\-t $\ast$ \hyperlink{<API key>}{receive\-\_\-msg\-\_\-mutex}
\item
pthread\-\_\-cond\-\_\-t $\ast$ \hyperlink{<API key>}{receive\-\_\-msg\-\_\-ready\-\_\-cv}
\item
void $\ast$ \hyperlink{<API key>}{receive\-\_\-msg}
\item
\hyperlink{<API key>}{mdhim\-\_\-options\-\_\-t} $\ast$ \hyperlink{<API key>}{db\-\_\-opts}
\item
struct \hyperlink{structmdhim__stat}{mdhim\-\_\-stat} $\ast$ \hyperlink{<API key>}{stats}
\end{DoxyCompactItemize}
\subsection{Member Data Documentation}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!db\-\_\-opts@{db\-\_\-opts}}
\index{db\-\_\-opts@{db\-\_\-opts}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{db\-\_\-opts}]{\setlength{\rightskip}{0pt plus 5cm}{\bf mdhim\-\_\-options\-\_\-t}$\ast$ mdhim\-\_\-t\-::db\-\_\-opts}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!key\-\_\-type@{key\-\_\-type}}
\index{key\-\_\-type@{key\-\_\-type}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{key\-\_\-type}]{\setlength{\rightskip}{0pt plus 5cm}int mdhim\-\_\-t\-::key\-\_\-type}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!mdhim\-\_\-client\-\_\-comm@{mdhim\-\_\-client\-\_\-comm}}
\index{mdhim\-\_\-client\-\_\-comm@{mdhim\-\_\-client\-\_\-comm}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{mdhim\-\_\-client\-\_\-comm}]{\setlength{\rightskip}{0pt plus 5cm}M\-P\-I\-\_\-\-Comm mdhim\-\_\-t\-::mdhim\-\_\-client\-\_\-comm}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!mdhim\-\_\-comm@{mdhim\-\_\-comm}}
\index{mdhim\-\_\-comm@{mdhim\-\_\-comm}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{mdhim\-\_\-comm}]{\setlength{\rightskip}{0pt plus 5cm}M\-P\-I\-\_\-\-Comm mdhim\-\_\-t\-::mdhim\-\_\-comm}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!mdhim\-\_\-comm\-\_\-size@{mdhim\-\_\-comm\-\_\-size}}
\index{mdhim\-\_\-comm\-\_\-size@{mdhim\-\_\-comm\-\_\-size}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{mdhim\-\_\-comm\-\_\-size}]{\setlength{\rightskip}{0pt plus 5cm}int mdhim\-\_\-t\-::mdhim\-\_\-comm\-\_\-size}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!mdhim\-\_\-rank@{mdhim\-\_\-rank}}
\index{mdhim\-\_\-rank@{mdhim\-\_\-rank}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{mdhim\-\_\-rank}]{\setlength{\rightskip}{0pt plus 5cm}int mdhim\-\_\-t\-::mdhim\-\_\-rank}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!mdhim\-\_\-rs@{mdhim\-\_\-rs}}
\index{mdhim\-\_\-rs@{mdhim\-\_\-rs}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{mdhim\-\_\-rs}]{\setlength{\rightskip}{0pt plus 5cm}{\bf mdhim\-\_\-rs\-\_\-t}$\ast$ mdhim\-\_\-t\-::mdhim\-\_\-rs}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!num\-\_\-rangesrvs@{num\-\_\-rangesrvs}}
\index{num\-\_\-rangesrvs@{num\-\_\-rangesrvs}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{num\-\_\-rangesrvs}]{\setlength{\rightskip}{0pt plus 5cm}uint32\-\_\-t mdhim\-\_\-t\-::num\-\_\-rangesrvs}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!rangesrv\-\_\-master@{rangesrv\-\_\-master}}
\index{rangesrv\-\_\-master@{rangesrv\-\_\-master}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{rangesrv\-\_\-master}]{\setlength{\rightskip}{0pt plus 5cm}int mdhim\-\_\-t\-::rangesrv\-\_\-master}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!rangesrvs@{rangesrvs}}
\index{rangesrvs@{rangesrvs}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{rangesrvs}]{\setlength{\rightskip}{0pt plus 5cm}{\bf rangesrv\-\_\-info}$\ast$ mdhim\-\_\-t\-::rangesrvs}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!receive\-\_\-msg@{receive\-\_\-msg}}
\index{receive\-\_\-msg@{receive\-\_\-msg}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{receive\-\_\-msg}]{\setlength{\rightskip}{0pt plus 5cm}void$\ast$ mdhim\-\_\-t\-::receive\-\_\-msg}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!receive\-\_\-msg\-\_\-mutex@{receive\-\_\-msg\-\_\-mutex}}
\index{receive\-\_\-msg\-\_\-mutex@{receive\-\_\-msg\-\_\-mutex}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{receive\-\_\-msg\-\_\-mutex}]{\setlength{\rightskip}{0pt plus 5cm}pthread\-\_\-mutex\-\_\-t$\ast$ mdhim\-\_\-t\-::receive\-\_\-msg\-\_\-mutex}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!receive\-\_\-msg\-\_\-ready\-\_\-cv@{receive\-\_\-msg\-\_\-ready\-\_\-cv}}
\index{receive\-\_\-msg\-\_\-ready\-\_\-cv@{receive\-\_\-msg\-\_\-ready\-\_\-cv}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{receive\-\_\-msg\-\_\-ready\-\_\-cv}]{\setlength{\rightskip}{0pt plus 5cm}pthread\-\_\-cond\-\_\-t$\ast$ mdhim\-\_\-t\-::receive\-\_\-msg\-\_\-ready\-\_\-cv}}\label{<API key>}
\hypertarget{<API key>}{\index{mdhim\-\_\-t@{mdhim\-\_\-t}!stats@{stats}}
\index{stats@{stats}!mdhim_t@{mdhim\-\_\-t}}
\subsubsection[{stats}]{\setlength{\rightskip}{0pt plus 5cm}struct {\bf mdhim\-\_\-stat}$\ast$ mdhim\-\_\-t\-::stats}}\label{<API key>}
The documentation for this struct was generated from the following file\-:\begin{DoxyCompactItemize}
\item
src/\hyperlink{mdhim_8h}{mdhim.\-h}\end{DoxyCompactItemize} |
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using aGrader.Properties;
using aGrader.sourceCodes;
namespace aGrader
{
public partial class LanguageSelection : Form
{
public LanguageSelection()
{
InitializeComponent();
}
private void butCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void butC_Click(object sender, EventArgs e)
{
<API key>(false);
TestC.GetTccPath();
<API key>();
var dialog = new FolderBrowserDialog {Description = Resources.<API key>};
if (dialog.ShowDialog() == DialogResult.OK)
{
SourceCodes.SetPath(dialog.SelectedPath);
SourceCodes.LoadSourceCodeFiles("c");
DialogResult = DialogResult.OK;
Close();
}
else
{
<API key>();
}
}
private void <API key>()
{
foreach (var button in Controls.OfType<Button>())
{
button.Enabled = !button.Enabled;
}
}
private void butJava_Click(object sender, EventArgs e)
{
TestJava.GetPathToJava();
<API key>(true);
}
private void <API key>(bool show)
{
<API key>.Visible = show;
butJavaOneFile.Visible = show;
Size = show? new Size(311, 140) : new Size(311,75);
}
private void <API key>(object sender, EventArgs e)
{
<API key>();
var dialog = new FolderBrowserDialog
{Description = Resources.<API key> };
if (dialog.ShowDialog() == DialogResult.OK)
{
SourceCodes.SetPath(dialog.SelectedPath);
SourceCodes.LoadSourceCodeFiles("java", "single");
DialogResult = DialogResult.OK;
Close();
}
else
{
<API key>();
}
}
private void <API key>(object sender, EventArgs e)
{
<API key>();
var dialog = new FolderBrowserDialog
{ Description = Resources.<API key> };
if (dialog.ShowDialog() == DialogResult.OK)
{
SourceCodes.SetPath(dialog.SelectedPath);
SourceCodes.LoadSourceCodeFiles("java", "multi");
DialogResult = DialogResult.OK;
Close();
}
else
{
<API key>();
}
}
}
} |
// // modification, are permitted provided that the following conditions are met:
// // documentation and/or other materials provided with the distribution.
// // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("ShovelTests")]
[assembly: AssemblyDescription("")]
[assembly: <API key>("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("miron")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")] |
cask v1: '<API key>' do
version '1.0.1'
sha256 '<SHA256-like>'
url "http://www.polycom.co.uk/content/dam/polycom/common/documents/firmware/PPCIPmac_v#{version}.dmg.zip"
name 'People + Content IP'
homepage 'http://www.polycom.co.uk/products-services/<API key>/<API key>/people-content-ip.html#stab1'
license :gratis
container nested: "PPCIPmac_v#{version}.dmg"
app 'People + Content IP.app'
end |
#ifndef INTERFACE_HPP
#define INTERFACE_HPP
#include <array>
#include <vector>
#include <string>
#include <sstream>
#include <stdint.h>
#include "util.hpp"
/*! Represents one hardware interface.
* This struct includes all necessary information
* to characterize one ethernet port
*/
struct Interface {
std::array<uint8_t, 6> mac = {{0}}; //!< MAC address
uint32_t netlinkIndex = uint32_t_max; //!< Index of the interface in the netlink context
uint32_t netmapIndex = uint32_t_max; //!< Index of the interface in the netmap context
std::vector<uint32_t> IPs; //!< All configured IPs
std::string name = "noname"; //!< Name of the interface
/*! Order by netmapIndex. */
bool operator< (const Interface& i) const {
return netmapIndex > i.netmapIndex;
};
/*! Equal by netmapIndex. */
bool operator== (const Interface& i) const {
return netmapIndex == i.netmapIndex;
};
/*! Equal by netmapIndex. */
bool operator== (uint32_t i) const {
return netmapIndex == i;
};
/*! Equal by name. */
bool operator== (std::string str) const {
return name == str;
};
/* Return string representation. */
std::string toString(){
std::stringstream sstream;
sstream << "\tName: " << name << std::endl;
sstream << "\tMAC address: " << mac_to_str(mac) << std::endl;
sstream << "\tNetlink Index: " << netlinkIndex << std::endl;
sstream << "\tNetmap Index: " << netmapIndex << std::endl;
sstream << "\tIP addresses: ";
for(auto ip : IPs) {
sstream << ip_to_str(ip) << std::endl << "\t ";
}
return sstream.str();
};
};
#endif /* INTERFACE_HPP */ |
# Usage instructions
* [Get-GacAssembly](Get-GacAssembly.md) Gets the assemblies in the GAC (alias gga)
* [Get-GacAssemblyFile](Get-GacAssemblyFile.md) Gets the FileInfo of assemblies in the GAC
* [<API key>](<API key>.md) Gets the InstallReference of assemblies in the GAC
* [Add-GacAssembly](Add-GacAssembly.md) Adds the assembly to the GAC
* [Remove-GacAssembly](Remove-GacAssembly.md) Removes the assembly from the GAC
* [<API key>](<API key>.md) Creates a new install reference
* [<API key>](<API key>.md) Determines whether the assembly name is fully qualified
* [<API key>](<API key>.md) Determines whether the install reference can be used with Add-GacAssembly and Remove-GacAssembly
* [FileVersion Table View](<API key>.md) Adds column showing the FileVersion
# Alternatives
There are some alternatives to PowerShell GAC to view are modify the contents of the GAC. PowerShell GAC has the following advantages compare to some of these alternatives:
* Supports all .Net versions, including .Net 4.0 en .Net 4.5, even from PowerShell 2.0
* No other tools needed
* Does not depend on changing internals, but uses the documented GAC API
* Full range of features of the GAC accessible
* Extraction of assemblies from the GAC possible
* Listing file versions of the assemblies in the GAC
* Great integration with other PowerShell commands and scripts
## System.EnterpriseServices.Internal.Publish
The .Net Framework comes contains two simples method to add and remove assemblies from the GAC. There are no methods to view the contents of the GAC. These methods do not return any error codes nor exceptions, so there is no feedback on the results. Also in order to remove an assembly from the GAC you need specify the path to an assembly with the same identity as the assembly in the GAC. Administrative rights are required.
The methods [GacInstall](https:
The .Net 4.0 version of the `System.EnterpriseServices` assembly is needed to add or remove .Net 4.0 or .Net 4.5 assemblies. Since PowerShell 2.0 is not able to load .Net 4.0 assemblies it is needed to [run PowerShell 2.0 using .Net 4.0](https://stackoverflow.com/questions/2094694/<API key>) or use PowerShell 3.0.
The following PowerShell script can be used to add and remove assemblies from the GAC.
powershell
Add-Type -AssemblyName System.EnterpriseServices
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall('c:\folder\some.dll')
Add-Type -AssemblyName System.EnterpriseServices
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacRemove('c:\folder\some.dll')
## Gacutil.exe
Gacutil is a command line tool to view and modify the GAC. It has almost the same features as PowerShell GAC. This tool comes with Visual Studio, .Net Framework SDK and Windows SDK. The .Net 4.0 version of this tool is needed to install .Net 4.0 or 4.5 assemblies. Administrative rights are needed for adding and removing assemblies from the GAC. For more information see [here](https://msdn.microsoft.com/en-us/library/ex0ss12c(v=vs.110).aspx).
# Build instructions for developers
Uses the [GAC](https:
Use VisualStudio 2010 or 2012 to open the solution or build from the commandline with `MSBuild.exe PowerShellGac.csproj`. No need for VisualStudio. |
/**
* UB-RIA-UI 1.0
*
* @ignore
* @file
* @author wangyaqiong, liyidong(srhb18@gmail.com)
*/
define(
function (require) {
var Control = require('esui/Control');
var lib = require('esui/lib');
var ui = require('esui');
require('esui/Panel');
require('esui/Overlay');
/**
*
*
* @class ui.TogglePanel
* @extends.esui.Control
*/
var exports = {};
/**
* `"TogglePanel"`
*
* @type {string}
* @override
*/
exports.type = 'TogglePanel';
/**
*
*
* @param {Object} options
* @override
* @protected
*/
exports.initOptions = function (options) {
var defaults = {
expanded: false,
position: 'layer'
};
var properties = lib.extend(defaults, options);
this.setProperties(properties);
};
/**
* DOM
*
* @override
* @protected
*/
exports.initStructure = function () {
var children = lib.getChildren(this.main);
var titleElem = children[0];
var contentElem = children[1];
// TitleDOM
initTitle.call(this, titleElem);
// contentDOM
var position = this.position;
if (position === 'fixed') {
initContentPanel.call(this, contentElem);
}
else {
initContentOverlay.call(this, contentElem);
}
};
/**
* TitleDOM
*
* @inner
* @param {Object} titleElem TitleDOM
*/
function initTitle(titleElem) {
var titlePanel = ui.create('Panel', {main: titleElem});
this.helper.addPartClasses('title', titlePanel.main);
this.addChild(titlePanel, 'title');
titlePanel.render();
this.set('title', titleElem && titleElem.innerHTML);
}
/**
* PanelContentDOM
*
* @inner
* @param {Object} contentElem contentDOM
*/
function initContentPanel(contentElem) {
var options = {
main: contentElem,
childName: 'content',
viewContext: this.viewContext,
renderOptions: this.renderOptions
};
var contentPanel = ui.create('Panel', options);
this.helper.addPartClasses('content', contentPanel.main);
this.addChild(contentPanel, 'content');
contentPanel.render();
}
/**
* OverlayContentDOM
*
* @inner
* @param {Object} contentElem contentDOM
*/
function initContentOverlay(contentElem) {
var overlayMain = this.helper.createPart('layer', 'div');
lib.addClass(overlayMain, this.helper.getPartClassName('layer'));
var options = {
main: contentElem,
childName: 'content',
attachedDOM: this.main,
attachedLayout: 'bottom,left',
autoClose: false,
viewContext: this.viewContext,
renderOptions: this.renderOptions
};
var contentLayer = ui.create('Overlay', options);
this.helper.addPartClasses('content', contentLayer.main);
this.addChild(contentLayer, 'content');
contentLayer.render();
var globalEvent = lib.bind(close, this);
contentLayer.on(
'show',
function () {
this.helper.addDOMEvent(document, 'mousedown', globalEvent);
}
);
contentLayer.on(
'hide',
function () {
this.helper.removeDOMEvent(document, 'mousedown', globalEvent);
}
);
}
/**
* layer
*
* @param {mini-event.Event} e
* @inner
*/
function close(e) {
var target = e.target;
var layer = this.getChild('content');
if (!layer) {
return;
}
var isChild = lib.dom.contains(layer.main, target);
if (!isChild) {
layer.hide();
// attachedTargetexpanded.
// expanded
var attachedTarget = layer.attachedTarget;
var isAttachedTarget = lib.dom.contains(attachedTarget, target) || attachedTarget === target;
if (!isAttachedTarget) {
this.removeState('expanded');
this.removeState('active');
}
}
}
/**
* Title
*
* @inner
*/
function onToggle() {
this.toggleContent();
}
/**
* /
*
* @inner
*/
exports.toggleContent = function () {
this.toggleStates();
this.fire('change');
};
exports.toggleStates = function () {
var position = this.position;
if (position === 'fixed') {
this.toggleState('expanded');
this.toggleState('active');
}
else {
var contentLayer = this.getChild('content');
if (this.isExpanded()) {
this.removeState('expanded');
this.removeState('active');
contentLayer.hide();
}
else {
this.addState('expanded');
this.addState('active');
contentLayer.show();
}
}
};
exports.initEvents = function () {
var me = this;
me.$super(arguments);
var titlePanel = me.getChild('title');
me.helper.addDOMEvent(titlePanel.main, 'click', lib.bind(onToggle, me));
};
var painters = require('esui/painters');
/**
*
*
* @override
* @protected
*/
exports.repaint = painters.createRepaint(
Control.prototype.repaint,
painters.state('expanded'),
{
name: 'title',
paint: function (panel, title) {
panel.getChild('title').set('content', title);
}
},
{
name: 'content',
paint: function (panel, content) {
panel.getChild('content').set('content', content);
}
},
/**
* @property {number} width
*
*
*/
painters.style('width')
);
exports.isExpanded = function () {
return this.hasState('expanded');
};
var TogglePanel = require('eoo').create(Control, exports);
ui.register(TogglePanel);
return TogglePanel;
}
); |
#include <Python.h>
#include <datetime.h>
#include <dynd/types/string_type.hpp>
#include <dynd/types/bytes_type.hpp>
#include <dynd/types/strided_dim_type.hpp>
#include <dynd/types/cfixed_dim_type.hpp>
#include <dynd/types/var_dim_type.hpp>
#include <dynd/types/base_struct_type.hpp>
#include <dynd/types/date_type.hpp>
#include <dynd/types/datetime_type.hpp>
#include <dynd/types/type_type.hpp>
#include <dynd/type_promotion.hpp>
#include <dynd/memblock/<API key>.hpp>
#include <dynd/memblock/pod_memory_block.hpp>
#include <dynd/type_promotion.hpp>
#include <dynd/exceptions.hpp>
#include <dynd/kernels/assignment_kernels.hpp>
#include "array_from_py.hpp"
#include "<API key>.hpp"
#include "<API key>.hpp"
#include "<API key>.hpp"
#include "array_functions.hpp"
#include "type_functions.hpp"
#include "utility_functions.hpp"
#include "numpy_interop.hpp"
using namespace std;
using namespace dynd;
using namespace pydynd;
static const intptr_t <API key> = 16;
// Initialize the pydatetime API
namespace {
struct init_pydatetime {
init_pydatetime() {
PyDateTime_IMPORT;
}
};
init_pydatetime pdt;
struct afpd_coordentry {
// The current coordinate of this axis being processed
intptr_t coord;
// The type in the output array for this axis
ndt::type tp;
// The arrmeta pointer in the output array for this axis
const char *arrmeta_ptr;
// The data pointer in the output array for the next axis (or element)
char *data_ptr;
// Used for var dimensions, the amount of presently reserved space
intptr_t reserved_size;
};
struct afpd_dtype {
// The data type after all the dimensions
ndt::type dtp;
// The arrmeta pointer in the output array for the dtype
const char *arrmeta_ptr;
void swap(afpd_dtype& rhs) {
dtp.swap(rhs.dtp);
std::swap(arrmeta_ptr, rhs.arrmeta_ptr);
}
};
} // anonymous namespace
static void <API key>(
PyObject *obj,
std::vector<intptr_t>& shape,
std::vector<afpd_coordentry>& coord,
afpd_dtype& elem,
dynd::nd::array& arr,
intptr_t current_axis,
const eval::eval_context *ectx);
/**
* This allocates an nd::array for the first time,
* using the shape provided, and filling in the
* `coord` and `elem`.
*
* Pass shape.size() to promoted_axis for initial
* allocations or dtype promotions.
*/
static nd::array allocate_nd_arr(
const std::vector<intptr_t>& shape,
std::vector<afpd_coordentry>& coord,
afpd_dtype& elem,
intptr_t promoted_axis)
{
intptr_t ndim = (intptr_t)shape.size();
// Allocate the nd::array
nd::array result = nd::make_strided_array(
elem.dtp, ndim,
ndim == 0 ? NULL : &shape[0]);
// Fill `coord` with pointers from the allocated arrays,
// reserving some data for any var dimensions.
coord.resize(ndim);
ndt::type tp = result.get_type();
const char *arrmeta_ptr = result.get_arrmeta();
char *data_ptr = result.<API key>();
for (intptr_t i = 0; i < ndim; ++i) {
afpd_coordentry& c = coord[i];
c.coord = 0;
c.tp = tp;
c.arrmeta_ptr = arrmeta_ptr;
// If it's a var dim, reserve some space
if (tp.get_type_id() == var_dim_type_id) {
if (i < promoted_axis) {
// Only initialize the var dim elements prior
// to the promoted axis
intptr_t initial_count = <API key>;
ndt::<API key>(tp, arrmeta_ptr,
data_ptr, initial_count);
c.reserved_size = initial_count;
data_ptr = reinterpret_cast<const var_dim_type_data *>(data_ptr)->begin;
} else {
data_ptr = NULL;
}
// Advance arrmeta_ptr and data_ptr to the child dimension
arrmeta_ptr += sizeof(<API key>);
tp = tp.tcast<var_dim_type>()->get_element_type();
} else {
// Advance arrmeta_ptr and data_ptr to the child dimension
arrmeta_ptr += sizeof(<API key>);
tp = tp.tcast<strided_dim_type>()->get_element_type();
}
c.data_ptr = data_ptr;
}
elem.arrmeta_ptr = arrmeta_ptr;
return result;
}
/**
* This copies everything up to, and possibly including, the
* current coordinate in `src_coord`. When finished,
* `dst_coord` is left in a state equivalent to `src_coord`.
*
* The `copy_final_coord` controls whether the final coordinate
* for the axis `current_axis - 1` gets copied or not. Generally
* it shouldn't be, but when dealing with iterators it becomes
* necessary so as to preserve the already retrieved data.
*
* If `promoted_axis` is less than shape.size(), it's for
* the case where a dim was promoted from strided to var.
* If `promoted_axis` is equal to shape.size(), it's for
* promotion of a dtype.
*/
static void <API key>(
const std::vector<intptr_t>& shape,
char *dst_data_ptr,
std::vector<afpd_coordentry>& dst_coord,
afpd_dtype& dst_elem,
const char *src_data_ptr,
std::vector<afpd_coordentry>& src_coord,
afpd_dtype& src_elem,
const <API key>& ck,
intptr_t current_axis,
intptr_t promoted_axis,
bool copy_final_coord,
bool final_coordinate)
{
if (current_axis == promoted_axis - 1) {
// Base case - the final dimension
if (shape[current_axis] >= 0) {
// strided dimension case
const <API key> *dst_md =
reinterpret_cast<const <API key> *>(dst_coord[current_axis].arrmeta_ptr);
const <API key> *src_md =
reinterpret_cast<const <API key> *>(src_coord[current_axis].arrmeta_ptr);
if (!final_coordinate) {
// Copy the full dimension
ck(dst_data_ptr, dst_md->stride,
src_data_ptr, src_md->stride, shape[current_axis]);
} else {
// Copy up to, and possibly including, the coordinate
ck(dst_data_ptr, dst_md->stride,
src_data_ptr, src_md->stride,
src_coord[current_axis].coord + int(copy_final_coord));
dst_coord[current_axis].coord = src_coord[current_axis].coord;
dst_coord[current_axis].data_ptr = dst_data_ptr + dst_md->stride * dst_coord[current_axis].coord;
}
} else {
// var dimension case
const <API key> *dst_md =
reinterpret_cast<const <API key> *>(dst_coord[current_axis].arrmeta_ptr);
const <API key> *src_md =
reinterpret_cast<const <API key> *>(src_coord[current_axis].arrmeta_ptr);
var_dim_type_data *dst_d =
reinterpret_cast<var_dim_type_data *>(dst_data_ptr);
const var_dim_type_data *src_d =
reinterpret_cast<const var_dim_type_data *>(src_data_ptr);
if (!final_coordinate) {
ndt::<API key>(dst_coord[current_axis].tp,
dst_coord[current_axis].arrmeta_ptr,
dst_data_ptr, src_d->size);
// Copy the full dimension
ck(dst_d->begin, dst_md->stride,
src_d->begin, src_md->stride, src_d->size);
} else {
// Initialize the var element to the same reserved space as the input
ndt::<API key>(dst_coord[current_axis].tp,
dst_coord[current_axis].arrmeta_ptr,
dst_data_ptr, src_coord[current_axis].reserved_size);
dst_coord[current_axis].reserved_size = src_coord[current_axis].reserved_size;
// Copy up to, and possibly including, the coordinate
if (ck.get_function() != NULL) {
ck(dst_d->begin, dst_md->stride,
src_d->begin, src_md->stride,
src_coord[current_axis].coord + int(copy_final_coord));
}
dst_coord[current_axis].coord = src_coord[current_axis].coord;
dst_coord[current_axis].data_ptr = dst_d->begin +
dst_md->stride * dst_coord[current_axis].coord;
}
}
} else {
// Recursive case
if (shape[current_axis] >= 0) {
// strided dimension case
const <API key> *dst_md =
reinterpret_cast<const <API key> *>(dst_coord[current_axis].arrmeta_ptr);
const <API key> *src_md =
reinterpret_cast<const <API key> *>(src_coord[current_axis].arrmeta_ptr);
if (!final_coordinate) {
// Copy the full dimension
intptr_t size = shape[current_axis];
intptr_t dst_stride = dst_md->stride;
intptr_t src_stride = src_md->stride;
for (intptr_t i = 0; i < size; ++i,
dst_data_ptr += dst_stride,
src_data_ptr += src_stride) {
<API key>(shape,
dst_data_ptr, dst_coord, dst_elem,
src_data_ptr, src_coord, src_elem,
ck, current_axis + 1, promoted_axis, copy_final_coord, false);
}
} else {
// Copy up to, and including, the coordinate
intptr_t size = src_coord[current_axis].coord;
intptr_t dst_stride = dst_md->stride;
intptr_t src_stride = src_md->stride;
dst_coord[current_axis].coord = size;
dst_coord[current_axis].data_ptr = dst_data_ptr + dst_stride * size;
for (intptr_t i = 0; i <= size; ++i,
dst_data_ptr += dst_stride,
src_data_ptr += src_stride) {
<API key>(shape,
dst_data_ptr, dst_coord, dst_elem,
src_data_ptr, src_coord, src_elem,
ck, current_axis + 1, promoted_axis, copy_final_coord, i == size);
}
}
} else {
// var dimension case
const <API key> *dst_md =
reinterpret_cast<const <API key> *>(dst_coord[current_axis].arrmeta_ptr);
const <API key> *src_md =
reinterpret_cast<const <API key> *>(src_coord[current_axis].arrmeta_ptr);
var_dim_type_data *dst_d =
reinterpret_cast<var_dim_type_data *>(dst_data_ptr);
const var_dim_type_data *src_d =
reinterpret_cast<const var_dim_type_data *>(src_data_ptr);
if (!final_coordinate) {
ndt::<API key>(dst_coord[current_axis].tp,
dst_coord[current_axis].arrmeta_ptr,
dst_data_ptr, src_d->size);
// Copy the full dimension
intptr_t size = src_d->size;
char *dst_elem_ptr = dst_d->begin;
intptr_t dst_stride = dst_md->stride;
const char *src_elem_ptr = src_d->begin;
intptr_t src_stride = src_md->stride;
for (intptr_t i = 0; i < size; ++i,
dst_elem_ptr += dst_stride,
src_elem_ptr += src_stride) {
<API key>(shape,
dst_elem_ptr, dst_coord, dst_elem,
src_elem_ptr, src_coord, src_elem,
ck, current_axis + 1, promoted_axis, copy_final_coord, false);
}
} else {
// Initialize the var element to the same reserved space as the input
ndt::<API key>(dst_coord[current_axis].tp,
dst_coord[current_axis].arrmeta_ptr,
dst_data_ptr, src_coord[current_axis].reserved_size);
dst_coord[current_axis].reserved_size = src_coord[current_axis].reserved_size;
// Copy up to, and including, the size
intptr_t size = src_coord[current_axis].coord;
char *dst_elem_ptr = dst_d->begin;
intptr_t dst_stride = dst_md->stride;
const char *src_elem_ptr = src_d->begin;
intptr_t src_stride = src_md->stride;
dst_coord[current_axis].coord = size;
dst_coord[current_axis].data_ptr = dst_elem_ptr + dst_stride * size;
for (intptr_t i = 0; i <= size; ++i,
dst_elem_ptr += dst_stride,
src_elem_ptr += src_stride) {
<API key>(shape,
dst_elem_ptr, dst_coord, dst_elem,
src_elem_ptr, src_coord, src_elem,
ck, current_axis + 1, promoted_axis, copy_final_coord, i == size);
}
}
}
}
}
/**
* This function promotes the dtype the array currently has with
* `tp`, allocates a new one, then copies all the data up to the
* current index in `coord`. This modifies coord and elem in place.
*/
static void <API key>(
const std::vector<intptr_t>& shape,
std::vector<afpd_coordentry>& coord,
afpd_dtype& elem,
nd::array& arr,
const ndt::type& tp)
{
intptr_t ndim = shape.size();
vector<afpd_coordentry> newcoord;
afpd_dtype newelem;
if (elem.dtp.get_type_id() == <API key>) {
// If the `elem` dtype is uninitialized, it means a dummy
// array was created to capture dimensional structure until
// the first value is encountered
newelem.dtp = tp;
} else {
newelem.dtp = <API key>(elem.dtp, tp);
}
// Create the new array
nd::array newarr = allocate_nd_arr(shape, newcoord, newelem, ndim);
// Copy the data up to, but not including, the current `coord`
// from the old `arr` to the new one
<API key> k;
if (elem.dtp.get_type_id() != <API key>) {
<API key>(
&k, 0, newelem.dtp, newelem.arrmeta_ptr, elem.dtp, elem.arrmeta_ptr,
<API key>, &eval::<API key>);
} else {
// An assignment kernel which copies one byte - will only
// be called with count==0 when dtp is uninitialized
<API key>(
&k, 0, ndt::make_type<char>(), NULL, ndt::make_type<char>(), NULL,
<API key>, &eval::<API key>);
}
<API key>(shape, newarr.<API key>(),
newcoord, newelem, arr.<API key>(),
coord, elem, k, 0, ndim, false, true);
arr.swap(newarr);
coord.swap(newcoord);
elem.swap(newelem);
}
/**
* This function promotes the requested `axis` from
* a strided dim to a var dim. It modifies `shape`, `coord`,
* `elem`, and `arr` to point to a new array, and
* copies the data over.
*/
static void promote_nd_arr_dim(
std::vector<intptr_t>& shape,
std::vector<afpd_coordentry>& coord,
afpd_dtype& elem,
nd::array& arr,
intptr_t axis,
bool copy_final_coord)
{
vector<afpd_coordentry> newcoord;
afpd_dtype newelem;
newelem.dtp = elem.dtp;
// Convert the axis into a var dim
shape[axis] = -1;
// Create the new array
nd::array newarr = allocate_nd_arr(shape, newcoord, newelem, axis);
// Copy the data up to, but not including, the current `coord`
// from the old `arr` to the new one. The recursion stops
// at `axis`, where all subsequent dimensions are handled by the
// created kernel.
<API key> k;
if (elem.dtp.get_type_id() != <API key>) {
<API key>(&k, 0, newcoord[axis].tp,
newcoord[axis].arrmeta_ptr, coord[axis].tp,
coord[axis].arrmeta_ptr, <API key>,
&eval::<API key>);
}
<API key>(shape, newarr.<API key>(),
newcoord, newelem, arr.<API key>(),
coord, elem, k, 0, axis, copy_final_coord, true);
arr.swap(newarr);
coord.swap(newcoord);
elem.swap(newelem);
}
static bool bool_assign(char *data, PyObject *obj)
{
if (obj == Py_True) {
*data = 1;
return true;
} else if (obj == Py_False) {
*data = 0;
return true;
} else {
return false;
}
}
static bool int_assign(const ndt::type& tp, char *data, PyObject *obj)
{
#if PY_VERSION_HEX < 0x03000000
if (PyInt_Check(obj)) {
long value = PyInt_AS_LONG(obj);
// Check whether we're assigning to int32 or int64
if (tp.get_type_id() == int64_type_id) {
int64_t *result_ptr = reinterpret_cast<int64_t *>(data);
*result_ptr = static_cast<int64_t>(value);
} else {
# if SIZEOF_LONG > SIZEOF_INT
if (value >= INT_MIN && value <= INT_MAX) {
int32_t *result_ptr = reinterpret_cast<int32_t *>(data);
*result_ptr = static_cast<int32_t>(value);
} else {
// Needs promotion to int64
return false;
}
}
# else
int32_t *result_ptr = reinterpret_cast<int32_t *>(data);
*result_ptr = static_cast<int32_t>(value);
}
# endif
return true;
}
#endif
if (PyLong_Check(obj)) {
PY_LONG_LONG value = PyLong_AsLongLong(obj);
if (value == -1 && PyErr_Occurred()) {
throw runtime_error("error converting int value");
}
if (tp.get_type_id() == int64_type_id) {
int64_t *result_ptr = reinterpret_cast<int64_t *>(data);
*result_ptr = static_cast<int64_t>(value);
} else {
if (value >= INT_MIN && value <= INT_MAX) {
int32_t *result_ptr = reinterpret_cast<int32_t *>(data);
*result_ptr = static_cast<int32_t>(value);
} else {
// This value requires promotion to int64
return false;
}
}
return true;
}
return false;
}
static bool real_assign(char *data, PyObject *obj)
{
double *result_ptr = reinterpret_cast<double *>(data);
if (PyFloat_Check(obj)) {
*result_ptr = PyFloat_AS_DOUBLE(obj);
return true;
#if PY_VERSION_HEX < 0x03000000
} else if (PyInt_Check(obj)) {
*result_ptr = PyInt_AS_LONG(obj);
return true;
#endif
} else if (PyLong_Check(obj)) {
double value = PyLong_AsDouble(obj);
if (value == -1 && PyErr_Occurred()) {
throw runtime_error("error converting int value");
}
*result_ptr = value;
return true;
} else if (obj == Py_True) {
*result_ptr = 1;
return true;
} else if (obj == Py_False) {
*result_ptr = 0;
return true;
} else {
return false;
}
}
static bool complex_assign(char *data, PyObject *obj)
{
complex<double> *result_ptr = reinterpret_cast<complex<double> *>(data);
if (PyComplex_Check(obj)) {
*result_ptr = complex<double>(<API key>(obj),
<API key>(obj));
return true;
} else if (PyFloat_Check(obj)) {
*result_ptr = PyFloat_AS_DOUBLE(obj);
return true;
#if PY_VERSION_HEX < 0x03000000
} else if (PyInt_Check(obj)) {
*result_ptr = PyInt_AS_LONG(obj);
return true;
#endif
} else if (PyLong_Check(obj)) {
double value = PyLong_AsDouble(obj);
if (value == -1 && PyErr_Occurred()) {
throw runtime_error("error converting int value");
}
*result_ptr = value;
return true;
} else if (obj == Py_True) {
*result_ptr = 1;
return true;
} else if (obj == Py_False) {
*result_ptr = 0;
return true;
} else {
return false;
}
}
/**
* Assign a string pyobject to an array element.
*
* \param tp The string type.
* \param arrmeta Arrmeta for the string.
* \param data The data element being assigned to.
* \param obj The Python object containing the value
*
* \return True if the assignment was successful, false if the input type is incompatible.
*/
static bool string_assign(const ndt::type &tp, const char *arrmeta, char *data,
PyObject *obj, const eval::eval_context *ectx)
{
if (PyUnicode_Check(obj)) {
// Go through UTF8 (was accessing the cpython unicode values directly
// before, but on Python 3.3 OS X it didn't work correctly.)
pyobject_ownref utf8(<API key>(obj));
char *s = NULL;
Py_ssize_t len = 0;
if (<API key>(utf8.get(), &s, &len) < 0) {
throw exception();
}
const string_type *st = tp.tcast<string_type>();
st-><API key>(arrmeta, data, s, s + len, ectx);
return true;
}
#if PY_VERSION_HEX < 0x03000000
else if (PyString_Check(obj)) {
char *s = NULL;
intptr_t len = 0;
if (<API key>(obj, &s, &len) < 0) {
throw runtime_error("Error getting string data");
}
const string_type *st = tp.tcast<string_type>();
st-><API key>(arrmeta, data, s, s + len, ectx);
return true;
}
#endif
else {
return false;
}
}
#if PY_VERSION_HEX >= 0x03000000
/**
* Assign a bytes pyobject to an array element.
*
* \param tp The string type.
* \param arrmeta Arrmeta for the type.
* \param data The data element being assigned to.
* \param obj The Python object containing the value
*
* \return True if the assignment was successful, false if the input type is
* incompatible.
*/
static bool bytes_assign(const ndt::type &tp, const char *arrmeta, char *data,
PyObject *obj)
{
if (PyBytes_Check(obj)) {
char *s = NULL;
intptr_t len = 0;
if (<API key>(obj, &s, &len) < 0) {
throw runtime_error("Error getting bytes data");
}
const bytes_type *st = tp.tcast<bytes_type>();
st->set_bytes_data(arrmeta, data, s, s + len);
return true;
}
else {
return false;
}
}
#endif
static void <API key>(
PyObject *obj,
std::vector<intptr_t>& shape,
std::vector<afpd_coordentry>& coord,
afpd_dtype& elem,
dynd::nd::array& arr,
intptr_t current_axis,
const eval::eval_context *ectx)
{
if (PyUnicode_Check(obj)
#if PY_VERSION_HEX < 0x03000000
|| PyString_Check(obj)
#endif
) {
// Special case strings, because they act as sequences too
elem.dtp = ndt::make_string();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
string_assign(elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj, ectx);
return;
}
#if PY_VERSION_HEX >= 0x03000000
if (PyBytes_Check(obj)) {
// Special case bytes, because they act as sequences too
elem.dtp = ndt::make_bytes(1);
arr = allocate_nd_arr(shape, coord, elem, shape.size());
bytes_assign(elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj);
return;
}
#endif
if (PyDict_Check(obj)) {
throw invalid_argument("cannot automatically deduce dynd type to "
"convert dict into nd.array");
}
if (PySequence_Check(obj)) {
Py_ssize_t size = PySequence_Size(obj);
if (size != -1) {
// Add this size to the shape
shape.push_back(size);
// Initialize the data pointer for child elements with the one for
// this element
if (!coord.empty() && current_axis > 0) {
coord[current_axis].data_ptr = coord[current_axis-1].data_ptr;
}
// Process all the elements
for (intptr_t i = 0; i < size; ++i) {
if (!coord.empty()) {
coord[current_axis].coord = i;
}
pyobject_ownref item(PySequence_GetItem(obj, i));
<API key>(item.get(), shape, coord, elem, arr,
current_axis + 1, ectx);
// Advance to the next element. Because the array may be
// dynamically reallocated deeper in the recursive call, we
// need to get the stride from the arrmeta each time.
const <API key> *md =
reinterpret_cast<const <API key> *>(
coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr += md->stride;
}
if (size == 0) {
// When the sequence is zero-sized, we can't
// start deducing the type yet. To start capturing the
// dimensional structure, we make an array of
// int32, while keeping elem.dtp as an uninitialized type.
elem.dtp = ndt::make_type<int32_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
// Make the dtype uninitialized again, to signal we have
// deduced anything yet.
elem.dtp = ndt::type();
}
return;
} else {
// If it doesn't actually check out as a sequence,
// fall through eventually to the iterator check.
PyErr_Clear();
}
}
if (PyBool_Check(obj)) {
elem.dtp = ndt::make_type<dynd_bool>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
*coord[current_axis-1].data_ptr = (obj == Py_True);
return;
}
#if PY_VERSION_HEX < 0x03000000
if (PyInt_Check(obj)) {
long value = PyInt_AS_LONG(obj);
# if SIZEOF_LONG > SIZEOF_INT
// Use a 32-bit int if it fits.
if (value >= INT_MIN && value <= INT_MAX) {
elem.dtp = ndt::make_type<int32_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
int32_t *result_ptr = reinterpret_cast<int32_t *>(coord[current_axis-1].data_ptr);
*result_ptr = static_cast<int32_t>(value);
} else {
elem.dtp = ndt::make_type<int64_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
int64_t *result_ptr = reinterpret_cast<int64_t *>(coord[current_axis-1].data_ptr);
*result_ptr = static_cast<int64_t>(value);
}
# else
elem.dtp = ndt::make_type<int32_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
int32_t *result_ptr = reinterpret_cast<int32_t *>(coord[current_axis-1].data_ptr);
*result_ptr = static_cast<int32_t>(value);
# endif
return;
}
#endif
if (PyLong_Check(obj)) {
PY_LONG_LONG value = PyLong_AsLongLong(obj);
if (value == -1 && PyErr_Occurred()) {
throw runtime_error("error converting int value");
}
// Use a 32-bit int if it fits.
if (value >= INT_MIN && value <= INT_MAX) {
elem.dtp = ndt::make_type<int32_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
int32_t *result_ptr = reinterpret_cast<int32_t *>(coord[current_axis-1].data_ptr);
*result_ptr = static_cast<int32_t>(value);
} else {
elem.dtp = ndt::make_type<int64_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
int64_t *result_ptr = reinterpret_cast<int64_t *>(coord[current_axis-1].data_ptr);
*result_ptr = static_cast<int64_t>(value);
}
return;
}
if (PyFloat_Check(obj)) {
elem.dtp = ndt::make_type<double>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
double *result_ptr = reinterpret_cast<double *>(coord[current_axis-1].data_ptr);
*result_ptr = PyFloat_AS_DOUBLE(obj);
return;
}
if (PyComplex_Check(obj)) {
elem.dtp = ndt::make_type<complex<double> >();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
complex<double> *result_ptr = reinterpret_cast<complex<double> *>(coord[current_axis-1].data_ptr);
*result_ptr = complex<double>(<API key>(obj),
<API key>(obj));
return;
}
// Check if it's an iterator
{
PyObject *iter = PyObject_GetIter(obj);
if (iter != NULL) {
pyobject_ownref iter_owner(iter);
// Indicate a var dim.
shape.push_back(-1);
PyObject *item = PyIter_Next(iter);
if (item != NULL) {
intptr_t i = 0;
while (item != NULL) {
pyobject_ownref item_ownref(item);
if (!coord.empty()) {
coord[current_axis].coord = i;
char *data_ptr = (current_axis > 0) ? coord[current_axis-1].data_ptr
: arr.<API key>();
if (coord[current_axis].coord >= coord[current_axis].reserved_size) {
// Increase the reserved capacity if needed
coord[current_axis].reserved_size *= 2;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
data_ptr, coord[current_axis].reserved_size);
}
// Set the data pointer for the child element
var_dim_type_data *d = reinterpret_cast<var_dim_type_data *>(data_ptr);
const <API key> *md =
reinterpret_cast<const <API key> *>(coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr = d->begin + i * md->stride;
}
<API key>(item, shape, coord, elem, arr,
current_axis + 1, ectx);
item = PyIter_Next(iter);
++i;
}
if (PyErr_Occurred()) {
// Propagate any error
throw exception();
}
// Shrink the var element to fit
char *data_ptr = (current_axis > 0) ? coord[current_axis-1].data_ptr
: arr.<API key>();
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
data_ptr, i);
return;
} else {
// Because this iterator's sequence is zero-sized, we can't
// start deducing the type yet. To start capturing the
// dimensional structure, we make an array of
// int32, while keeping elem.dtp as an uninitialized type.
elem.dtp = ndt::make_type<int32_t>();
arr = allocate_nd_arr(shape, coord, elem, shape.size());
// Make the dtype uninitialized again, to signal we have
// deduced anything yet.
elem.dtp = ndt::type();
// Set it to a zero-sized var element
char *data_ptr = (current_axis > 0) ? coord[current_axis-1].data_ptr
: arr.<API key>();
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr, data_ptr, 0);
return;
}
} else {
if (<API key>(PyExc_TypeError)) {
// A TypeError indicates that the object doesn't support
// the iterator protocol
PyErr_Clear();
} else {
// Propagate the error
throw exception();
}
}
}
stringstream ss;
ss << "Unable to convert object of type ";
pyobject_ownref typestr(PyObject_Str((PyObject *)Py_TYPE(obj)));
ss << pystring_as_string(typestr.get());
ss << " to a dynd array";
throw runtime_error(ss.str());
}
/**
* Converts a Python object into an nd::array, dynamically
* reallocating the result with a new type if a new value
* requires it.
*
* When called initially, `coord` and `shape`should be empty, and
* `arr` should be a NULL nd::array, and current_axis should be 0.
*
* A dimension will start as `strided` if the first element
* encountered follows the sequence protocol, so its size is known.
* It will start as `var` if the first element encountered follows
* the iterator protocol.
*
* If a dimension is `strided`, and either a sequence of a different
* size, or an iterator is encountered, that dimension will be
* promoted to `var.
*
* \param obj The PyObject to convert to an nd::array.
* \param shape A vector, same size as coord, of the array shape. Negative
* entries for var dimensions
* \param coord A vector of afpd_coordentry. This tracks the current
* coordinate being allocated and for var
* dimensions, the amount of reserved space.
* \param elem Data for tracking the dtype elements. If no element has been
* seen yet, its values are NULL. Note that an array may be allocated,
* with zero-size arrays having some structure, before encountering
* an actual element.
* \param arr The nd::array currently being populated. If a new type
* is encountered, this will be updated dynamically.
* \param current_axis The axis within shape being processed at
* the current level of recursion.
*/
static void <API key>(
PyObject *obj,
std::vector<intptr_t>& shape,
std::vector<afpd_coordentry>& coord,
afpd_dtype& elem,
dynd::nd::array& arr,
intptr_t current_axis,
const eval::eval_context *ectx)
{
if (arr.is_null()) {
// If the arr is NULL, we're doing the first recursion determining
// number of dimensions, etc.
<API key>(obj, shape, coord, elem, arr, current_axis, ectx);
return;
}
// If it's the dtype, check for scalars
if (current_axis == (intptr_t)shape.size()) {
switch (elem.dtp.get_kind()) {
case bool_kind:
if (!bool_assign(coord[current_axis-1].data_ptr, obj)) {
<API key>(shape, coord, elem, arr,
<API key>(obj));
<API key>(
elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj, ectx);
}
return;
case int_kind:
if (!int_assign(elem.dtp, coord[current_axis-1].data_ptr, obj)) {
<API key>(shape, coord, elem, arr,
<API key>(obj));
<API key>(
elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj, ectx);
}
return;
case real_kind:
if (!real_assign(coord[current_axis-1].data_ptr, obj)) {
<API key>(shape, coord, elem, arr,
<API key>(obj));
<API key>(
elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj, ectx);
}
return;
case complex_kind:
if (!complex_assign(coord[current_axis-1].data_ptr, obj)) {
<API key>(shape, coord, elem, arr,
<API key>(obj));
<API key>(
elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj, ectx);
}
return;
case string_kind:
if (!string_assign(elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr, obj,
ectx)) {
throw runtime_error("TODO: Handle string type promotion");
}
return;
#if PY_VERSION_HEX >= 0x03000000
case bytes_kind:
if (!bytes_assign(elem.dtp, elem.arrmeta_ptr,
coord[current_axis-1].data_ptr, obj)) {
throw runtime_error("TODO: Handle bytes type promotion");
}
return;
#endif
case void_kind:
// In this case, zero-sized dimension were encountered before
// an actual element from which to deduce a type.
<API key>(shape, coord, elem, arr,
<API key>(obj));
<API key>(elem.dtp, elem.arrmeta_ptr,
coord[current_axis - 1].data_ptr,
obj, ectx);
return;
default:
throw runtime_error("internal error: unexpected type in recursive pyobject to dynd array conversion");
}
}
// Special case error for string and bytes, because they
// support the sequence and iterator protocols, but we don't
// want them to end up as dimensions.
if (PyUnicode_Check(obj) ||
#if PY_VERSION_HEX >= 0x03000000
PyBytes_Check(obj)) {
#else
PyString_Check(obj)) {
#endif
stringstream ss;
ss << "Ragged dimension encountered, type ";
pyobject_ownref typestr(PyObject_Str((PyObject *)Py_TYPE(obj)));
ss << pystring_as_string(typestr.get());
ss << " after a dimension type while converting to a dynd array";
throw runtime_error(ss.str());
}
if (PyDict_Check(obj)) {
throw invalid_argument("cannot automatically deduce dynd type to "
"convert dict into nd.array");
}
// We're processing a dimension
if (shape[current_axis] >= 0) {
// It's a strided dimension
if (PySequence_Check(obj)) {
Py_ssize_t size = PySequence_Size(obj);
if (size != -1) {
// The object supports the sequence protocol, so use it
if (size != shape[current_axis]) {
// Promote the current axis from strided to var
promote_nd_arr_dim(shape, coord, elem, arr, current_axis, false);
// Re-invoke this call, this time triggering the var dimension code
<API key>(obj, shape, coord, elem, arr,
current_axis, ectx);
return;
}
// In the strided case, the initial data pointer is the same
// as the parent's. Note that for current_axis==0, arr.is_null()
// is guaranteed to be true, so it is impossible to get here.
coord[current_axis].data_ptr = coord[current_axis-1].data_ptr;
// Process all the elements
for (intptr_t i = 0; i < size; ++i) {
coord[current_axis].coord = i;
pyobject_ownref item(PySequence_GetItem(obj, i));
<API key>(item.get(), shape, coord, elem, arr,
current_axis + 1, ectx);
// Advance to the next element. Because the array may be
// dynamically reallocated deeper in the recursive call, we
// need to get the stride from the arrmeta each time.
const <API key> *md =
reinterpret_cast<const <API key> *>(coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr += md->stride;
}
return;
} else {
// If it doesn't actually check out as a sequence,
// fall through to the iterator check.
PyErr_Clear();
}
}
// It wasn't a sequence, check if it's an iterator
PyObject *iter = PyObject_GetIter(obj);
if (iter != NULL) {
pyobject_ownref iter_owner(iter);
// In the strided case, the initial data pointer is the same
// as the parent's. Note that for current_axis==0, arr.is_null()
// is guaranteed to be true, so it is impossible to get here.
coord[current_axis].data_ptr = coord[current_axis-1].data_ptr;
// Process all the elements
Py_ssize_t size = shape[current_axis];
for (intptr_t i = 0; i < size; ++i) {
coord[current_axis].coord = i;
PyObject *item = PyIter_Next(iter);
if (item == NULL) {
if (PyErr_Occurred()) {
// Propagate any error
throw exception();
}
// Promote the current axis from strided to var
promote_nd_arr_dim(shape, coord, elem, arr, current_axis, true);
// Shrink the var dim element to fit
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
coord[current_axis-1].data_ptr, i);
return;
}
pyobject_ownref item_ownref(item);
<API key>(item, shape, coord, elem, arr,
current_axis + 1, ectx);
// Advance to the next element. Because the array may be
// dynamically reallocated deeper in the recursive call, we
// need to get the stride from the arrmeta each time.
const <API key> *md =
reinterpret_cast<const <API key> *>(coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr += md->stride;
}
// Make sure the iterator has no more elements. If it does, we must
// promote the dimension to var, then continue copying
PyObject *item = PyIter_Next(iter);
if (item != NULL) {
pyobject_ownref item_ownref_outer(item);
// Promote the current axis from strided to var
promote_nd_arr_dim(shape, coord, elem, arr, current_axis, true);
// Give the var dim some capacity so we can continue processing the iterator
coord[current_axis].reserved_size =
std::max(size*2, <API key>);
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
coord[current_axis-1].data_ptr,
coord[current_axis].reserved_size);
item_ownref_outer.release();
intptr_t i = size;
while (item != NULL) {
pyobject_ownref item_ownref(item);
coord[current_axis].coord = i;
char *data_ptr = coord[current_axis-1].data_ptr;
if (coord[current_axis].coord >= coord[current_axis].reserved_size) {
// Increase the reserved capacity if needed
coord[current_axis].reserved_size *= 2;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
data_ptr, coord[current_axis].reserved_size);
}
// Set the data pointer for the child element
var_dim_type_data *d = reinterpret_cast<var_dim_type_data *>(data_ptr);
const <API key> *md =
reinterpret_cast<const <API key> *>(coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr = d->begin + i * md->stride;
<API key>(item, shape, coord, elem, arr,
current_axis + 1, ectx);
item = PyIter_Next(iter);
++i;
}
if (PyErr_Occurred()) {
// Propagate any error
throw exception();
}
// Shrink the var element to fit
char *data_ptr = coord[current_axis-1].data_ptr;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
data_ptr, i);
return;
} else if (PyErr_Occurred()) {
// Propagate any error
throw exception();
}
return;
}
} else {
// It's a var dimension
if (PySequence_Check(obj)) {
Py_ssize_t size = PySequence_Size(obj);
if (size != -1) {
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
coord[current_axis-1].data_ptr, size);
coord[current_axis].reserved_size = size;
// Process all the elements
for (intptr_t i = 0; i < size; ++i) {
coord[current_axis].coord = i;
pyobject_ownref item(PySequence_GetItem(obj, i));
// Set the data pointer for the child element. We must
// re-retrieve from `coord` each time, because the recursive
// call could reallocate the destination array.
var_dim_type_data *d = reinterpret_cast<var_dim_type_data *>(coord[current_axis-1].data_ptr);
const <API key> *md =
reinterpret_cast<const <API key> *>(coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr = d->begin + i * md->stride;
<API key>(item, shape, coord, elem, arr,
current_axis + 1, ectx);
}
return;
} else {
// If it doesn't actually check out as a sequence,
// fall through to the iterator check.
PyErr_Clear();
}
}
PyObject *iter = PyObject_GetIter(obj);
if (iter != NULL) {
pyobject_ownref iter_owner(iter);
PyObject *item = PyIter_Next(iter);
if (item != NULL) {
pyobject_ownref item_ownref_outer(item);
intptr_t i = 0;
coord[current_axis].reserved_size = <API key>;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
coord[current_axis-1].data_ptr,
coord[current_axis].reserved_size);
item_ownref_outer.release();
while (item != NULL) {
pyobject_ownref item_ownref(item);
coord[current_axis].coord = i;
char *data_ptr = coord[current_axis-1].data_ptr;
if (coord[current_axis].coord >= coord[current_axis].reserved_size) {
// Increase the reserved capacity if needed
coord[current_axis].reserved_size *= 2;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
data_ptr, coord[current_axis].reserved_size);
}
// Set the data pointer for the child element
var_dim_type_data *d = reinterpret_cast<var_dim_type_data *>(data_ptr);
const <API key> *md =
reinterpret_cast<const <API key> *>(coord[current_axis].arrmeta_ptr);
coord[current_axis].data_ptr = d->begin + i * md->stride;
<API key>(item, shape, coord, elem, arr,
current_axis + 1, ectx);
item = PyIter_Next(iter);
++i;
}
if (PyErr_Occurred()) {
// Propagate any error
throw exception();
}
// Shrink the var element to fit
char *data_ptr = coord[current_axis-1].data_ptr;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr,
data_ptr, i);
return;
} else {
// Set it to a zero-sized var element
char *data_ptr = coord[current_axis-1].data_ptr;
ndt::<API key>(coord[current_axis].tp,
coord[current_axis].arrmeta_ptr, data_ptr, 0);
return;
}
} else {
if (<API key>(PyExc_TypeError)) {
// A TypeError indicates that the object doesn't support
// the iterator protocol
PyErr_Clear();
} else {
// Propagate the error
throw exception();
}
}
}
// The object supported neither the sequence nor the iterator
// protocol, so report an error.
stringstream ss;
ss << "Ragged dimension encountered, type ";
pyobject_ownref typestr(PyObject_Str((PyObject *)Py_TYPE(obj)));
ss << pystring_as_string(typestr.get());
ss << " after a dimension type while converting to a dynd array";
throw runtime_error(ss.str());
}
dynd::nd::array pydynd::<API key>(PyObject *obj,
const eval::eval_context *ectx)
{
std::vector<afpd_coordentry> coord;
std::vector<intptr_t> shape;
afpd_dtype elem;
nd::array arr;
memset(&elem, 0, sizeof(elem));
<API key>(obj, shape, coord, elem, arr, 0, ectx);
// Finalize any variable-sized buffers, etc
if (!arr.get_type().is_builtin()) {
arr.get_type().extended()-><API key>(arr.get_arrmeta());
}
// As a special case, convert the outer dimension from var to strided
if (arr.get_type().get_type_id() == var_dim_type_id) {
arr = arr(irange());
}
return arr;
} |
#!/bin/bash
ROOT=$(dirname $0)
# Get RKQC path
export RKQC_PATH=${ROOT}/rkqc
if [ $(echo $PATH | grep ${RKQC_PATH} | wc -l) -eq 0 ]; then
export PATH=$PATH:$RKQC_PATH
fi
function show_help {
echo "Usage: $0 [-hv] [-rqfRTFckdso] [-l #] [-P #] [-D <pass_name>] <filename>.scaffold [args]*"
echo " -r Generate resource estimate (default)"
echo " -q Generate QASM"
echo " -f Generate flattened QASM"
echo " -b Generate OpenQASM"
echo " -R Enable rotation decomposition"
echo " -T Enable Toffoli decomposition"
echo " -l Levels of recursion to run (default=1)"
echo " -P Set precision of rotation decomposition in decimal digits (default=10)"
echo " -F Force running all steps"
echo " -c Clean all files (no other actions)"
echo " -k Keep all intermediate files (default only keeps specified output,"
echo " but requires recompilation for any new output)"
echo " -d Dry-run; show all commands to be run, but do not execute"
echo " -D Debug named pass, use SCAFFOLD for all"
echo " -s Generate QX Simulator input file"
echo " -o Generate optimized QASM"
echo " -v Show current Scaffold version information"
}
function show_version {
echo "Scaffold - Release 5.0 (April 23, 2020)"
}
# Parse opts
OPTIND=1 # Reset in case getopts has been used previously in the shell.
rkqc=0
clean=0
dryrun=""
force=0
coptimization=0
purge=1
res=0
rot=0
toff=0
flat=0
openqasm=0
qc=0
precision=4
targets=""
optimize=0
debug_passes=""
while getopts "h?vcdfbsFkqroTRD:l:P:" opt; do
case "$opt" in
h|\?)
show_help
exit 0
;;
v)
show_version
exit 0
;;
c) clean=1
;;
d) dryrun="--dry-run"
;;
F) force=1
;;
f) flat=1
;;
b) openqasm=1
;;
k) purge=0
;;
O) coptimization=1
;;
q) targets="${targets} qasm"
;;
r) res=1
;;
R) rot=1
;;
T) toff=1
;;
s) qc=1
;;
D) debug_val=$(echo "${OPTARG}" | tr a-z A-Z)
export "DEBUG_${debug_val}=1"
;;
o) optimize=1
;;
l) targets="${targets} SQCT_LEVELS=${OPTARG}"
;;
P) precision=${OPTARG}
esac
done
shift $((OPTIND-1))
[ "$1" = "--" ] && shift
if [ ${flat} -eq 1 ]; then
targets="${targets} flat"
fi
if [ ${openqasm} -eq 1 ]; then
targets="${targets} openqasm"
fi
if [ ${qc} -eq 1 ]; then
targets="${targets} qc"
fi
if [ ${optimize} -eq 1 ]; then
targets="${targets} optimize"
fi
# Put resources at the end so it is easy to read
if [ ${res} -eq 1 ]; then
targets="${targets} resources"
fi
# Force first
if [ ${force} -eq 1 ]; then
targets="clean ${targets}"
fi
# Default to resource estimate
if [ -z "${targets}" ]; then
targets="resources"
fi
# Don't purge until done
if [ ${purge} -eq 1 ]; then
targets="${targets} purge"
fi
echo ${1}
if [ $# -lt 1 ]; then
echo "Error: Missing filename argument"
show_help
exit 1
fi
filename=${1}
if [ ! -e ${filename} ]; then
echo "${filename}: file not found"
show_help
exit 1
fi
shift
expresion=""
arg_num=1
while [ "${1}" != "" ]; do
if [ $arg_num != 1 ]; then
expression="${expression}; "
fi
expression="${expression}s/argv\[${arg_num}\]/${1}/g"
arg_num=${arg_num}+1
shift
done
dir="$(dirname ${filename})/"
file=$(basename ${filename} .scaffold)
cfile="${file}.*"
echo "file: $file"
if [ "${expression}" != "" ]; then
sed -E -e "${expression}" "${filename}" > "${file}_args.scaffold"
filename="${file}_args.scaffold"
fi
if [ $(egrep '^rkqc.*{\s*' ${filename} | wc -l) -gt 0 ]; then
rkqc=1
toff=1
fi
if [ ${clean} -eq 1 ]; then
make -f $ROOT/scaffold/Scaffold.makefile ${dryrun} ROOT=$ROOT DIRNAME=${dir} FILENAME=${filename} FILE=${file} CFILE=${cfile} clean
exit
fi
make -f $ROOT/scaffold/Scaffold.makefile ${dryrun} ROOT=$ROOT DIRNAME=${dir} FILENAME=${filename} FILE=${file} CFILE=${cfile} TOFF=${toff} RKQC=${rkqc} COPTIMIZATION=${coptimization} ROTATIONS=${rot} PRECISION=${precision} OPTIMIZE=${optimize} ${targets}
exit 0 |
<?hh // partial
// Because of PSR HTTP Message
namespace Titon\Http\Server;
use Psr\Http\Message\StreamableInterface;
use Titon\Http\Http;
use Titon\Http\Stream\MemoryStream;
use Titon\Type\Xml;
/**
* Output XML as the response by converting any type of resource to XML.
*
* @package Titon\Http\Server
*/
class XmlResponse extends Response {
/**
* Set the body, status code, and optional XML root node.
* Convert the body to XML before passing along.
*
* @param mixed $body
* @param int $status
* @param string $root
*/
public function __construct(mixed $body = null, int $status = Http::OK, string $root = 'root') {
if (!$body instanceof StreamableInterface) {
$body = new MemoryStream( Xml::from($body, $root)->toString() );
}
parent::__construct($body, $status);
}
/**
* Set the content type and length before sending.
*
* @return string
*/
public function send(): string {
$this->contentType('xml');
if ($body = $this->getBody()) {
$this->contentLength($body->getSize());
}
return parent::send();
}
} |
(function() {
var G = glocal.Promise;
console.log('main context : ', G.context)
G.context.test = true;
G.resolve('tututu')
.delay(100)
.glocalize('shloup', true)
//.slog("slog 1 : ")
.clog()
//.elog()
//.delay(500)
.glocalize('br', 'fe')
//.slog("slog 2 : ")
.clog()
.elog()
//.elog()
G.resolve('glup')
.glocalize('bloupi', 'a')
//.slog("slog 3 : ")
.clog()
.delay(300)
.then(function(s) {
return G.resolve(45678)
//.delay(100)
.clog()
.glocalize("ho", true)
.clog()
//.then(function(){ throw new Error("hello"); })
})
.glocalize('fleu', 'y')
//.slog("slog 4 : ")
.clog()
.then(function(s) {
return G.resolve(true)
.delay(100)
.clog()
.glocalize("haaaa", false)
.clog()
.then(function(s) {
return G.resolve("roooooo")
//.delay(100)
.clog().glocalize("hi", false).clog("hi");
})
.clog("hi")
})
.clog()
.log("end log")
.elog()
console.log('main context end : ', G.context)
/*
G.resolve("bloutch")
.glocalize("zooooo", "floupi")
.delay(1000)
.then(function(s){
console.log("g : ", s, G.context);
}, function(e){
console.log("error : ", e);
});
*/
}); |
title: "Ansible for the impatient sysadmin / (part 2)"
date: 2018-08-08T19:05:38+02:00
draft: true
featured_image: "/images/ansible-2.png"
description: "A no fluff guide to start using Ansible for automation. Part 2 - Using Ansible to execute ad-hoc commands on servers"
toc: true
tags: ["Ansible", "sysadmin", "Automation", "SSH"]
Running commands on servers - one after another
Running commands on servers - all at once
Dealing with stdout & stderr
Logging
Copying files to servers
See you in part -3 |
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
if (!Array.prototype.reduce) {
var toObject = require('./_toObject');
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (typeof fun !== "function") {
throw new TypeError();
}
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1) {
throw new TypeError('reduce of empty array with no initial value');
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError('reduce of empty array with no initial value');
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, self);
}
}
return result;
};
} |
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/select.h>
#include <errno.h>
#include <syslog.h>
#include <string.h>
#include "smbftpd.h"
/*
* Get value from set by username and transfer the value into
* bps (bits per second).
*/
off_t <API key>(struct opt_set *set, const char *user)
{
off_t size;
const char *value;
value = set_get_value(set, user);
if (NULL == value) {
return 0;
}
size = 1024 * strtol(value, (char **)NULL, 10);
return size;
}
/* This function is used to block/unblock signale in <API key>()
* to avoid signal received when select.
*/
static void <API key>(int block)
{
static sigset_t sig_set;
if (block) {
sigemptyset(&sig_set);
sigaddset(&sig_set, SIGCHLD);
sigaddset(&sig_set, SIGINT);
sigaddset(&sig_set, SIGQUIT);
sigaddset(&sig_set, SIGURG);
sigaddset(&sig_set, SIGIO);
sigaddset(&sig_set, SIGBUS);
sigaddset(&sig_set, SIGHUP);
while (sigprocmask(SIG_BLOCK, &sig_set, NULL) < 0) {
if (errno == EINTR) {
continue;
}
break;
}
} else {
while (sigprocmask(SIG_UNBLOCK, &sig_set, NULL) < 0) {
if (errno == EINTR) {
continue;
}
break;
}
}
return;
}
/* Returns the difference, in milliseconds, between the given timeval and
* now.
*/
static long elapsed_time_count(struct timeval *since)
{
struct timeval now;
gettimeofday(&now, NULL);
return (((now.tv_sec - since->tv_sec) * 1000L) +
((now.tv_usec - since->tv_usec) / 1000L));
}
/**
* Delay download/upload task by count the speed and sleep for a
* while if needed.
*
* @param byte_count
* @param tvsince
* @param rate
*/
void <API key>(off_t byte_count, struct timeval *tvsince, off_t rate)
{
time_t ideal_time = 0, elapsed_time = 0;
/* Calculate the time interval since the transfer of data started. */
elapsed_time = elapsed_time_count(tvsince);
ideal_time = byte_count * 1000L / rate;
if (ideal_time > elapsed_time) {
struct timeval tvdelay;
/* Setup for the select. We use select() instead of usleep() because it
* seems to be far more portable across platforms.
*
* IdealTime and ElapsedTime are in milleconds, but tv_usec will be microseconds,
* so be sure to convert properly.
*/
tvdelay.tv_usec = (ideal_time - elapsed_time) * 1000;
tvdelay.tv_sec = tvdelay.tv_usec / 1000000L;
tvdelay.tv_usec = tvdelay.tv_usec % 1000000L;
/* No interruptions, please... */
<API key>(1);
if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
syslog(LOG_ERR, "warning: unable to throttle bandwidth: %s",
strerror(errno));
<API key>(0);
}
return;
} |
using System;
using Moq;
using NUnit.Framework;
using XenAdmin.Diagnostics.Hotfixing;
using XenAPI;
namespace XenAdminTests.UnitTests.Diagnostics
{
[TestFixture, Category(TestCategories.SmokeTest)]
public class HotFixFactoryTests : <API key>
{
private const string id = "test";
public HotFixFactoryTests() : base(id){}
private readonly HotfixFactory factory = new HotfixFactory();
[TearDown]
public void TearDownPerTest()
{
ObjectManager.ClearXenObjects(id);
ObjectManager.RefreshCache(id);
}
[Test]
public void <API key>()
{
string[] enumNames = Enum.GetNames(typeof (HotfixFactory.<API key>));
Array.Sort(enumNames);
string[] expectedNames = new []{"Boston", "SanibelToClearwater", "Creedence", "Dundee"};
Array.Sort(expectedNames);
CollectionAssert.AreEqual(expectedNames, enumNames, "Expected contents of <API key> enum");
}
[Test]
public void <API key>()
{
Assert.AreEqual("<API key>;<API key>",
factory.Hotfix(HotfixFactory.<API key>.Boston).UUID,
"Boston UUID lookup from enum");
Assert.AreEqual("<API key>",
factory.Hotfix(HotfixFactory.<API key>.SanibelToClearwater).UUID,
"SanibelToClearwater UUID lookup from enum");
Assert.AreEqual("<API key> ",
factory.Hotfix(HotfixFactory.<API key>.Creedence).UUID,
"Creedence UUID lookup from enum");
Assert.AreEqual("<API key>",
factory.Hotfix(HotfixFactory.<API key>.Dundee).UUID,
"Dundee UUID lookup from enum");
}
[Test]
public void <API key>()
{
Assert.AreEqual("XS60E001;RPU001",
factory.Hotfix(HotfixFactory.<API key>.Boston).Filename,
"Boston Filename lookup from enum");
Assert.AreEqual("RPU001",
factory.Hotfix(HotfixFactory.<API key>.SanibelToClearwater).Filename,
"SanibelToClearwater Filename lookup from enum");
Assert.AreEqual("RPU002",
factory.Hotfix(HotfixFactory.<API key>.Creedence).Filename,
"Creedence Filename lookup from enum");
Assert.AreEqual("RPU003",
factory.Hotfix(HotfixFactory.<API key>.Dundee).Filename,
"Dundee Filename lookup from enum");
}
[Test]
[TestCase("2.1.1", Description = "Ely")]
[TestCase("9999.9999.9999", Description = "Future")]
public void <API key>(string platformVersion)
{
Mock<Host> host = ObjectManager.NewXenObject<Host>(id);
host.Setup(h => h.PlatformVersion).Returns(platformVersion);
Assert.IsNull(factory.Hotfix(host.Object));
}
[Test]
[TestCase("6.0.2", "RPU001", Description = "Sanibel")]
[TestCase("6.0.0", "XS60E001;RPU001", Description = "Boston")]
public void <API key>(string productVersion, string filenames)
{
Mock<Host> host = ObjectManager.NewXenObject<Host>(id);
host.Setup(h => h.ProductVersion).Returns(productVersion);
Assert.That(filenames, Is.EqualTo(factory.Hotfix(host.Object).Filename));
}
[Test]
[TestCase("2.1.1", Description = "Ely", Result = false)]
[TestCase("2.0.0", Description = "Dundee", Result = true)]
[TestCase("1.9.0", Description = "Creedence", Result = true)]
[TestCase("1.8.0", Description = "Clearwater", Result = true)]
[TestCase("1.6.10", Description = "Tampa", Result = true)]
[TestCase("9999.9999.9999", Description = "Future", Result = false)]
public bool <API key>(string version)
{
Mock<Host> host = ObjectManager.NewXenObject<Host>(id);
host.Setup(h => h.PlatformVersion).Returns(version);
return factory.IsHotfixRequired(host.Object);
}
[Test]
[TestCase("6.0.2", Description = "Sanibel", Result = true)]
[TestCase("6.0.0", Description = "Boston", Result = true)]
public bool <API key>(string productVersion)
{
Mock<Host> host = ObjectManager.NewXenObject<Host>(id);
host.Setup(h => h.ProductVersion).Returns(productVersion);
return factory.IsHotfixRequired(host.Object);
}
}
} |
/**
* Members view model
*/
var app = app || {};
app.on2tClients = (function () {
'use strict'
var locals, mapOptions;
// map center
var center = new google.maps.LatLng(40.589500, -8.683542);
// marker position
var factory = new google.maps.LatLng(40.589500, -8.683542);
var clientViewModel = (function () {
var properties
var clientClassModel = {
fields: {
place: {
field: 'Place',
defaultValue: ''
},
url: {
field: 'Website',
defaultValue: 'www.on2See.com'
},
marker: {
field: 'Location',
defaultValue: []
},
text: {
field: 'Description',
defaultValue: 'Empty'
}
}
};
var clientDataSource = new kendo.data.DataSource({
type: 'everlive',
schema: {
model: clientModel
},
transport: {
typeName: 'Places'
}
});
var itemViewModel = kendo.data.ObservableObject.extend({
attribute: null,
isViewInitialized: false,
markers: [],
details: [],
hideView: false,
itemMarker: function (marker, text) {
var itemPosition = new google.maps.LatLng(marker.latitude, marker.longitude);
marker.Mark = new google.maps.Marker({
map: map,
position: position,
icon: {
url: 'styles/images/icon.png',
anchor: new google.maps.Point(20, 38),
scaledSize: new google.maps.Size(40, 40)
}
});
google.maps.event.addListener(marker.Mark, 'click', function () {
infoWindow.setContent(text);
infoWindow.open(map, marker.Mark);
});
},
});
return {
init: function () {
//common variables
if (typeof google === "undefined") {
return;
}
infoWindow = new google.maps.InfoWindow();
//create empty LatLngBounds object
allBounds = new google.maps.LatLngBounds();
var pos, userCords, streetView, tempPlaceHolder = [];
var mapOptions = {
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
},
show: function () {
//resize the map in case the orientation has been changed
google.maps.event.trigger(map, "resize");
},
hide: function () {
//hide loading mask if user changed the tab as it is only relevant to location tab
kendo.mobile.application.hideLoading();
},
viewModel: new clientViewModel(),
onSelected: function (e) {
}
};
});
return {
clientViewModel: clientViewModel,
initClients: function () {
var mapOptions = {
center: center,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("on2tmap-canvas"), mapOptions);
// InfoWindow content
var content = '<div id="iw-container">' +
'<div class="iw-title">Porcelain Factory of Vista Alegre</div>' +
'<div class="iw-content">' +
'<div class="iw-subTitle">History</div>' +
'<img src="images/vistalegre.jpg" alt="Porcelain Factory of Vista Alegre" height="115" width="83">' +
'<p>Founded in 1824, the Porcelain Factory of Vista Alegre was the first industrial unit dedicated to porcelain production in Portugal. For the foundation and success of this risky industrial development was crucial the spirit of persistence of its founder, José Ferreira Pinto Basto. Leading figure in Portuguese society of the nineteenth century farm owner, daring dealer, wisely incorporated the liberal ideas of the century, having become "the first example of free enterprise" in Portugal.</p>' +
'<div class="iw-subTitle">Contacts</div>' +
'<p>VISTA ALEGRE ATLANTIS, SA<br>3830-292 Ílhavo - Portugal<br>' +
'<br>Phone. +351 234 320 600<br>e-mail: geral@vaa.pt<br>www: www.myvistaalegre.com</p>' +
'</div>' +
'<div class="iw-bottom-gradient"></div>' +
'</div>';
// A new Info Window is created and set content
var infowindow = new google.maps.InfoWindow({
content: content,
// Assign a maximum value for the width of the infowindow allows
// greater control over the various content elements
maxWidth: 350
});
// marker options
var marker = new google.maps.Marker({
position: factory,
map: map,
title: "Fábrica de Porcelana da Vista Alegre"
});
// This event expects a click on a marker
// When this event is fired the Info Window is opened.
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
});
// START INFOWINDOW CUSTOMIZE.
// The google.maps.event.addListener() event expects
// the creation of the infowindow HTML structure 'domready'
// and before the opening of the infowindow, defined styles are applied.
google.maps.event.addListener(infowindow, 'domready', function () {
// Reference to the DIV that wraps the bottom of infowindow
var iwOuter = $('.gm-style-iw');
/* Since this div is in a position prior to .gm-div style-iw.
* We use jQuery and create a iwBackground variable,
* and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
*/
var iwBackground = iwOuter.prev();
// Removes background shadow DIV
iwBackground.children(':nth-child(2)').css({ 'display': 'none' });
// Removes white background DIV
iwBackground.children(':nth-child(4)').css({ 'display': 'none' });
// Moves the infowindow 115px to the right.
iwOuter.parent().parent().css({ left: '115px' });
// Moves the shadow of the arrow 76px to the left margin.
iwBackground.children(':nth-child(1)').attr('style', function (i, s) { return s + 'left: 76px !important;' });
// Moves the arrow 76px to the left margin.
iwBackground.children(':nth-child(3)').attr('style', function (i, s) { return s + 'left: 76px !important;' });
// Changes the desired tail shadow color.
iwBackground.children(':nth-child(3)').find('div').children().css({ 'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index': '1' });
// Reference to the div that groups the close button elements.
var iwCloseBtn = iwOuter.next();
// Apply the desired effect to the close button
iwCloseBtn.css({ opacity: '1', right: '38px', top: '3px', border: '7px solid #48b5e9', 'border-radius': '13px', 'box-shadow': '0 0 5px #3990B9' });
// If the content of infowindow not exceed the set maximum height, then the gradient is removed.
if ($('.iw-content').height() < 140) {
$('.iw-bottom-gradient').css({ display: 'none' });
}
// The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
iwCloseBtn.mouseout(function () {
$(this).css({ opacity: '1' });
});
});
},
showClients: function () {
}
}
}()); |
#ifndef <API key>
#define <API key>
#include "game/Propeller.h"
#include "editorbackend/CSharp/CSharpInstance.h"
#include "engine/sys/GameWindow.h"
<API key>(editor, <API key>);
namespace editor {
// separated window to run the game in
class GameView : public CSharpInstance
{
private:
PrimaryGameInstance gameInstance;
engine::sys::GameWindow *window;
public:
bool init();
void uninit();
void startup(intptr_t ptr);
void update();
};
}
#endif |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using nScanty.Data;
namespace nScanty
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
public class MvcApplication : System.Web.HttpApplication
{
public static void <API key>(<API key> filters)
{
filters.Add(new <API key>());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"RSS",
"rss",
new {controller = "Home", action = "Rss"});
routes.MapRoute(
"Post",
"Home/{year}/{month}/{slug}",
new {controller = "Home", action = "Post" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
<API key>(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
RegisterUser();
//RouteDebug.RouteDebugger.<API key>(RouteTable.Routes);
}
private static void RegisterUser()
{
var repo = new UserRepository();
var username = <API key>.AppSettings["user"];
var user = repo.GetUser(username);
if (null != user) return;
var hashed<API key>.AppSettings["hashedPassword"];
if (!string.IsNullOrEmpty(hashedPassword))
{
repo.<API key>(username, hashedPassword);
}
else
{
var <API key>.AppSettings["password"];
repo.CreateUser(username, password);
}
}
}
} |
#ifndef MUTEX_H
#define MUTEX_H
#include <string.h>
#include <limits.h>
#if defined WIN32 || defined _WIN32 || defined WINCE
#ifndef _WIN32_WINNT // This is needed for the declaration of <API key> in winbase.h with Visual Studio 2005 (and older?)
#define _WIN32_WINNT 0x0500
#endif
#include <windows.h>
#undef small
#undef min
#undef max
#undef abs
#include <tchar.h>
#if defined _MSC_VER
#if _MSC_VER >= 1400
#include <intrin.h>
#endif
#endif
#else
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#endif
#include <stdarg.h>
#if defined __linux__ || defined __APPLE__
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
//// exchange-add operation for atomic operations on reference counters ///////
#if defined __INTEL_COMPILER && !(defined WIN32 || defined _WIN32) // atomic increment on the linux version of the Intel(tm) compiler
#define CV_XADD(addr,delta) <API key>(const_cast<void*>(reinterpret_cast<volatile void*>(addr)), delta)
#elif defined __GNUC__
#if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__
#ifdef __ATOMIC_SEQ_CST
#define CV_XADD(addr, delta) <API key>((_Atomic(int)*)(addr), (delta), __ATOMIC_SEQ_CST)
#else
#define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), (delta), 5)
#endif
#elif __GNUC__*10 + __GNUC_MINOR__ >= 42
#if !(defined WIN32 || defined _WIN32) && (defined __i486__ || defined __i586__ || \
defined __i686__ || defined __MMX__ || defined __SSE__ || defined __ppc__) || \
(defined __GNUC__ && defined _STLPORT_MAJOR)
#define CV_XADD <API key>
#else
#include <ext/atomicity.h>
#define CV_XADD __gnu_cxx::__exchange_and_add
#endif
#else
#include <bits/atomicity.h>
#if __GNUC__*10 + __GNUC_MINOR__ >= 34
#define CV_XADD __gnu_cxx::__exchange_and_add
#else
#define CV_XADD __exchange_and_add
#endif
#endif
#elif defined WIN32 || defined _WIN32 || defined WINCE
int <API key>(int* addr, int delta);
#define CV_XADD <API key>
#else
static inline int CV_XADD(int* addr, int delta)
{
int tmp = *addr;
*addr += delta;
return tmp;
}
#endif
class Mutex
{
public:
Mutex();
~Mutex();
Mutex(const Mutex& m);
Mutex& operator = (const Mutex& m);
void lock();
bool trylock();
void unlock();
struct Impl;
protected:
Impl* impl;
};
class AutoLock
{
public:
explicit AutoLock(Mutex& m) : mutex(&m) {
mutex->lock();
}
~AutoLock() {
mutex->unlock();
}
protected:
Mutex* mutex;
private:
AutoLock(const AutoLock&);
AutoLock& operator = (const AutoLock&);
};
#ifdef WIN32
class CriticalSection
{
public:
CriticalSection() {
<API key>(&cs);
}
~CriticalSection() {
<API key>(&cs);
}
void lock() {
<API key>(&cs);
}
void unlock() {
<API key>(&cs);
}
bool trylock() {
return <API key>(&cs) != 0;
}
private:
CRITICAL_SECTION cs;
};
#elif defined __APPLE__
#include <libkern/OSAtomic.h>
class CriticalSection
{
public:
CriticalSection() {
sl = OS_SPINLOCK_INIT;
}
~CriticalSection() {
<API key>(&mutex);
}
void lock() {
OSSpinLockLock(&sl);
}
void unlock() {
OSSpinLockUnlock(&sl);
}
bool trylock() {
return OSSpinLockTry(&sl);
}
private:
OSSpinLock sl;
};
#elif defined __linux__ && !defined ANDROID
class CriticalSection
{
public:
CriticalSection() {
pthread_spin_init(&sl, 0);
}
~CriticalSection() {
<API key>(&sl);
}
void lock() {
pthread_spin_lock(&sl);
}
void unlock() {
pthread_spin_unlock(&sl);
}
bool trylock() {
return <API key>(&sl) == 0;
}
private:
pthread_spinlock_t sl;
};
#else //WIN32
class CriticalSection
{
public:
CriticalSection() {
pthread_mutex_init(&mutex, 0);
}
~CriticalSection() {
<API key>(&mutex);
}
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
<API key>(&mutex);
}
bool trylock() {
return <API key>(&mutex) == 0;
}
private:
pthread_mutex_t mutex;
};
#endif //WIN32
class <API key>
{
public:
<API key>(CriticalSection& _cs) : cs(&_cs) {
cs->lock();
}
~<API key>() {
cs->unlock();
}
private:
CriticalSection* cs;
private:
<API key>(const <API key>&);
<API key>& operator = (const <API key>&);
};
#endif //MUTEX_H |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('servo', '<API key>'),
]
operations = [
migrations.AddField(
model_name='orderstatus',
name='duration',
field=models.IntegerField(default=0),
preserve_default=True,
),
] |
class Gitup < Formula
desc "Update multiple git repositories at once"
homepage "https://github.com/earwig/git-repo-updater"
url "https://github.com/earwig/git-repo-updater.git",
:revision => "<SHA1-like>",
:tag => "v0.4.1"
bottle do
cellar :any_skip_relocation
sha256 "<SHA256-like>" => :high_sierra
sha256 "<SHA256-like>" => :sierra
sha256 "<SHA256-like>" => :el_capitan
end
depends_on "python@2" if MacOS.version <= :snow_leopard
resource "colorama" do
url "https://files.pythonhosted.org/packages/source/c/colorama/colorama-0.3.9.tar.gz"
sha256 "<SHA256-like>"
end
resource "smmap2" do
url "https://files.pythonhosted.org/packages/source/s/smmap2/smmap2-2.0.3.tar.gz"
sha256 "<SHA256-like>"
end
resource "gitdb2" do
url "https://files.pythonhosted.org/packages/source/g/gitdb2/gitdb2-2.0.3.tar.gz"
sha256 "<SHA256-like>"
end
resource "GitPython" do
url "https://files.pythonhosted.org/packages/source/G/GitPython/GitPython-2.1.8.tar.gz"
sha256 "<SHA256-like>"
end
def install
ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages"
%w[colorama smmap2 gitdb2 GitPython].each do |r|
resource(r).stage do
system "python", *Language::Python.setup_install_args(libexec/"vendor")
end
end
ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages"
system "python", *Language::Python.setup_install_args(libexec) |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using LZ4.Tests.Helpers;
// ReSharper disable InconsistentNaming
namespace LZ4.Tests
{
[TestFixture]
public class ConformanceTests
{
#region consts
private const int MAXIMUM_LENGTH = 1 * 10 * 1024 * 1024; // 10MB
#endregion
#region utilities
private void TestConformance(TimedMethod[] compressors, TimedMethod[] decompressors)
{
var provider = new BlockDataProvider(Utilities.<API key>());
var r = new Random(0);
Console.WriteLine("Architecture: {0}bit", IntPtr.Size * 8);
var total = 0;
const long limit = 1L * 1024 * 1024 * 1024;
var last_pct = 0;
while (total < limit)
{
var length = Utilities.RandomLength(r, MAXIMUM_LENGTH);
var block = provider.GetBytes(length);
TestData(block, compressors, decompressors);
total += block.Length;
var pct = (int)((double)total * 100 / limit);
if (pct > last_pct)
{
Console.WriteLine("{0}%...", pct);
last_pct = pct;
}
}
}
#endregion
[TestFixtureSetUp]
public void Setup()
{
Utilities.Download();
}
[Test]
public void <API key>()
{
var compressors = new[] {
new TimedMethod("MixedMode 64", (b, l) => LZ4mm.LZ4Codec.Encode64(b, 0, l)),
new TimedMethod("MixedMode 32", (b, l) => LZ4mm.LZ4Codec.Encode32(b, 0, l)),
new TimedMethod("C++/CLI 64", (b, l) => LZ4cc.LZ4Codec.Encode64(b, 0, l)),
new TimedMethod("C++/CLI 32", (b, l) => LZ4cc.LZ4Codec.Encode32(b, 0, l)),
new TimedMethod("Unsafe 64", (b, l) => LZ4pn.LZ4Codec.Encode64(b, 0, l)),
new TimedMethod("Unsafe 32", (b, l) => LZ4pn.LZ4Codec.Encode32(b, 0, l)),
new TimedMethod("Safe 64", (b, l) => LZ4ps.LZ4Codec.Encode64(b, 0, l)),
new TimedMethod("Safe 32", (b, l) => LZ4ps.LZ4Codec.Encode32(b, 0, l)),
};
var decompressors = new[] {
new TimedMethod("MixedMode 64", (b, l) => LZ4mm.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("MixedMode 32", (b, l) => LZ4mm.LZ4Codec.Decode32(b, 0, b.Length, l)),
new TimedMethod("C++/CLI 64", (b, l) => LZ4cc.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("C++/CLI 32", (b, l) => LZ4cc.LZ4Codec.Decode32(b, 0, b.Length, l)),
new TimedMethod("Unsafe 64", (b, l) => LZ4pn.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("Unsafe 32", (b, l) => LZ4pn.LZ4Codec.Decode32(b, 0, b.Length, l)),
new TimedMethod("Safe 64", (b, l) => LZ4ps.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("Safe 32", (b, l) => LZ4ps.LZ4Codec.Decode32(b, 0, b.Length, l)),
};
TestConformance(compressors, decompressors);
}
[Test]
public void <API key>()
{
var compressors = new[] {
new TimedMethod("MixedMode 64", (b, l) => LZ4mm.LZ4Codec.Encode64HC(b, 0, l)),
new TimedMethod("MixedMode 32", (b, l) => LZ4mm.LZ4Codec.Encode32HC(b, 0, l)),
new TimedMethod("C++/CLI 64", (b, l) => LZ4cc.LZ4Codec.Encode64HC(b, 0, l)),
new TimedMethod("C++/CLI 32", (b, l) => LZ4cc.LZ4Codec.Encode32HC(b, 0, l)),
new TimedMethod("Unsafe 64", (b, l) => LZ4pn.LZ4Codec.Encode64HC(b, 0, l)),
new TimedMethod("Unsafe 32", (b, l) => LZ4pn.LZ4Codec.Encode32HC(b, 0, l)),
new TimedMethod("Safe 64", (b, l) => LZ4ps.LZ4Codec.Encode64HC(b, 0, l)),
new TimedMethod("Safe 32", (b, l) => LZ4ps.LZ4Codec.Encode32HC(b, 0, l)),
};
var decompressors = new[] {
new TimedMethod("MixedMode 64", (b, l) => LZ4mm.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("MixedMode 32", (b, l) => LZ4mm.LZ4Codec.Decode32(b, 0, b.Length, l)),
new TimedMethod("C++/CLI 64", (b, l) => LZ4cc.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("C++/CLI 32", (b, l) => LZ4cc.LZ4Codec.Decode32(b, 0, b.Length, l)),
new TimedMethod("Unsafe 64", (b, l) => LZ4pn.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("Unsafe 32", (b, l) => LZ4pn.LZ4Codec.Decode32(b, 0, b.Length, l)),
new TimedMethod("Safe 64", (b, l) => LZ4ps.LZ4Codec.Decode64(b, 0, b.Length, l)),
new TimedMethod("Safe 32", (b, l) => LZ4ps.LZ4Codec.Decode32(b, 0, b.Length, l)),
};
TestConformance(compressors, decompressors);
}
private static void TestData(
byte[] original,
IEnumerable<TimedMethod> compressors,
IEnumerable<TimedMethod> decompressors)
{
int length = original.Length;
var compressed = new Dictionary<string, byte[]>();
byte[] compressed0 = null;
foreach (var compressor in compressors)
{
var buffer = compressor.Run(original, length);
compressed[compressor.Name] = buffer;
if (compressed0 == null)
{
compressed0 = buffer;
}
else if (compressor.Identical)
{
Utilities.AssertEqual(compressed0, buffer, compressor.Name);
}
}
foreach (var decompressor in decompressors)
{
try
{
var temp = decompressor.Run(compressed[decompressor.Name], length);
Utilities.AssertEqual(original, temp, decompressor.Name);
}
catch
{
Console.WriteLine("Failed in: {0}", decompressor.Name);
throw;
}
}
}
}
}
// ReSharper restore InconsistentNaming |
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
if(globals.drawing_line === true){
cancelLines(null);
}
ev.dataTransfer.setData("Text",ev.target.src);
}
function drop(ev) {
ev.preventDefault();
var data_img=ev.dataTransfer.getData("Text");
var container = document.<API key>("container")[globals.widget_id];
var imageObj = new Image();
imageObj.src = data_img;
imageObj.width = globals.images_width;
imageObj.height = globals.images_height;
//calculate position
var tempX = ev.pageX;
var tempY = ev.pageY;
var containerX = getLeft("container");
var containerY = getTop("container");
var finalX = tempX - containerX - (imageObj.width / 2);
var finalY = tempY - containerY - (imageObj.height / 2);
//fuck IE 10
if ((tempX - containerX) < 0 || (tempX-getLeft("container")) > container.offsetWidth || (tempY - containerY) < 0 || (tempY-getTop("container")) > container.offsetHeight ){
finalX = container.offsetWidth / 2 - (imageObj.width / 2);
finalY = container.offsetHeight / 2 - (imageObj.height / 2);
}
var type = GetNodeNumber(data_img);
var label = globals.JSONObject.names[GetNodeNumber(data_img)] + " " + globals.id_node;
// new image
globals.knodes[globals.knodes.length] = new Kinetic.Image({
image: imageObj,
x: finalX,
y: finalY,
width: globals.images_width,
height: globals.images_height,
draggable: true,
id: globals.id_node
});
//set up label
globals.klabels[globals.klabels.length] = new Kinetic.Text({
x: finalX,
y: finalY + globals.images_height,
text: label,
fontSize: 18,
fontFamily: 'Calibri',
fill: '#555',
margin: 0,
padding: 0,
align: 'center'
});
//label double click
globals.klabels[globals.klabels.length - 1].on("dblclick", function(evt){
var index;
//search for label position
for(index = 0; index < globals.klabels.length; index++)
if(globals.klabels[index] == this)
break;
var result = prompt("Give new name:", globals.nodes[index].label);
this.setText(result);
globals.nodes[index].label = result;
globals.image_layer.draw();
});
//image events
globals.knodes[globals.knodes.length - 1].on("click", function(evt){
if (globals.drawing_line === true) {
GetContext(this.attrs.image.src, this.attrs.x,this.attrs.y,this.attrs.height,this.attrs.width,this.attrs.id);
ContextShow(evt);
globals.context_menu_count = 3;
}
else if(globals.deleting === true) {
deleteNode(this.attrs.id);
}
});
globals.knodes[globals.knodes.length - 1].on("dragmove", function() {
var tmppoints;
var index = GetNodeIndex(this.attrs.id);
for (var i = 0; i < globals.edges.length; i++) {
if (globals.edges[i].from === this.attrs.id) {
tmppoints = globals.kedges[i].getPoints();
tmppoints[0].x = this.getX() + (globals.images_width / 2);
tmppoints[0].y = this.getY() + (globals.images_width / 2);
globals.kedges[i].setPoints(tmppoints);
}
else if (globals.edges[i].to === this.attrs.id) {
tmppoints = globals.kedges[i].getPoints();
tmppoints[1].x = this.getX() + (globals.images_width / 2);
tmppoints[1].y = this.getY() + (globals.images_width / 2);
globals.kedges[i].setPoints(tmppoints);
}
}
//adjust label
globals.klabels[index].attrs.x = this.getX();
globals.klabels[index].attrs.y = this.getY() + globals.images_height;
globals.line_layer.draw();
});
globals.knodes[globals.knodes.length - 1].on("dragend", function() {
globals.line_layer.draw();
});
// add cursor styling
globals.knodes[globals.knodes.length - 1].on('mouseover', function() {
if(globals.drawing_line === false && globals.deleting === false)
document.body.style.cursor = 'pointer';
});
globals.knodes[globals.knodes.length - 1].on('mouseout', function() {
if(globals.drawing_line === false && globals.deleting === false)
document.body.style.cursor = 'default';
});
globals.nodes_ports[globals.knodes.length - 1] = new node_ports(globals.port_limits[GetNodeNumber(data_img)].slice());
globals.nodes[globals.knodes.length - 1] = new node(globals.knodes[globals.knodes.length - 1].attrs.id, type, finalX, finalY, data_img, globals.nodes_ports[globals.knodes.length - 1], label);
//draw image to image layer
globals.image_layer.add(globals.knodes[globals.knodes.length - 1]);
globals.image_layer.add(globals.klabels[globals.knodes.length - 1]);
globals.image_layer.draw();
globals.id_node++;
}
function drawEdges(x, y, height, width, id, index,event) {
event.preventDefault();
var node_index;
node_index = GetNodeIndex(id);
if (globals.click === 0) {
globals.tmp_point = new Array();
globals.tmp_point[0] = x + (width / 2);
globals.tmp_point[1] = y + (height / 2);
globals.click = 1;
globals.tmp_node_id = id;
//port limit calculation
if(globals.nodes_ports[node_index].ports[index] != -1)
globals.nodes_ports[node_index].ports[index] = globals.nodes_ports[node_index].ports[index] - 1;
globals.current_node_index = node_index;
globals.current_port_index = index;
}
else {
var dash;
var color;
if(globals.line_style === 0){
dash = [30, 0];
color = 'black'
} else if(globals.line_style === 1){
dash = [15, 5];
color = 'black'
} else if(globals.line_style === 2){
dash = [30, 0];
color = 'red'
} else if(globals.line_style === 3){
dash = [15, 5];
color = 'red'
} else if(globals.line_style === 4){
dash = [30, 0];
color = 'cyan'
} else if(globals.line_style === 5){
dash = [15, 5];
color = 'cyan'
} else if(globals.line_style === 6){
dashArray: [29, 20, 0.001, 20]
color = 'black'
} else {
dash = [5, 5];
color = 'black';
}
globals.kedges[globals.kedges.length] = new Kinetic.Line({
points: [globals.tmp_point[0], globals.tmp_point[1], x + (width / 2), y + (height / 2)],
stroke: color,
strokeWidth: 8,
lineCap: 'miter',
lineJoin: 'butt',
id : globals.id_edge,
dashArray : dash
});
globals.edges[globals.edges.length] = new edge(globals.id_edge, globals.line_style, globals.tmp_node_id, id, globals.tmp_point[0], globals.tmp_point[1], x + (width / 2), y + (height / 2),globals.current_port_index, index);
//EVENT
globals.kedges[globals.kedges.length - 1].on('click', function() {
if(globals.deleting === true)
{
deleteEdge(this.attrs.id);
}
});
globals.kedges[globals.kedges.length - 1].on('mouseover', function() {
var edge_index, from_node_index, to_node_index;
var from_node_src, to_node_src;
//search for edge
edge_index = GetEdgeIndex(this.attrs.id);
//search for nodes indexes
from_node_index = GetNodeIndex(globals.edges[edge_index].from);
to_node_index = GetNodeIndex(globals.edges[edge_index].to);
from_node_src = GetNodeNumber(globals.nodes[from_node_index].url);
to_node_src = GetNodeNumber(globals.nodes[to_node_index].url);
globals.edge_label.setText(globals.nodes[from_node_index].label + " : " + globals.JSONObject.ports[from_node_src][globals.edges[edge_index].porta] + " <
globals.image_layer.draw();
});
globals.kedges[globals.kedges.length - 1].on('mouseleave', function() {
globals.edge_label.setText(" ");
globals.image_layer.draw();
});
//port limit calculation
if(globals.nodes_ports[node_index].ports[index] != -1)
globals.nodes_ports[node_index].ports[index] = globals.nodes_ports[node_index].ports[index] - 1;
globals.current_node_index = node_index;
globals.current_port_index = index;
globals.line_layer.add(globals.kedges[globals.kedges.length - 1]);
globals.line_layer.draw();
globals.click = 0;
globals.id_edge++;
}
CloseContext();
}
function deleteNode(id){
var node_index = GetNodeIndex(id);
globals.knodes[node_index].destroy();
for (var i = 0; i < globals.kedges.length; i++) {
if (globals.edges[i].from === id) {
globals.kedges[i].destroy();
globals.kedges.splice(i,1);
if (globals.nodes_ports[GetNodeIndex(globals.edges[i].to)].ports[globals.edges[i].portb] != -1)
globals.nodes_ports[GetNodeIndex(globals.edges[i].to)].ports[globals.edges[i].portb]++;
globals.edges.splice(i,1);
i
}
else if (globals.edges[i].to === id) {
globals.kedges[i].destroy();
globals.kedges.splice(i,1);
if (globals.nodes_ports[GetNodeIndex(globals.edges[i].from)].ports[globals.edges[i].porta] != -1)
globals.nodes_ports[GetNodeIndex(globals.edges[i].from)].ports[globals.edges[i].porta]++;
globals.edges.splice(i,1);
i
}
}
globals.nodes_ports.splice(node_index,1);
globals.klabels[node_index].destroy();
globals.klabels.splice(node_index,1);
globals.knodes.splice(node_index,1);
globals.nodes.splice(node_index,1);
globals.image_layer.draw();
globals.line_layer.draw();
}
function deleteEdge(id){
var edge_index = GetEdgeIndex(id);
globals.kedges[edge_index].destroy();
globals.kedges.splice(edge_index, 1);
var from_node_index = GetNodeIndex(globals.edges[edge_index].from);
var to_node_index = GetNodeIndex(globals.edges[edge_index].to);
if (globals.nodes_ports[from_node_index].ports[globals.edges[edge_index].porta] != -1)
globals.nodes_ports[from_node_index].ports[globals.edges[edge_index].porta]++;
if (globals.nodes_ports[to_node_index].ports[globals.edges[edge_index].portb] != -1)
globals.nodes_ports[to_node_index].ports[globals.edges[edge_index].portb]++;
globals.edges.splice(edge_index, 1);
globals.line_layer.draw();
}
function loadNode(old_node){
var data_img = old_node.url;
var type;
var container = document.<API key>("container")[globals.widget_id];
var imageObj = new Image();
imageObj.onload = function(){
refreshLayer(globals.image_layer);
}
imageObj.src = data_img;
imageObj.width = globals.images_width;
imageObj.height = globals.images_height;
var finalX = old_node.x;
var finalY = old_node.y;
type = GetNodeNumber(data_img);
// new image
globals.knodes[globals.knodes.length] = new Kinetic.Image({
image: imageObj,
x: finalX,
y: finalY,
width: globals.images_width,
height: globals.images_height,
draggable: true,
id: globals.id_node
});
//set up label
globals.klabels[globals.klabels.length] = new Kinetic.Text({
x: finalX,
y: finalY + globals.images_height,
text: old_node.label,
fontSize: 18,
fontFamily: 'Calibri',
fill: '#555',
margin: 0,
padding: 0,
align: 'center'
});
//label double click
globals.klabels[globals.klabels.length - 1].on("dblclick", function(evt){
var index;
//search for label position
for(index = 0; index < globals.klabels.length; index++)
if(globals.klabels[index] == this)
break;
var result = prompt("Give new name:", globals.nodes[index].label);
this.setText(result);
globals.nodes[index].label = result;
globals.image_layer.draw();
});
//image events
globals.knodes[globals.knodes.length - 1].on("click", function(evt){
if (globals.drawing_line === true) {
GetContext(this.attrs.image.src, this.attrs.x,this.attrs.y,this.attrs.height,this.attrs.width,this.attrs.id);
ContextShow(evt);
globals.context_menu_count = 3;
}
else if(globals.deleting === true) {
deleteNode(this.attrs.id);
}
});
globals.knodes[globals.knodes.length - 1].on("dragmove", function() {
var tmppoints;
var index = GetNodeIndex(this.attrs.id);
for (var i = 0; i < globals.edges.length; i++) {
if (globals.edges[i].from === this.attrs.id) {
tmppoints = globals.kedges[i].getPoints();
tmppoints[0].x = this.getX() + (globals.images_width / 2);
tmppoints[0].y = this.getY() + (globals.images_width / 2);
globals.kedges[i].setPoints(tmppoints);
}
else if (globals.edges[i].to === this.attrs.id) {
tmppoints = globals.kedges[i].getPoints();
tmppoints[1].x = this.getX() + (globals.images_width / 2);
tmppoints[1].y = this.getY() + (globals.images_width / 2);
globals.kedges[i].setPoints(tmppoints);
}
}
//adjust label
globals.klabels[index].attrs.x = this.getX();
globals.klabels[index].attrs.y = this.getY() + globals.images_height;
globals.line_layer.draw();
});
globals.knodes[globals.knodes.length - 1].on("dragend", function() {
globals.line_layer.draw();
});
// add cursor styling
globals.knodes[globals.knodes.length - 1].on('mouseover', function() {
if(globals.drawing_line === false && globals.deleting === false)
document.body.style.cursor = 'pointer';
});
globals.knodes[globals.knodes.length - 1].on('mouseout', function() {
if(globals.drawing_line === false && globals.deleting === false)
document.body.style.cursor = 'default';
});
globals.nodes_ports[globals.nodes.length] = old_node.ports;
globals.nodes[globals.nodes.length] = new node(globals.knodes[globals.id_node].attrs.id, type, old_node.x, old_node.y, old_node.url, old_node.ports, old_node.label);
//draw image to image layer
globals.image_layer.add(globals.knodes[globals.knodes.length - 1]);
globals.image_layer.add(globals.klabels[globals.klabels.length - 1]);
globals.image_layer.draw();
globals.id_node++;
}
function loadEdge(old_edge){
var dash;
var color;
if(old_edge.type === 0){
dash = [30, 0];
color = 'black'
} else if(old_edge.type === 1){
dash = [15, 5];
color = 'black'
} else if(old_edge.type === 2){
dash = [30, 0];
color = 'red'
} else if(old_edge.type === 3){
dash = [15, 5];
color = 'red'
} else if(old_edge.type === 4){
dash = [30, 0];
color = 'cyan'
} else if(old_edge.type === 5){
dash = [15, 5];
color = 'cyan'
} else if(old_edge.type === 6){
dashArray: [29, 20, 0.001, 20]
color = 'black'
} else {
dash = [5, 5];
color = 'black';
}
globals.kedges[globals.kedges.length] = new Kinetic.Line({
points: [old_edge.ax, old_edge.ay, old_edge.bx, old_edge.by],
stroke: color,
strokeWidth: 8,
lineCap: 'miter',
lineJoin: 'butt',
id : globals.id_edge,
dashArray : dash
});
//EVENT
globals.kedges[globals.kedges.length - 1].on('click', function() {
if(globals.deleting === true)
{
deleteEdge(this.attrs.id);
}
});
globals.kedges[globals.kedges.length - 1].on('mouseover', function() {
var edge_index, from_node_index, to_node_index;
var from_node_src, to_node_src;
//search for edge
edge_index = GetEdgeIndex(this.attrs.id);
//search for nodes indexes
from_node_index = GetNodeIndex(globals.edges[edge_index].from);
to_node_index = GetNodeIndex(globals.edges[edge_index].to);
from_node_src = GetNodeNumber(globals.nodes[from_node_index].url);
to_node_src = GetNodeNumber(globals.nodes[to_node_index].url);
globals.edge_label.setText(globals.nodes[from_node_index].label + " : " + globals.JSONObject.ports[from_node_src][globals.edges[edge_index].porta] + " <
globals.image_layer.draw();
});
globals.kedges[globals.kedges.length - 1].on('mouseleave', function() {
globals.edge_label.setText(" ");
globals.image_layer.draw();
});
globals.edges[globals.edges.length] = new edge(globals.id_edge, old_edge.type, old_edge.from, old_edge.to, old_edge.ax, old_edge.ay, old_edge.bx, old_edge.by, old_edge.porta, old_edge.portb);
globals.line_layer.add(globals.kedges[globals.kedges.length - 1]);
globals.line_layer.draw();
globals.image_layer.draw();
globals.id_edge++;
} |
#include "TracepointThreadBar.h"
#include <GteVector.h>
#include <absl/strings/str_format.h>
#include <memory>
#include <utility>
#include "App.h"
#include "Batcher.h"
#include "CaptureViewElement.h"
#include "ClientData/CaptureData.h"
#include "ClientProtos/capture_data.pb.h"
#include "ClientServices/<API key>.h"
#include "CoreMath.h"
#include "Geometry.h"
#include "GlCanvas.h"
#include "GrpcProtos/tracepoint.pb.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/ThreadConstants.h"
#include "TimeGraphLayout.h"
#include "Viewport.h"
namespace orbit_gl {
TracepointThreadBar::TracepointThreadBar(CaptureViewElement* parent, OrbitApp* app,
const orbit_gl::<API key>* timeline_info,
orbit_gl::Viewport* viewport, TimeGraphLayout* layout,
const orbit_client_data::ModuleManager* module_manager,
const orbit_client_data::CaptureData* capture_data,
uint32_t thread_id, const Color& color)
: ThreadBar(parent, app, timeline_info, viewport, layout, module_manager, capture_data,
thread_id, "Tracepoints", color) {}
void TracepointThreadBar::DoDraw(Batcher& batcher, TextRenderer& text_renderer,
const DrawContext& draw_context) {
ThreadBar::DoDraw(batcher, text_renderer, draw_context);
if (IsEmpty()) {
return;
}
float event_bar_z = draw_context.picking_mode == PickingMode::kClick
? GlCanvas::<API key>
: GlCanvas::kZValueEventBar;
Color color = GetColor();
Box box(GetPos(), Vec2(GetWidth(), -GetHeight()), event_bar_z);
batcher.AddBox(box, color, shared_from_this());
}
void TracepointThreadBar::DoUpdatePrimitives(Batcher& batcher, TextRenderer& text_renderer,
uint64_t min_tick, uint64_t max_tick,
PickingMode picking_mode) {
<API key>("TracepointThreadBar::DoUpdatePrimitives", kOrbitColorIndigo);
ThreadBar::DoUpdatePrimitives(batcher, text_renderer, min_tick, max_tick, picking_mode);
float z = GlCanvas::kZValueEvent;
float track_height = layout_-><API key>(GetThreadId());
const bool picking = picking_mode != PickingMode::kNone;
const Color kWhite(255, 255, 255, 255);
const Color kWhiteTransparent(255, 255, 255, 190);
const Color kGrey(128, 128, 128, 255);
ORBIT_CHECK(capture_data_ != nullptr);
if (!picking) {
capture_data_-><API key>(
GetThreadId(), min_tick, max_tick,
[&](const orbit_client_protos::TracepointEventInfo& tracepoint) {
uint64_t time = tracepoint.time();
float radius = track_height / 4;
const Vec2 pos(timeline_info_->GetWorldFromTick(time), GetPos()[1]);
if (GetThreadId() == orbit_base::<API key>) {
const Color color = tracepoint.pid() == capture_data_->process_id() ? kGrey : kWhite;
batcher.AddVerticalLine(pos, -track_height, z, color);
} else {
batcher.AddVerticalLine(pos, -radius, z, kWhiteTransparent);
batcher.AddVerticalLine(Vec2(pos[0], pos[1] - track_height), radius, z,
kWhiteTransparent);
batcher.AddCircle(Vec2(pos[0], pos[1] - track_height / 2), radius, z,
kWhiteTransparent);
}
});
} else {
constexpr float kPickingBoxWidth = 9.0f;
constexpr float kPickingBoxOffset = kPickingBoxWidth / 2.0f;
capture_data_-><API key>(
GetThreadId(), min_tick, max_tick,
[&](const orbit_client_protos::TracepointEventInfo& tracepoint) {
uint64_t time = tracepoint.time();
Vec2 pos(timeline_info_->GetWorldFromTick(time) - kPickingBoxOffset,
GetPos()[1] - track_height + 1);
Vec2 size(kPickingBoxWidth, track_height);
auto user_data = std::make_unique<PickingUserData>(
nullptr,
[&](PickingId id) -> std::string { return <API key>(batcher, id); });
user_data->custom_data_ = &tracepoint;
batcher.AddShadedBox(pos, size, z, kWhite, std::move(user_data));
});
}
}
std::string TracepointThreadBar::<API key>(Batcher& batcher, PickingId id) const {
auto* user_data = batcher.GetUserData(id);
ORBIT_CHECK(user_data && user_data->custom_data_);
const auto* <API key> =
static_cast<const orbit_client_protos::TracepointEventInfo*>(user_data->custom_data_);
uint64_t tracepoint_info_key = <API key>->tracepoint_info_key();
ORBIT_CHECK(capture_data_ != nullptr);
orbit_grpc_protos::TracepointInfo tracepoint_info =
capture_data_->GetTracepointInfo(tracepoint_info_key);
if (GetThreadId() == orbit_base::<API key>) {
return absl::StrFormat(
"<b>%s : %s</b><br/>"
"<i>Tracepoint event</i><br/>"
"<br/>"
"<b>Core:</b> %d<br/>"
"<b>Process:</b> %s [%d]<br/>"
"<b>Thread:</b> %s [%d]<br/>",
tracepoint_info.category(), tracepoint_info.name(), <API key>->cpu(),
capture_data_->GetThreadName(<API key>->pid()), <API key>->pid(),
capture_data_->GetThreadName(<API key>->tid()), <API key>->tid());
} else {
return absl::StrFormat(
"<b>%s : %s</b><br/>"
"<i>Tracepoint event</i><br/>"
"<br/>"
"<b>Core:</b> %d<br/>",
tracepoint_info.category(), tracepoint_info.name(), <API key>->cpu());
}
}
bool TracepointThreadBar::IsEmpty() const {
return capture_data_ == nullptr ||
capture_data_-><API key>(GetThreadId()) == 0;
}
} // namespace orbit_gl |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mango.image.median_filter — mango 0.9.8 documentation</title>
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var <API key> = {
URL_ROOT: '../',
VERSION: '0.9.8',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=<API key>"></script>
<link rel="top" title="mango 0.9.8 documentation" href="../index.html" />
<link rel="up" title="Image Processing and Analysis (mango.image)" href="../image.html" />
<link rel="next" title="mango.image.stdd_filter" href="mango.image.stdd_filter.html" />
<link rel="prev" title="mango.image.mean_filter" href="mango.image.mean_filter.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="mango.image.stdd_filter.html" title="mango.image.stdd_filter"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="mango.image.mean_filter.html" title="mango.image.mean_filter"
accesskey="P">previous</a> |</li>
<li><a href="../index.html">mango 0.9.8 documentation</a> »</li>
<li><a href="../image.html" accesskey="U">Image Processing and Analysis (<tt class="docutils literal"><span class="pre">mango.image</span></tt>)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="<API key>">
<h1>mango.image.median_filter<a class="headerlink" href="
<dl class="function">
<dt id="mango.image.median_filter">
<tt class="descclassname">mango.image.</tt><tt class="descname">median_filter</tt><big>(</big><em>input</em>, <em>se=<mango.image._mango_open_filters.<API key> object at 0x7f720bc1f628></em>, <em>mode='mirror'</em>, <em>cval=None</em>, <em>stride=(1</em>, <em>1</em>, <em>1)</em>, <em>boffset=(0</em>, <em>0</em>, <em>0)</em>, <em>eoffset=(0</em>, <em>0</em>, <em>0)</em><big>)</big><a class="headerlink" href="
<dd><p>Neighbourhood median filter.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>input</strong> (<a class="reference internal" href="mango.Dds.html#mango.Dds" title="mango.Dds"><tt class="xref py py-obj docutils literal"><span class="pre">mango.Dds</span></tt></a>) – Image to be filtered.</li>
<li><strong>se</strong> (<a class="reference internal" href="mango.image.StructuringElement.html#mango.image.StructuringElement" title="mango.image.StructuringElement"><tt class="xref py py-obj docutils literal"><span class="pre">StructuringElement</span></tt></a>.) – Structuring element which defines the neighbourhood over which the medians are calculated.</li>
<li><strong>mode</strong> (<a class="reference external" href="http://docs.python.org/2/library/functions.html#str" title="(in Python v2.7)"><em>str</em></a>) – String indicating how to handle borders, one of
“mirror”, “constant”, “reflect”.</li>
<li><strong>cval</strong> (<em>scalar</em>) – When <tt class="samp docutils literal"><span class="pre">mode=='constant'</span></tt> use this value
to initialise borders.</li>
<li><strong>stride</strong> (<em>3-sequence</em>) – The sub-sampling step-size for each dimension.</li>
<li><strong>boffset</strong> (<em>3-sequence</em>) – The offset (<tt class="samp docutils literal"><span class="pre">(bz,by,bx)</span></tt> relative to <tt class="samp docutils literal"><span class="pre">input.origin</span></tt>)
at which the filtering starts.</li>
<li><strong>eoffset</strong> (<em>3-sequence</em>) – The offset (<tt class="samp docutils literal"><span class="pre">(ez,ey,ex)</span></tt> relative to <tt class="samp docutils literal"><span class="pre">(input.origin</span> <span class="pre">+</span> <span class="pre">input.shape)</span></tt>)
at which the filtering stops.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Return type:</th><td class="field-body"><p class="first"><a class="reference internal" href="mango.Dds.html#mango.Dds" title="mango.Dds"><tt class="xref py py-obj docutils literal"><span class="pre">mango.Dds</span></tt></a></p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Returns:</th><td class="field-body"><p class="first last">Median-filtered image.</p>
</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="mango.image.mean_filter.html"
title="previous chapter">mango.image.mean_filter</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="mango.image.stdd_filter.html"
title="next chapter">mango.image.stdd_filter</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/mango.image.median_filter.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="mango.image.stdd_filter.html" title="mango.image.stdd_filter"
>next</a> |</li>
<li class="right" >
<a href="mango.image.mean_filter.html" title="mango.image.mean_filter"
>previous</a> |</li>
<li><a href="../index.html">mango 0.9.8 documentation</a> »</li>
<li><a href="../image.html" >Image Processing and Analysis (<tt class="docutils literal"><span class="pre">mango.image</span></tt>)</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2014, Department of Applied Mathematics, The Australian National University.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.3.
</div>
</body>
</html> |
module Autoparts
module Packages
class MongoDB < Package
name 'mongodb'
version '2.6.1'
description 'MongoDB: A cross-platform document-oriented NoSQL database system'
category Category::DATA_STORES
source_url 'http://fastdl.mongodb.org/linux/<API key>.6.1.tgz'
source_sha1 '<SHA1-like>'
source_filetype 'tgz'
def compile
# mongodb is distributed precompiled
end
def install
prefix_path.parent.mkpath
FileUtils.rm_rf prefix_path
execute 'mv', <API key> + "<API key>-#{version}", prefix_path
end
def post_install
mongodb_var_path.mkpath
mongodb_log_path.mkpath
unless mongodb_conf_path.exist?
File.open(mongodb_conf_path, 'w') do |f|
f.write mongodb_conf_file
end
end
end
def purge
mongodb_var_path.rmtree if mongodb_var_path.exist?
mongodb_log_path.rmtree if mongodb_log_path.exist?
mongodb_conf_path.unlink if mongodb_conf_path.exist?
end
def mongod_path
bin_path + 'mongod'
end
def mongodb_conf_path
Path.etc + 'mongodb.conf'
end
def mongodb_var_path
Path.var + 'mongodb'
end
def mongodb_log_path
Path.var + 'log' + 'mongodb'
end
def <API key>
mongodb_var_path + 'mongod.pid'
end
def mongodb_conf_file
<<-EOF.unindent
# Changing the following settings may break Autoparts process management
dbpath = #{mongodb_var_path}
pidfilepath = #{<API key>}
logpath = #{mongodb_log_path}/mongod.log
logappend = true
bind_ip = 127.0.0.1
smallfiles = true
EOF
end
def start
execute mongod_path, '--fork', '--config', mongodb_conf_path
end
def stop
execute mongod_path, '--shutdown', '--config', mongodb_conf_path
<API key>.unlink if <API key>.exist?
end
def running?
if <API key>.exist?
pid = File.read(<API key>).strip
if pid.length > 0 && `ps -o cmd= #{pid}`.include?(mongod_path.basename.to_s)
return true
end
end
false
end
def tips
<<-EOS.unindent
To start the server:
$ parts start mongodb
To stop the server:
$ parts stop mongodb
To open MongoDB shell:
$ mongo
EOS
end
end
end
end |
class Yq < Formula
desc "Process YAML documents from the CLI"
homepage "https://github.com/mikefarah/yq"
url "https://github.com/mikefarah/yq/archive/v4.18.1.tar.gz"
sha256 "<SHA256-like>"
license "MIT"
head "https://github.com/mikefarah/yq.git", branch: "master"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, monterey: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, big_sur: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, catalina: "<SHA256-like>"
sha256 cellar: :any_skip_relocation, x86_64_linux: "<SHA256-like>"
end
depends_on "go" => :build
depends_on "pandoc" => :build
conflicts_with "python-yq", because: "both install `yq` executables"
def install
system "go", "build", *std_go_args(ldflags: "-s -w")
# Install shell completions
(bash_completion/"yq").write Utils.safe_popen_read(bin/"yq", "shell-completion", "bash")
(zsh_completion/"_yq").write Utils.safe_popen_read(bin/"yq", "shell-completion", "zsh")
(fish_completion/"yq.fish").write Utils.safe_popen_read(bin/"yq", "shell-completion", "fish")
# Install man pages
system "./scripts/<API key>.sh"
system "./scripts/generate-man-page.sh"
man1.install "yq.1"
end
test do
assert_equal "key: cat", shell_output("#{bin}/yq eval --null-input --no-colors '.key = \"cat\"'").chomp
assert_equal "cat", pipe_output("#{bin}/yq eval \".key\" -", "key: cat", 0).chomp
end
end |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('simsoexp', '<API key>'),
]
operations = [
migrations.RemoveField(
model_name='results',
name='metrics',
),
migrations.AddField(
model_name='results',
name='aborted_jobs',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='jobs',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='migrations',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='norm_laxity',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='on_schedule',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='preemptions',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='sys_preempt',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='task_migrations',
field=models.IntegerField(default=0),
preserve_default=False,
),
migrations.AddField(
model_name='results',
name='timers',
field=models.IntegerField(default=0),
preserve_default=False,
),
] |
<?php
namespace Swagger\Client\Model;
use \ArrayAccess;
use \Swagger\Client\ObjectSerializer;
class Service implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Service';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'price' => 'double',
'online_price' => 'double',
'tax_included' => 'double',
'program_id' => 'int',
'tax_rate' => 'double',
'product_id' => 'double',
'id' => 'string',
'name' => 'string',
'count' => 'int'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'price' => 'double',
'online_price' => 'double',
'tax_included' => 'double',
'program_id' => 'int32',
'tax_rate' => 'double',
'product_id' => 'double',
'id' => null,
'name' => null,
'count' => 'int32'
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'price' => 'Price',
'online_price' => 'OnlinePrice',
'tax_included' => 'TaxIncluded',
'program_id' => 'ProgramId',
'tax_rate' => 'TaxRate',
'product_id' => 'ProductId',
'id' => 'Id',
'name' => 'Name',
'count' => 'Count'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'price' => 'setPrice',
'online_price' => 'setOnlinePrice',
'tax_included' => 'setTaxIncluded',
'program_id' => 'setProgramId',
'tax_rate' => 'setTaxRate',
'product_id' => 'setProductId',
'id' => 'setId',
'name' => 'setName',
'count' => 'setCount'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'price' => 'getPrice',
'online_price' => 'getOnlinePrice',
'tax_included' => 'getTaxIncluded',
'program_id' => 'getProgramId',
'tax_rate' => 'getTaxRate',
'product_id' => 'getProductId',
'id' => 'getId',
'name' => 'getName',
'count' => 'getCount'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['price'] = isset($data['price']) ? $data['price'] : null;
$this->container['online_price'] = isset($data['online_price']) ? $data['online_price'] : null;
$this->container['tax_included'] = isset($data['tax_included']) ? $data['tax_included'] : null;
$this->container['program_id'] = isset($data['program_id']) ? $data['program_id'] : null;
$this->container['tax_rate'] = isset($data['tax_rate']) ? $data['tax_rate'] : null;
$this->container['product_id'] = isset($data['product_id']) ? $data['product_id'] : null;
$this->container['id'] = isset($data['id']) ? $data['id'] : null;
$this->container['name'] = isset($data['name']) ? $data['name'] : null;
$this->container['count'] = isset($data['count']) ? $data['count'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function <API key>()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this-><API key>()) === 0;
}
/**
* Gets price
*
* @return double
*/
public function getPrice()
{
return $this->container['price'];
}
/**
* Sets price
*
* @param double $price The cost of the pricing option when sold at a physical location.
*
* @return $this
*/
public function setPrice($price)
{
$this->container['price'] = $price;
return $this;
}
/**
* Gets online_price
*
* @return double
*/
public function getOnlinePrice()
{
return $this->container['online_price'];
}
/**
* Sets online_price
*
* @param double $online_price The cost of the pricing option when sold online.
*
* @return $this
*/
public function setOnlinePrice($online_price)
{
$this->container['online_price'] = $online_price;
return $this;
}
/**
* Gets tax_included
*
* @return double
*/
public function getTaxIncluded()
{
return $this->container['tax_included'];
}
/**
* Sets tax_included
*
* @param double $tax_included The amount of tax included in the price, if inclusive pricing is enabled.
*
* @return $this
*/
public function setTaxIncluded($tax_included)
{
$this->container['tax_included'] = $tax_included;
return $this;
}
/**
* Gets program_id
*
* @return int
*/
public function getProgramId()
{
return $this->container['program_id'];
}
/**
* Sets program_id
*
* @param int $program_id The ID of the program that this pricing option applies to.
*
* @return $this
*/
public function setProgramId($program_id)
{
$this->container['program_id'] = $program_id;
return $this;
}
/**
* Gets tax_rate
*
* @return double
*/
public function getTaxRate()
{
return $this->container['tax_rate'];
}
/**
* Sets tax_rate
*
* @param double $tax_rate The tax rate applied to the pricing option. This field is populated only when you include a `LocationID` in the request.
*
* @return $this
*/
public function setTaxRate($tax_rate)
{
$this->container['tax_rate'] = $tax_rate;
return $this;
}
/**
* Gets product_id
*
* @return double
*/
public function getProductId()
{
return $this->container['product_id'];
}
/**
* Sets product_id
*
* @param double $product_id The unique ID of the pricing option.
*
* @return $this
*/
public function setProductId($product_id)
{
$this->container['product_id'] = $product_id;
return $this;
}
/**
* Gets id
*
* @return string
*/
public function getId()
{
return $this->container['id'];
}
/**
* Sets id
*
* @param string $id The barcode ID of the pricing option.
*
* @return $this
*/
public function setId($id)
{
$this->container['id'] = $id;
return $this;
}
/**
* Gets name
*
* @return string
*/
public function getName()
{
return $this->container['name'];
}
/**
* Sets name
*
* @param string $name The name of the pricing option.
*
* @return $this
*/
public function setName($name)
{
$this->container['name'] = $name;
return $this;
}
/**
* Gets count
*
* @return int
*/
public function getCount()
{
return $this->container['count'];
}
/**
* Sets count
*
* @param int $count The initial count of usages available for the pricing option.
*
* @return $this
*/
public function setCount($count)
{
$this->container['count'] = $count;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::<API key>($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::<API key>($this));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.