text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* QUnit - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2009 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var QUnit = {
// Initialize the configuration options
init: function() {
config = {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autorun: false,
assertions: [],
filters: [],
queue: []
};
var tests = id("qunit-tests"),
banner = id("qunit-banner"),
result = id("qunit-testresult");
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
},
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
synchronize(function() {
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
config.currentModule = name;
config.moduleTestEnvironment = testEnvironment;
config.moduleStats = { all: 0, bad: 0 };
QUnit.moduleStart( name, testEnvironment );
});
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = 0;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = testName, testEnvironment, testEnvironmentArg;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
// is 2nd argument a testEnvironment?
if ( expected && typeof expected === 'object') {
testEnvironmentArg = expected;
expected = null;
}
if ( config.currentModule ) {
name = config.currentModule + " module: " + name;
}
if ( !validTest(name) ) {
return;
}
synchronize(function() {
QUnit.testStart( testName );
testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, config.moduleTestEnvironment);
if (testEnvironmentArg) {
extend(testEnvironment,testEnvironmentArg);
}
// allow utility functions to access the current test environment
QUnit.current_testEnvironment = testEnvironment;
config.assertions = [];
config.expected = expected;
try {
if ( !config.pollution ) {
saveGlobal();
}
testEnvironment.setup.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + name + ": " + e.message );
}
if ( async ) {
QUnit.stop();
}
try {
callback.call(testEnvironment);
} catch(e) {
fail("Test " + name + " died, exception and test follows", e, callback);
QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
start();
}
}
});
synchronize(function() {
try {
checkPollution();
testEnvironment.teardown.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Teardown failed on " + name + ": " + e.message );
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset);
}
if ( config.expected && config.expected != config.assertions.length ) {
QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += config.assertions.length;
config.moduleStats.all += config.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
ol.style.display = "none";
for ( var i = 0; i < config.assertions.length; i++ ) {
var assertion = config.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.appendChild(document.createTextNode(assertion.message || "(no message)"));
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
var b = document.createElement("strong");
b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>";
addEvent(b, "click", function() {
var next = b.nextSibling, display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() === "strong" ) {
var text = "", node = target.firstChild;
while ( node.nodeType === 3 ) {
text += node.nodeValue;
node = node.nextSibling;
}
text = text.replace(/(^\s*|\s*$)/g, "");
if ( window.location ) {
window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text);
}
}
});
var li = document.createElement("li");
li.className = bad ? "fail" : "pass";
li.appendChild( b );
li.appendChild( ol );
tests.appendChild( li );
if ( bad ) {
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "block";
id("qunit-filter-pass").disabled = null;
id("qunit-filter-missing").disabled = null;
}
}
} else {
for ( var i = 0; i < config.assertions.length; i++ ) {
if ( !config.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
QUnit.testDone( testName, bad, config.assertions.length );
if ( !window.setTimeout && !config.queue.length ) {
done();
}
});
if ( window.setTimeout && !config.doneTimer ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
}
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) {
config.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
QUnit.log(a, msg);
config.assertions.push({
result: !!a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) {
push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
push(expected != actual, actual, expected, message);
},
deepEqual: function(a, b, message) {
push(QUnit.equiv(a, b), a, b, message);
},
notDeepEqual: function(a, b, message) {
push(!QUnit.equiv(a, b), a, b, message);
},
strictEqual: function(actual, expected, message) {
push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
push(expected !== actual, actual, expected, message);
},
start: function() {
// A slight delay, to avoid any current callbacks
if ( window.setTimeout ) {
window.setTimeout(function() {
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process();
}, 13);
} else {
config.blocking = false;
process();
}
},
stop: function(timeout) {
config.blocking = true;
if ( timeout && window.setTimeout ) {
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
QUnit.start();
}, timeout);
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*/
reset: function() {
if ( window.jQuery ) {
jQuery("#main").html( config.fixture );
jQuery.event.global = {};
jQuery.ajaxSettings = extend({}, config.ajaxSettings);
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Safe object type checking
is: function( type, obj ) {
return Object.prototype.toString.call( obj ) === "[object "+ type +"]";
},
// Logging callbacks
done: function(failures, total) {},
log: function(result, message) {},
testStart: function(name) {},
testDone: function(name, failures, total) {},
moduleStart: function(name, testEnvironment) {},
moduleDone: function(name, failures, total) {}
};
// Backwards compatibility, deprecated
QUnit.equals = QUnit.equal;
QUnit.same = QUnit.deepEqual;
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
GETParams = location.search.slice(1).split('&');
for ( var i = 0; i < GETParams.length; i++ ) {
GETParams[i] = decodeURIComponent( GETParams[i] );
if ( GETParams[i] === "noglobals" ) {
GETParams.splice( i, 1 );
i--;
config.noglobals = true;
} else if ( GETParams[i].search('=') > -1 ) {
GETParams.splice( i, 1 );
i--;
}
}
// restrict modules/tests by get parameters
config.filters = GETParams;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
addEvent(window, "load", function() {
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "none";
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
filter.disabled = true;
addEvent( filter, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("pass") > -1 ) {
li[i].style.display = filter.checked ? "none" : "";
}
}
});
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
var missing = document.createElement("input");
missing.type = "checkbox";
missing.id = "qunit-filter-missing";
missing.disabled = true;
addEvent( missing, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) {
li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block";
}
}
});
toolbar.appendChild( missing );
label = document.createElement("label");
label.setAttribute("for", "qunit-filter-missing");
label.innerHTML = "Hide missing tests (untested code is broken code)";
toolbar.appendChild( label );
}
var main = id('main');
if ( main ) {
config.fixture = main.innerHTML;
}
if ( window.jQuery ) {
config.ajaxSettings = window.jQuery.ajaxSettings;
}
QUnit.start();
});
function done() {
if ( config.doneTimer && window.clearTimeout ) {
window.clearTimeout( config.doneTimer );
config.doneTimer = null;
}
if ( config.queue.length ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
return;
}
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
html = ['Tests completed in ',
+new Date - config.started, ' milliseconds.<br/>',
'<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join('');
if ( banner ) {
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
}
if ( tests ) {
var result = id("qunit-testresult");
if ( !result ) {
result = document.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests.nextSibling );
}
result.innerHTML = html;
}
QUnit.done( config.stats.bad, config.stats.all );
}
function validTest( name ) {
var i = config.filters.length,
run = false;
if ( !i ) {
return true;
}
while ( i-- ) {
var filter = config.filters[i],
not = filter.charAt(0) == '!';
if ( not ) {
filter = filter.slice(1);
}
if ( name.indexOf(filter) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
}
return run;
}
function push(result, actual, expected, message) {
message = message || (result ? "okay" : "failed");
QUnit.ok( result, result ? message + ": " + QUnit.jsDump.parse(expected) : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );
}
function synchronize( callback ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process();
}
}
function process() {
var start = (new Date()).getTime();
while ( config.queue.length && !config.blocking ) {
if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) {
config.queue.shift()();
} else {
setTimeout( process, 13 );
break;
}
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( old, config.pollution );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
config.expected++;
}
var deletedGlobals = diff( config.pollution, old );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
config.expected++;
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
a[prop] = b[prop];
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
// Test for equality any JavaScript type.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: Philippe Rathé <[email protected]>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
var parents = []; // stack to avoiding loops from circular referencing
// Determine what is o.
function hoozit(o) {
if (QUnit.is("String", o)) {
return "string";
} else if (QUnit.is("Boolean", o)) {
return "boolean";
} else if (QUnit.is("Number", o)) {
if (isNaN(o)) {
return "nan";
} else {
return "number";
}
} else if (typeof o === "undefined") {
return "undefined";
// consider: typeof null === object
} else if (o === null) {
return "null";
// consider: typeof [] === object
} else if (QUnit.is( "Array", o)) {
return "array";
// consider: typeof new Date() === object
} else if (QUnit.is( "Date", o)) {
return "date";
// consider: /./ instanceof Object;
// /./ instanceof RegExp;
// typeof /./ === "function"; // => false in IE and Opera,
// true in FF and Safari
} else if (QUnit.is( "RegExp", o)) {
return "regexp";
} else if (typeof o === "object") {
return "object";
} else if (QUnit.is( "Function", o)) {
return "function";
} else {
return undefined;
}
}
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = hoozit(o);
if (prop) {
if (hoozit(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"nan": function (b) {
return isNaN(b);
},
"date": function (b, a) {
return hoozit(b) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function (b, a) {
return hoozit(b) === "regexp" &&
a.source === b.source && // the regex itself
a.global === b.global && // and its modifers (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function () {
var caller = callers[callers.length - 1];
return caller !== Object &&
typeof caller !== "undefined";
},
"array": function (b, a) {
var i, j, loop;
var len;
// b could be an object literal here
if ( ! (hoozit(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
//track reference to avoid circular references
parents.push(a);
for (i = 0; i < len; i++) {
loop = false;
for(j=0;j<parents.length;j++){
if(parents[j] === a[i]){
loop = true;//dont rewalk array
}
}
if (!loop && ! innerEquiv(a[i], b[i])) {
parents.pop();
return false;
}
}
parents.pop();
return true;
},
"object": function (b, a) {
var i, j, loop;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of strings
// comparing constructors is more strict than using instanceof
if ( a.constructor !== b.constructor) {
return false;
}
// stack constructor before traversing properties
callers.push(a.constructor);
//track reference to avoid circular references
parents.push(a);
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
loop = false;
for(j=0;j<parents.length;j++){
if(parents[j] === a[i])
loop = true; //don't go down the same path twice
}
aProperties.push(i); // collect a's properties
if (!loop && ! innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
callers.pop(); // unstack, we are done
parents.pop();
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
}
};
}();
innerEquiv = function () { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function (a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [b, a]);
}
// apply transition with (1..n) arguments
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
};
return innerEquiv;
}();
/**
* jsDump
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
* Date: 5/15/2008
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] );
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
return type == 'function' ? parser.call( this, obj ) :
type == 'string' ? parser :
this.parsers.error;
},
typeOf:function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("RegExp", obj)) {
type = "regexp";
} else if (QUnit.is("Date", obj)) {
type = "date";
} else if (QUnit.is("Function", obj)) {
type = "function";
} else if (obj.setInterval && obj.document && !obj.nodeType) {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) {
type = "array";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
undefined:'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, this.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map ) {
var ret = [ ];
this.up();
for ( var key in map )
ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) );
this.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = this.HTML ? '<' : '<',
close = this.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in this.DOMAttrs ) {
var val = node[this.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + this.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:false //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
})(this);
| {
"pile_set_name": "Github"
} |
import os
_MODEL_PATH = os.path.join('/opt/ml/', 'model') # Path where all your model(s) live in
class ModelService(object):
model = None
@classmethod
def get_model(cls):
"""Get the model object for this instance, loading it if it's not already loaded."""
if cls.model is None:
# TODO Load a specific model
# TODO Examples:
# TODO 1. keras.models.load_model(os.path.join(_MODEL_PATH, '<model_file>'))
# TODO 2. joblib.load('<model_file>')
cls.model = None
return cls.model
@classmethod
def predict(cls, input):
"""For the input, do the predictions and return them."""
clf = cls.get_model()
return clf.predict(input)
def predict(json_input):
"""
Prediction given the request input
:param json_input: [dict], request input
:return: [dict], prediction
"""
# TODO Transform json_input and assign the transformed value to model_input
model_input = None
prediction = ModelService.predict(model_input)
print(prediction)
# TODO If you have more than 1 models, then create more classes similar to ModelService
# TODO where each of one will load one of your models
# TODO Transform prediction to a dict and assign it to result
result = {}
return result
| {
"pile_set_name": "Github"
} |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "SourceImpl.h"
#include <algorithm>
#include <cstring>
#include <wpi/json.h>
#include <wpi/timestamp.h>
#include "Log.h"
#include "Notifier.h"
#include "Telemetry.h"
using namespace cs;
static constexpr size_t kMaxImagesAvail = 32;
SourceImpl::SourceImpl(const wpi::Twine& name, wpi::Logger& logger,
Notifier& notifier, Telemetry& telemetry)
: m_logger(logger),
m_notifier(notifier),
m_telemetry(telemetry),
m_name{name.str()} {
m_frame = Frame{*this, wpi::StringRef{}, 0};
}
SourceImpl::~SourceImpl() {
// Wake up anyone who is waiting. This also clears the current frame,
// which is good because its destructor will call back into the class.
Wakeup();
// Set a flag so ReleaseFrame() doesn't re-add them to m_framesAvail.
// Put in a block so we destroy before the destructor ends.
{
m_destroyFrames = true;
auto frames = std::move(m_framesAvail);
}
// Everything else can clean up itself.
}
void SourceImpl::SetDescription(const wpi::Twine& description) {
std::scoped_lock lock(m_mutex);
m_description = description.str();
}
wpi::StringRef SourceImpl::GetDescription(
wpi::SmallVectorImpl<char>& buf) const {
std::scoped_lock lock(m_mutex);
buf.append(m_description.begin(), m_description.end());
return wpi::StringRef{buf.data(), buf.size()};
}
void SourceImpl::SetConnected(bool connected) {
bool wasConnected = m_connected.exchange(connected);
if (wasConnected && !connected)
m_notifier.NotifySource(*this, CS_SOURCE_DISCONNECTED);
else if (!wasConnected && connected)
m_notifier.NotifySource(*this, CS_SOURCE_CONNECTED);
}
uint64_t SourceImpl::GetCurFrameTime() {
std::unique_lock lock{m_frameMutex};
return m_frame.GetTime();
}
Frame SourceImpl::GetCurFrame() {
std::unique_lock lock{m_frameMutex};
return m_frame;
}
Frame SourceImpl::GetNextFrame() {
std::unique_lock lock{m_frameMutex};
auto oldTime = m_frame.GetTime();
m_frameCv.wait(lock, [=] { return m_frame.GetTime() != oldTime; });
return m_frame;
}
Frame SourceImpl::GetNextFrame(double timeout) {
std::unique_lock lock{m_frameMutex};
auto oldTime = m_frame.GetTime();
if (!m_frameCv.wait_for(
lock, std::chrono::milliseconds(static_cast<int>(timeout * 1000)),
[=] { return m_frame.GetTime() != oldTime; })) {
m_frame = Frame{*this, "timed out getting frame", wpi::Now()};
}
return m_frame;
}
void SourceImpl::Wakeup() {
{
std::scoped_lock lock{m_frameMutex};
m_frame = Frame{*this, wpi::StringRef{}, 0};
}
m_frameCv.notify_all();
}
void SourceImpl::SetBrightness(int brightness, CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
int SourceImpl::GetBrightness(CS_Status* status) const {
*status = CS_INVALID_HANDLE;
return 0;
}
void SourceImpl::SetWhiteBalanceAuto(CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
void SourceImpl::SetWhiteBalanceHoldCurrent(CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
void SourceImpl::SetWhiteBalanceManual(int value, CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
void SourceImpl::SetExposureAuto(CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
void SourceImpl::SetExposureHoldCurrent(CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
void SourceImpl::SetExposureManual(int value, CS_Status* status) {
*status = CS_INVALID_HANDLE;
}
VideoMode SourceImpl::GetVideoMode(CS_Status* status) const {
if (!m_properties_cached && !CacheProperties(status)) return VideoMode{};
std::scoped_lock lock(m_mutex);
return m_mode;
}
bool SourceImpl::SetPixelFormat(VideoMode::PixelFormat pixelFormat,
CS_Status* status) {
auto mode = GetVideoMode(status);
if (!mode) return false;
mode.pixelFormat = pixelFormat;
return SetVideoMode(mode, status);
}
bool SourceImpl::SetResolution(int width, int height, CS_Status* status) {
auto mode = GetVideoMode(status);
if (!mode) return false;
mode.width = width;
mode.height = height;
return SetVideoMode(mode, status);
}
bool SourceImpl::SetFPS(int fps, CS_Status* status) {
auto mode = GetVideoMode(status);
if (!mode) return false;
mode.fps = fps;
return SetVideoMode(mode, status);
}
bool SourceImpl::SetConfigJson(wpi::StringRef config, CS_Status* status) {
wpi::json j;
try {
j = wpi::json::parse(config);
} catch (const wpi::json::parse_error& e) {
SWARNING("SetConfigJson: parse error at byte " << e.byte << ": "
<< e.what());
*status = CS_PROPERTY_WRITE_FAILED;
return false;
}
return SetConfigJson(j, status);
}
bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) {
VideoMode mode;
// pixel format
if (config.count("pixel format") != 0) {
try {
auto str = config.at("pixel format").get<std::string>();
wpi::StringRef s(str);
if (s.equals_lower("mjpeg")) {
mode.pixelFormat = cs::VideoMode::kMJPEG;
} else if (s.equals_lower("yuyv")) {
mode.pixelFormat = cs::VideoMode::kYUYV;
} else if (s.equals_lower("rgb565")) {
mode.pixelFormat = cs::VideoMode::kRGB565;
} else if (s.equals_lower("bgr")) {
mode.pixelFormat = cs::VideoMode::kBGR;
} else if (s.equals_lower("gray")) {
mode.pixelFormat = cs::VideoMode::kGray;
} else {
SWARNING("SetConfigJson: could not understand pixel format value '"
<< str << '\'');
}
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read pixel format: " << e.what());
}
}
// width
if (config.count("width") != 0) {
try {
mode.width = config.at("width").get<unsigned int>();
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read width: " << e.what());
}
}
// height
if (config.count("height") != 0) {
try {
mode.height = config.at("height").get<unsigned int>();
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read height: " << e.what());
}
}
// fps
if (config.count("fps") != 0) {
try {
mode.fps = config.at("fps").get<unsigned int>();
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read fps: " << e.what());
}
}
// if all of video mode is set, use SetVideoMode, otherwise piecemeal it
if (mode.pixelFormat != VideoMode::kUnknown && mode.width != 0 &&
mode.height != 0 && mode.fps != 0) {
SINFO("SetConfigJson: setting video mode to pixelFormat "
<< mode.pixelFormat << ", width " << mode.width << ", height "
<< mode.height << ", fps " << mode.fps);
SetVideoMode(mode, status);
} else {
if (mode.pixelFormat != cs::VideoMode::kUnknown) {
SINFO("SetConfigJson: setting pixelFormat " << mode.pixelFormat);
SetPixelFormat(static_cast<cs::VideoMode::PixelFormat>(mode.pixelFormat),
status);
}
if (mode.width != 0 && mode.height != 0) {
SINFO("SetConfigJson: setting width " << mode.width << ", height "
<< mode.height);
SetResolution(mode.width, mode.height, status);
}
if (mode.fps != 0) {
SINFO("SetConfigJson: setting fps " << mode.fps);
SetFPS(mode.fps, status);
}
}
// brightness
if (config.count("brightness") != 0) {
try {
int val = config.at("brightness").get<int>();
SINFO("SetConfigJson: setting brightness to " << val);
SetBrightness(val, status);
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read brightness: " << e.what());
}
}
// white balance
if (config.count("white balance") != 0) {
try {
auto& setting = config.at("white balance");
if (setting.is_string()) {
auto str = setting.get<std::string>();
wpi::StringRef s(str);
if (s.equals_lower("auto")) {
SINFO("SetConfigJson: setting white balance to auto");
SetWhiteBalanceAuto(status);
} else if (s.equals_lower("hold")) {
SINFO("SetConfigJson: setting white balance to hold current");
SetWhiteBalanceHoldCurrent(status);
} else {
SWARNING("SetConfigJson: could not understand white balance value '"
<< str << '\'');
}
} else {
int val = setting.get<int>();
SINFO("SetConfigJson: setting white balance to " << val);
SetWhiteBalanceManual(val, status);
}
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read white balance: " << e.what());
}
}
// exposure
if (config.count("exposure") != 0) {
try {
auto& setting = config.at("exposure");
if (setting.is_string()) {
auto str = setting.get<std::string>();
wpi::StringRef s(str);
if (s.equals_lower("auto")) {
SINFO("SetConfigJson: setting exposure to auto");
SetExposureAuto(status);
} else if (s.equals_lower("hold")) {
SINFO("SetConfigJson: setting exposure to hold current");
SetExposureHoldCurrent(status);
} else {
SWARNING("SetConfigJson: could not understand exposure value '"
<< str << '\'');
}
} else {
int val = setting.get<int>();
SINFO("SetConfigJson: setting exposure to " << val);
SetExposureManual(val, status);
}
} catch (const wpi::json::exception& e) {
SWARNING("SetConfigJson: could not read exposure: " << e.what());
}
}
// properties
if (config.count("properties") != 0)
SetPropertiesJson(config.at("properties"), m_logger, GetName(), status);
return true;
}
std::string SourceImpl::GetConfigJson(CS_Status* status) {
std::string rv;
wpi::raw_string_ostream os(rv);
GetConfigJsonObject(status).dump(os, 4);
os.flush();
return rv;
}
wpi::json SourceImpl::GetConfigJsonObject(CS_Status* status) {
wpi::json j;
// pixel format
wpi::StringRef pixelFormat;
switch (m_mode.pixelFormat) {
case VideoMode::kMJPEG:
pixelFormat = "mjpeg";
break;
case VideoMode::kYUYV:
pixelFormat = "yuyv";
break;
case VideoMode::kRGB565:
pixelFormat = "rgb565";
break;
case VideoMode::kBGR:
pixelFormat = "bgr";
break;
case VideoMode::kGray:
pixelFormat = "gray";
break;
default:
break;
}
if (!pixelFormat.empty()) j.emplace("pixel format", pixelFormat);
// width
if (m_mode.width != 0) j.emplace("width", m_mode.width);
// height
if (m_mode.height != 0) j.emplace("height", m_mode.height);
// fps
if (m_mode.fps != 0) j.emplace("fps", m_mode.fps);
// TODO: output brightness, white balance, and exposure?
// properties
wpi::json props = GetPropertiesJsonObject(status);
if (props.is_array()) j.emplace("properties", props);
return j;
}
std::vector<VideoMode> SourceImpl::EnumerateVideoModes(
CS_Status* status) const {
if (!m_properties_cached && !CacheProperties(status))
return std::vector<VideoMode>{};
std::scoped_lock lock(m_mutex);
return m_videoModes;
}
std::unique_ptr<Image> SourceImpl::AllocImage(
VideoMode::PixelFormat pixelFormat, int width, int height, size_t size) {
std::unique_ptr<Image> image;
{
std::scoped_lock lock{m_poolMutex};
// find the smallest existing frame that is at least big enough.
int found = -1;
for (size_t i = 0; i < m_imagesAvail.size(); ++i) {
// is it big enough?
if (m_imagesAvail[i] && m_imagesAvail[i]->capacity() >= size) {
// is it smaller than the last found?
if (found < 0 ||
m_imagesAvail[i]->capacity() < m_imagesAvail[found]->capacity()) {
// yes, update
found = i;
}
}
}
// if nothing found, allocate a new buffer
if (found < 0)
image.reset(new Image{size});
else
image = std::move(m_imagesAvail[found]);
}
// Initialize image
image->SetSize(size);
image->pixelFormat = pixelFormat;
image->width = width;
image->height = height;
return image;
}
void SourceImpl::PutFrame(VideoMode::PixelFormat pixelFormat, int width,
int height, wpi::StringRef data, Frame::Time time) {
auto image = AllocImage(pixelFormat, width, height, data.size());
// Copy in image data
SDEBUG4("Copying data to "
<< reinterpret_cast<const void*>(image->data()) << " from "
<< reinterpret_cast<const void*>(data.data()) << " (" << data.size()
<< " bytes)");
std::memcpy(image->data(), data.data(), data.size());
PutFrame(std::move(image), time);
}
void SourceImpl::PutFrame(std::unique_ptr<Image> image, Frame::Time time) {
// Update telemetry
m_telemetry.RecordSourceFrames(*this, 1);
m_telemetry.RecordSourceBytes(*this, static_cast<int>(image->size()));
// Update frame
{
std::scoped_lock lock{m_frameMutex};
m_frame = Frame{*this, std::move(image), time};
}
// Signal listeners
m_frameCv.notify_all();
}
void SourceImpl::PutError(const wpi::Twine& msg, Frame::Time time) {
// Update frame
{
std::scoped_lock lock{m_frameMutex};
m_frame = Frame{*this, msg, time};
}
// Signal listeners
m_frameCv.notify_all();
}
void SourceImpl::NotifyPropertyCreated(int propIndex, PropertyImpl& prop) {
m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CREATED, prop.name,
propIndex, prop.propKind, prop.value,
prop.valueStr);
// also notify choices updated event for enum types
if (prop.propKind == CS_PROP_ENUM)
m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CHOICES_UPDATED,
prop.name, propIndex, prop.propKind,
prop.value, wpi::Twine{});
}
void SourceImpl::UpdatePropertyValue(int property, bool setString, int value,
const wpi::Twine& valueStr) {
auto prop = GetProperty(property);
if (!prop) return;
if (setString)
prop->SetValue(valueStr);
else
prop->SetValue(value);
// Only notify updates after we've notified created
if (m_properties_cached) {
m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_VALUE_UPDATED,
prop->name, property, prop->propKind,
prop->value, prop->valueStr);
}
}
void SourceImpl::ReleaseImage(std::unique_ptr<Image> image) {
std::scoped_lock lock{m_poolMutex};
if (m_destroyFrames) return;
// Return the frame to the pool. First try to find an empty slot, otherwise
// add it to the end.
auto it = std::find(m_imagesAvail.begin(), m_imagesAvail.end(), nullptr);
if (it != m_imagesAvail.end()) {
*it = std::move(image);
} else if (m_imagesAvail.size() > kMaxImagesAvail) {
// Replace smallest buffer; don't need to check for null because the above
// find would have found it.
auto it2 = std::min_element(
m_imagesAvail.begin(), m_imagesAvail.end(),
[](const std::unique_ptr<Image>& a, const std::unique_ptr<Image>& b) {
return a->capacity() < b->capacity();
});
if ((*it2)->capacity() < image->capacity()) *it2 = std::move(image);
} else {
m_imagesAvail.emplace_back(std::move(image));
}
}
std::unique_ptr<Frame::Impl> SourceImpl::AllocFrameImpl() {
std::scoped_lock lock{m_poolMutex};
if (m_framesAvail.empty()) return std::make_unique<Frame::Impl>(*this);
auto impl = std::move(m_framesAvail.back());
m_framesAvail.pop_back();
return impl;
}
void SourceImpl::ReleaseFrameImpl(std::unique_ptr<Frame::Impl> impl) {
std::scoped_lock lock{m_poolMutex};
if (m_destroyFrames) return;
m_framesAvail.push_back(std::move(impl));
}
| {
"pile_set_name": "Github"
} |
#include "rose.h"
int main(int argc, char** argv) {
SgProject* proj = frontend(argc,argv);
SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj);
SgFunctionDefinition* mainDef = mainDecl->get_definition();
std::vector<SgNode*> unaryOpNodes = NodeQuery::querySubTree(mainDef,V_SgUnaryOp);
for (int i = 0; i < unaryOpNodes.size(); i++) {
std::cout << unaryOpNodes[i]->class_name() << std::endl;
SgUnaryOp::Sgop_mode m = isSgUnaryOp(unaryOpNodes[i])->get_mode();
if (m == 0) {
std::cout << "prefix" << std::endl;
}
else if (m == 1) {
std::cout << "postfix" << std::endl;
}
else {
std::cout << "Neither post nor prefix" << std::endl;
}
}
return 0;
}
| {
"pile_set_name": "Github"
} |
00:00 So we have our cool little app here, we've got our
00:02 various forms, and we've got a navigation.
00:05 Let's go ahead and actually run this,
00:06 we've not run it yet.
00:08 So, what happens when you run it?
00:09 Well it actually just kicks off, I think,
00:11 a docker image on the Anvil servers.
00:13 So let's click this and get started.
00:15 Oh, before we do, let's give it a name.
00:19 I'm going to call this HighPoint-100days.
00:23 Now we can hit run.
00:25 Now notice it's running right here,
00:27 this little helper thing up at the top,
00:29 and then press stop and get back.
00:31 But anything below this, this is our app,
00:33 this is what people will see.
00:34 You can even expand and collapse the little side thing.
00:37 But if we click on these notice, not so much
00:40 is happening, right?
00:41 Our forms are not showing.
00:42 But still, look, our app is running.
00:44 And if we wanted to see it on other browsers
00:46 or on our phone or something you can even go over here.
00:49 But we're not going to that yet, we're just going to hit stop.
00:52 Now remember, don't close your browser,
00:54 you're not going back to an editor,
00:56 you just want to hit stop, you're already here.
00:58 So how do we link these things together?
01:01 Well, this is where this goes from kind of interesting
01:04 to really different and interesting.
01:06 Watch what happens when I hit code here.
01:08 We've already seen that we have our code in the background,
01:10 okay, and let's open our app browser for a minute.
01:14 So what we need to do is import these other forms,
01:16 in Python, so here's how it goes.
01:18 From add_doc_form,
01:21 import add_dock_form.
01:25 So this is the standard way you get
01:27 access to these other forms.
01:28 You're going to need this for all the various sub forms here.
01:37 All right, so we have them all imported, now what?
01:42 So we're going to write a little bit of code here,
01:44 that when the page loads, after init components,
01:48 when the page loads we want to show the home details form.
01:51 So notice we have a content panel here,
01:56 and what we're going to do, is we're going to put instances
01:58 of these forms into the content panel,
02:00 and that's the thing contained in the middle.
02:03 So we'll say self, notice the nice Intellisense,
02:05 cotentpanel.items,
02:07 not items, what you want to say clear, like that.
02:10 So, in case something was here,
02:12 we want to get it out, and we're going to do this every time
02:15 we navigate, but also at the beginning basically.
02:18 Say self.contentpanel.addcomponent,
02:21 and we're going to create,
02:23 we want to create a home details form like that.
02:27 And that's going to do it.
02:28 All right, now let's run this and see if it works.
02:30 Boom! Look at that. HighPoint Home.
02:32 Now none of this is working, so let's go link those
02:34 three things up and replicate it for the various
02:37 operations we have here.
02:39 So we go back to design, and we just double click home,
02:41 and notice link home clicked, and here's a function.
02:44 Go back to design, do it for all docs,
02:48 do it for add_doc.
02:50 So notice, here are the various things that we can do.
02:53 We can go home, and let's actually,
02:55 do this over here.
03:00 Call self.link, clicked, home, like so.
03:04 Do the same thing with the other little forms
03:06 for the various other pieces.
03:08 So what have we got here?
03:11 The all_docs.
03:15 And this would be add_doc.
03:17 Okay, great, it's almost finished.
03:19 Let's run it and see where we are.
03:23 Notice up here our title, HighPoint Home, HighPoint Home,
03:26 and we click here, we get all documents,
03:28 add a new document, but notice this is not changing.
03:31 This is subtitle, but this is label title.
03:33 Let's fix that.
03:38 Now one thing that's cool, is notice over here on the right.
03:40 These are all the stuff,
03:41 things we can work with, and if you expand it, it shows you
03:43 you can set the icon, text, etc., etc.
03:46 So what we want to do is set the text here.
03:50 So we'll set it home there.
03:54 This one let's say All Documents.
03:56 And this one be Add a document.
04:01 How cool!
04:02 Look at that.
04:03 Very, very nice, I love how this is coming together.
04:06 So, I think our navigation is basically done.
04:09 The next thing that we got to do,
04:10 is let's focus on adding a document.
04:13 Because it's not super interesting to show the documents,
04:15 until we have the ability to add them.
04:17 So we're going to focus on adding a document next.
| {
"pile_set_name": "Github"
} |
# amdefine
A module that can be used to implement AMD's define() in Node. This allows you
to code to the AMD API and have the module work in node programs without
requiring those other programs to use AMD.
## Usage
**1)** Update your package.json to indicate amdefine as a dependency:
```javascript
"dependencies": {
"amdefine": ">=0.1.0"
}
```
Then run `npm install` to get amdefine into your project.
**2)** At the top of each module that uses define(), place this code:
```javascript
if (typeof define !== 'function') { var define = require('amdefine')(module) }
```
**Only use these snippets** when loading amdefine. If you preserve the basic structure,
with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).
You can add spaces, line breaks and even require amdefine with a local path, but
keep the rest of the structure to get the stripping behavior.
As you may know, because `if` statements in JavaScript don't have their own scope, the var
declaration in the above snippet is made whether the `if` expression is truthy or not. If
RequireJS is loaded then the declaration is superfluous because `define` is already already
declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`
declarations of the same variable in the same scope gracefully.
If you want to deliver amdefine.js with your code rather than specifying it as a dependency
with npm, then just download the latest release and refer to it using a relative path:
[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)
### amdefine/intercept
Consider this very experimental.
Instead of pasting the piece of text for the amdefine setup of a `define`
variable in each module you create or consume, you can use `amdefine/intercept`
instead. It will automatically insert the above snippet in each .js file loaded
by Node.
**Warning**: you should only use this if you are creating an application that
is consuming AMD style defined()'d modules that are distributed via npm and want
to run that code in Node.
For library code where you are not sure if it will be used by others in Node or
in the browser, then explicitly depending on amdefine and placing the code
snippet above is suggested path, instead of using `amdefine/intercept`. The
intercept module affects all .js files loaded in the Node app, and it is
inconsiderate to modify global state like that unless you are also controlling
the top level app.
#### Why distribute AMD-style nodes via npm?
npm has a lot of weaknesses for front-end use (installed layout is not great,
should have better support for the `baseUrl + moduleID + '.js' style of loading,
single file JS installs), but some people want a JS package manager and are
willing to live with those constraints. If that is you, but still want to author
in AMD style modules to get dynamic require([]), better direct source usage and
powerful loader plugin support in the browser, then this tool can help.
#### amdefine/intercept usage
Just require it in your top level app module (for example index.js, server.js):
```javascript
require('amdefine/intercept');
```
The module does not return a value, so no need to assign the result to a local
variable.
Then just require() code as you normally would with Node's require(). Any .js
loaded after the intercept require will have the amdefine check injected in
the .js source as it is loaded. It does not modify the source on disk, just
prepends some content to the text of the module as it is loaded by Node.
#### How amdefine/intercept works
It overrides the `Module._extensions['.js']` in Node to automatically prepend
the amdefine snippet above. So, it will affect any .js file loaded by your
app.
## define() usage
It is best if you use the anonymous forms of define() in your module:
```javascript
define(function (require) {
var dependency = require('dependency');
});
```
or
```javascript
define(['dependency'], function (dependency) {
});
```
## RequireJS optimizer integration. <a name="optimizer"></name>
Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)
will have support for stripping the `if (typeof define !== 'function')` check
mentioned above, so you can include this snippet for code that runs in the
browser, but avoid taking the cost of the if() statement once the code is
optimized for deployment.
## Node 0.4 Support
If you want to support Node 0.4, then add `require` as the second parameter to amdefine:
```javascript
//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.
if (typeof define !== 'function') { var define = require('amdefine')(module, require) }
```
## Limitations
### Synchronous vs Asynchronous
amdefine creates a define() function that is callable by your code. It will
execute and trace dependencies and call the factory function *synchronously*,
to keep the behavior in line with Node's synchronous dependency tracing.
The exception: calling AMD's callback-style require() from inside a factory
function. The require callback is called on process.nextTick():
```javascript
define(function (require) {
require(['a'], function(a) {
//'a' is loaded synchronously, but
//this callback is called on process.nextTick().
});
});
```
### Loader Plugins
Loader plugins are supported as long as they call their load() callbacks
synchronously. So ones that do network requests will not work. However plugins
like [text](http://requirejs.org/docs/api.html#text) can load text files locally.
The plugin API's `load.fromText()` is **not supported** in amdefine, so this means
transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)
will not work. This may be fixable, but it is a bit complex, and I do not have
enough node-fu to figure it out yet. See the source for amdefine.js if you want
to get an idea of the issues involved.
## Tests
To run the tests, cd to **tests** and run:
```
node all.js
node all-intercept.js
```
## License
New BSD and MIT. Check the LICENSE file for all the details.
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.asterix.runtime.aggregates.serializable.std;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.functions.IFunctionDescriptor;
import org.apache.asterix.om.functions.IFunctionDescriptorFactory;
import org.apache.asterix.runtime.aggregates.base.AbstractSerializableAggregateFunctionDynamicDescriptor;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.runtime.base.IEvaluatorContext;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.algebricks.runtime.base.ISerializedAggregateEvaluator;
import org.apache.hyracks.algebricks.runtime.base.ISerializedAggregateEvaluatorFactory;
import org.apache.hyracks.api.exceptions.HyracksDataException;
public class SerializableLocalSqlSkewnessAggregateDescriptor
extends AbstractSerializableAggregateFunctionDynamicDescriptor {
private static final long serialVersionUID = 1L;
public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
@Override
public IFunctionDescriptor createFunctionDescriptor() {
return new SerializableLocalSqlSkewnessAggregateDescriptor();
}
};
@Override
public FunctionIdentifier getIdentifier() {
return BuiltinFunctions.SERIAL_LOCAL_SQL_SKEWNESS;
}
@Override
public ISerializedAggregateEvaluatorFactory createSerializableAggregateEvaluatorFactory(
final IScalarEvaluatorFactory[] args) {
return new ISerializedAggregateEvaluatorFactory() {
private static final long serialVersionUID = 1L;
@Override
public ISerializedAggregateEvaluator createAggregateEvaluator(IEvaluatorContext ctx)
throws HyracksDataException {
return new SerializableLocalSqlSkewnessAggregateFunction(args, ctx, sourceLoc);
}
};
}
}
| {
"pile_set_name": "Github"
} |
DEFINED_PHASES=compile install postinst postrm prepare unpack
DEPEND=>=sys-apps/policycoreutils-2.0.82 >=sec-policy/selinux-base-policy-2.20190201-r1 sys-devel/m4 >=sys-apps/checkpolicy-2.0.21
DESCRIPTION=SELinux policy for exim
EAPI=6
HOMEPAGE=https://wiki.gentoo.org/wiki/Project:SELinux
KEYWORDS=amd64 -arm ~arm64 ~mips x86
LICENSE=GPL-2
RDEPEND=>=sys-apps/policycoreutils-2.0.82 >=sec-policy/selinux-base-policy-2.20190201-r1
SLOT=0
SRC_URI=https://github.com/SELinuxProject/refpolicy/releases/download/RELEASE_2_20190201/refpolicy-2.20190201.tar.bz2 https://dev.gentoo.org/~perfinion/patches/selinux-base-policy/patchbundle-selinux-base-policy-2.20190201-r1.tar.bz2
_eclasses_=selinux-policy-2 fc82a837585d258b211de18f9a74d72a
_md5_=bf4faa9010f635c6145d6072bfae8c03
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkEncodedImageFormat_DEFINED
#define SkEncodedImageFormat_DEFINED
#include <stdint.h>
/**
* Enum describing format of encoded data.
*/
enum class SkEncodedImageFormat {
#ifdef SK_BUILD_FOR_GOOGLE3
kUnknown,
#endif
kBMP,
kGIF,
kICO,
kJPEG,
kPNG,
kWBMP,
kWEBP,
kPKM,
kKTX,
kASTC,
kDNG,
kHEIF,
};
#endif // SkEncodedImageFormat_DEFINED
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:wps="http://www.opengis.net/wps/1.0.0" targetNamespace="http://www.opengis.net/wps/1.0.0" elementFormDefault="unqualified" xml:lang="en" version="1.0.0 2010-02-03">
<annotation>
<appinfo>$Id: wpsAll.xsd 2007-10-09 $</appinfo>
<documentation>
<description>This XML Schema includes and imports, directly and indirectly, all the XML Schemas defined by the WPS Implemetation Specification.</description>
<copyright>
WPS is an OGC Standard.
Copyright (c) 2007,2010 Open Geospatial Consortium, Inc. All Rights Reserved.
To obtain additional rights of use, visit http://www.opengeospatial.org/legal/ .
</copyright>
</documentation>
</annotation>
<!-- ==============================================================
includes
============================================================== -->
<include schemaLocation="wpsDescribeProcess_request.xsd"/>
<include schemaLocation="wpsDescribeProcess_response.xsd"/>
<include schemaLocation="wpsExecute_request.xsd"/>
<include schemaLocation="wpsExecute_response.xsd"/>
<include schemaLocation="wpsGetCapabilities_request.xsd"/>
<include schemaLocation="wpsGetCapabilities_response.xsd"/>
</schema>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2017 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm;
import io.realm.internal.ColumnInfo;
import io.realm.internal.Table;
import io.realm.internal.fields.FieldDescriptor;
/**
* Immutable {@link RealmObjectSchema}.
*/
class ImmutableRealmObjectSchema extends RealmObjectSchema {
private static final String SCHEMA_IMMUTABLE_EXCEPTION_MSG = "This 'RealmObjectSchema' is immutable." +
" Please use 'DynamicRealm.getSchema() to get a mutable instance.";
ImmutableRealmObjectSchema(BaseRealm realm, RealmSchema schema, Table table, ColumnInfo columnInfo) {
super(realm, schema, table, columnInfo);
}
ImmutableRealmObjectSchema(BaseRealm realm, RealmSchema schema, Table table) {
super(realm, schema, table, new DynamicColumnIndices(table));
}
@Override
public RealmObjectSchema setClassName(String className) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema addField(String fieldName, Class<?> fieldType, FieldAttribute... attributes) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema addRealmObjectField(String fieldName, RealmObjectSchema objectSchema) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema addRealmListField(String fieldName, RealmObjectSchema objectSchema) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema addRealmListField(String fieldName, Class<?> primitiveType) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema removeField(String fieldName) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema renameField(String currentFieldName, String newFieldName) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema addIndex(String fieldName) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema removeIndex(String fieldName) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema addPrimaryKey(String fieldName) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema removePrimaryKey() {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema setRequired(String fieldName, boolean required) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema setNullable(String fieldName, boolean nullable) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
@Override
public RealmObjectSchema transform(Function function) {
throw new UnsupportedOperationException(SCHEMA_IMMUTABLE_EXCEPTION_MSG);
}
/**
* Returns a field descriptor based on Java field names found in model classes.
*
* @param publicJavaNameDescription field name or linked field description
* @param validColumnTypes valid field type for the last field in a linked field
* @return the corresponding FieldDescriptor.
* @throws IllegalArgumentException if a proper FieldDescriptor could not be created.
*/
@Override
FieldDescriptor getFieldDescriptors(String publicJavaNameDescription, RealmFieldType... validColumnTypes) {
return FieldDescriptor.createStandardFieldDescriptor(getSchemaConnector(), getTable(), publicJavaNameDescription, validColumnTypes);
}
}
| {
"pile_set_name": "Github"
} |
//
// Copyright 2020 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef ANGLE_TESTS_ANGLE_TEST_PLATFORM_H_
#define ANGLE_TESTS_ANGLE_TEST_PLATFORM_H_
#include <string>
#include "util/util_gl.h"
// Driver vendors
bool IsAdreno();
// Renderer back-ends
// Note: FL9_3 is explicitly *not* considered D3D11.
bool IsD3D11();
bool IsD3D11_FL93();
// Is a D3D9-class renderer.
bool IsD3D9();
// Is D3D9 or SM9_3 renderer.
bool IsD3DSM3();
bool IsDesktopOpenGL();
bool IsOpenGLES();
bool IsOpenGL();
bool IsNULL();
bool IsVulkan();
bool IsMetal();
bool IsD3D();
// Debug/Release
bool IsDebug();
bool IsRelease();
bool EnsureGLExtensionEnabled(const std::string &extName);
bool IsEGLClientExtensionEnabled(const std::string &extName);
bool IsEGLDeviceExtensionEnabled(EGLDeviceEXT device, const std::string &extName);
bool IsEGLDisplayExtensionEnabled(EGLDisplay display, const std::string &extName);
bool IsGLExtensionEnabled(const std::string &extName);
bool IsGLExtensionRequestable(const std::string &extName);
#endif // ANGLE_TESTS_ANGLE_TEST_PLATFORM_H_
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('zipObjectDeep', require('../zipObjectDeep'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
# -*- encoding: utf-8 -*-
class Razor::Command::RegisterNode < Razor::Command
summary "Register a node with Razor before it is discovered"
description <<-EOT
In order to make brownfield deployments of Razor easier we allow users to
register nodes explicitly. This command allows you to perform the same
registration that would happen when a new node checked in, ahead of time.
In order for this to be effective the hw_info must contain enough information
that the node can successfully be matched during the iPXE boot phase.
If the node matches an existing node, in keeping with the overall policy of
commands declaring desired state, the node installed field will be updated to
match the value in this command.
The final state is that a node with the supplied hardware information, and the
desired installed state, will be present in the database, regardless of it
existing before hand or not.
EOT
example api: <<-EOT
Register a machine before you boot it, and note that it already has an OS
installed, so should not be subject to policy-based reinstallation:
{
"hw_info": {
"net0": "78:31:c1:be:c8:00",
"net1": "72:00:01:f2:13:f0",
"net2": "72:00:01:f2:13:f1",
"serial": "xxxxxxxxxxx",
"asset": "Asset-1234567890",
"uuid": "Not Settable"
},
"installed": true
}
EOT
example cli: <<-EOT
Register a machine before you boot it, and note that it already has an OS
installed, so should not be subject to policy-based reinstallation:
razor register-node --hw-info net0=78:31:c1:be:c8:00 \\
--hw-info net1=72:00:01:f2:13:f0 \\
--hw-info net2=72:00:01:f2:13:f1 \\
--hw-info serial=xxxxxxxxxxx \\
--hw-info asset=Asset-1234567890 \\
--hw-info uuid="Not Settable" \\
--installed
EOT
authz true
attr 'installed', type: :bool, required: true, help: _(<<-HELP)
Should the node be considered 'installed' already? Installed nodes are
not eligible for policy matching, and will simply boot locally.
HELP
object 'hw_info', required: true, size: 1..Float::INFINITY, help: _(<<-HELP) do
The hardware information for the node. This is used to match the node on first
boot with the record in the database. The order of MAC address assignment in
this data is not significant, as a node with reordered MAC addresses will be
treated as the same node.
HELP
extra_attrs /^net[0-9]+$/, type: String
attr 'serial', type: String, help: _('The DMI serial number of the node')
attr 'asset', type: String, help: _('The DMI asset tag of the node')
attr 'uuid', type: String, help: _('The DMI UUID of the node')
end
def run(request, data)
Razor::Data::Node.lookup(data['hw_info']).set(installed: data['installed']).save.
tap do |node|
Razor::Data::Hook.trigger('node-registered', node: node)
end
end
end
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.io.snowflake.data.numeric;
public class SnowflakeDecimal extends SnowflakeNumber {
public SnowflakeDecimal() {}
public SnowflakeDecimal(int precision, int scale) {
super(precision, scale);
}
public static SnowflakeDecimal of(int precision, int scale) {
return new SnowflakeDecimal(precision, scale);
}
}
| {
"pile_set_name": "Github"
} |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_syssensor_c_h_
#define SDL_syssensor_c_h_
#include "SDL_config.h"
/* This is the system specific header for the SDL sensor API */
#include "SDL_sensor.h"
#include "SDL_sensor_c.h"
/* The SDL sensor structure */
struct _SDL_Sensor
{
SDL_SensorID instance_id; /* Device instance, monotonically increasing from 0 */
char *name; /* Sensor name - system dependent */
SDL_SensorType type; /* Type of the sensor */
int non_portable_type; /* Platform dependent type of the sensor */
float data[16]; /* The current state of the sensor */
struct _SDL_SensorDriver *driver;
struct sensor_hwdata *hwdata; /* Driver dependent information */
int ref_count; /* Reference count for multiple opens */
struct _SDL_Sensor *next; /* pointer to next sensor we have allocated */
};
typedef struct _SDL_SensorDriver
{
/* Function to scan the system for sensors.
* sensor 0 should be the system default sensor.
* This function should return 0, or -1 on an unrecoverable fatal error.
*/
int (*Init)(void);
/* Function to return the number of sensors available right now */
int (*GetCount)(void);
/* Function to check to see if the available sensors have changed */
void (*Detect)(void);
/* Function to get the device-dependent name of a sensor */
const char *(*GetDeviceName)(int device_index);
/* Function to get the type of a sensor */
SDL_SensorType (*GetDeviceType)(int device_index);
/* Function to get the platform dependent type of a sensor */
int (*GetDeviceNonPortableType)(int device_index);
/* Function to get the current instance id of the sensor located at device_index */
SDL_SensorID (*GetDeviceInstanceID)(int device_index);
/* Function to open a sensor for use.
The sensor to open is specified by the device index.
It returns 0, or -1 if there is an error.
*/
int (*Open)(SDL_Sensor * sensor, int device_index);
/* Function to update the state of a sensor - called as a device poll.
* This function shouldn't update the sensor structure directly,
* but instead should call SDL_PrivateSensorUpdate() to deliver events
* and update sensor device state.
*/
void (*Update)(SDL_Sensor * sensor);
/* Function to close a sensor after use */
void (*Close)(SDL_Sensor * sensor);
/* Function to perform any system-specific sensor related cleanup */
void (*Quit)(void);
} SDL_SensorDriver;
/* The available sensor drivers */
extern SDL_SensorDriver SDL_ANDROID_SensorDriver;
extern SDL_SensorDriver SDL_COREMOTION_SensorDriver;
extern SDL_SensorDriver SDL_DUMMY_SensorDriver;
#endif /* SDL_syssensor_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| {
"pile_set_name": "Github"
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>windows::basic_object_handle::basic_object_handle (1 of 5 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../basic_object_handle.html" title="windows::basic_object_handle::basic_object_handle">
<link rel="prev" href="../basic_object_handle.html" title="windows::basic_object_handle::basic_object_handle">
<link rel="next" href="overload2.html" title="windows::basic_object_handle::basic_object_handle (2 of 5 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../basic_object_handle.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../basic_object_handle.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.windows__basic_object_handle.basic_object_handle.overload1"></a><a class="link" href="overload1.html" title="windows::basic_object_handle::basic_object_handle (1 of 5 overloads)">windows::basic_object_handle::basic_object_handle
(1 of 5 overloads)</a>
</h5></div></div></div>
<p>
Construct an object handle without opening it.
</p>
<pre class="programlisting">basic_object_handle(
const executor_type & ex);
</pre>
<p>
This constructor creates an object handle without opening it.
</p>
<h6>
<a name="asio.reference.windows__basic_object_handle.basic_object_handle.overload1.h0"></a>
<span><a name="asio.reference.windows__basic_object_handle.basic_object_handle.overload1.parameters"></a></span><a class="link" href="overload1.html#asio.reference.windows__basic_object_handle.basic_object_handle.overload1.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">ex</span></dt>
<dd><p>
The I/O executor that the object handle will use, by default, to
dispatch handlers for any asynchronous operations performed on
the object handle.
</p></dd>
</dl>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2019 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../basic_object_handle.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../basic_object_handle.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
***
_This step doesn't require changes to the interactive environment, but feel free to explore._
***
To pass 'extra vars' to the Playbooks/Roles being run by the Operator, you can embed key-value pairs in the 'spec' section of the *Custom Resource (CR)*.
This is equivalent to how [*--extra-vars*](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#passing-variables-on-the-command-line) can be passed into the _ansible-playbook_ command.
## Example CR with extra-vars
The CR snippet below shows two 'extra vars' (`message` and `newParamater`) being passed in via `spec`. Passing 'extra vars' through the CR allows for customization of Ansible logic based on the contents of each CR instance.
```yaml
# Sample CR definition where some
# 'extra vars' are passed via the spec
apiVersion: "app.example.com/v1alpha1"
kind: "Database"
metadata:
name: "example"
spec:
message: "Hello world 2"
newParameter: "newParam"
```
## Accessing CR Fields
Now that you've passed 'extra vars' to your Playbook through the CR `spec`, we need to read them from the Ansible logic that makes up your Operator.
Variables passed in through the CR spec are made available at the top-level to be read from Jinja templates. For the CR example above, we could read the vars 'message' and 'newParameter' from a Playbook like so:
```
- debug:
msg: "message value from CR spec: {{ message }}"
- debug:
msg: "newParameter value from CR spec: {{ new_parameter }}"
```
Did you notice anything strange about the snippet above? The 'newParameter' variable that we set on our CR spec was accessed as 'new_parameter'. Keep this automatic conversion from camelCase to snake_case in mind, as it will happen to all 'extra vars' passed into the CR spec.
Refer to the next section for further info on reaching into the JSON structure exposed in the Ansible Operator runtime environment.
### JSON Structure
When a reconciliation job runs, the content of the associated CR is made available as variables in the Ansible runtime environment.
The JSON below is an example of what gets passed into ansible-runner (the Ansible Operator runtime).
Note that vars added to the 'spec' section of the CR ('message' and 'new_parameter') are placed at the top-level of this structure for easy access.
```json
{ "meta": {
"name": "<cr-name>",
"namespace": "<cr-namespace>",
},
"message": "Hello world 2",
"new_parameter": "newParam",
"_app_example_com_database": {
<Full CR>
},
}
```
### Accessing CR metadata
The `meta` fields provide the CR 'name' and 'namespace' associated with a reconciliation job. These and other nested fields can be accessed with dot notation in Ansible.
```yaml
- debug:
msg: "name: {{ meta.name }}, namespace: {{ meta.namespace }}"
```
In the next step, we'll use `operator-sdk` to generate our Operator project scaffolding.
| {
"pile_set_name": "Github"
} |
//
// SmartToast.h
// SmartToast
//
// Created by Mat Schmid on 2019-02-04.
// Copyright © 2019 Mat Schmid. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for SmartToast.
FOUNDATION_EXPORT double SmartToastVersionNumber;
//! Project version string for SmartToast.
FOUNDATION_EXPORT const unsigned char SmartToastVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SmartToast/PublicHeader.h>
| {
"pile_set_name": "Github"
} |
// @flow
import React from 'react';
import { it, describe } from 'flow-typed-test';
import {
Accuracy,
ActivityType,
GeofencingEventType,
GeofencingRegionState,
enableNetworkProviderAsync,
geocodeAsync,
getCurrentPositionAsync,
getHeadingAsync,
getProviderStatusAsync,
hasServicesEnabledAsync,
hasStartedGeofencingAsync,
hasStartedLocationUpdatesAsync,
installWebGeolocationPolyfill,
isBackgroundLocationAvailableAsync,
requestPermissionsAsync,
reverseGeocodeAsync,
setApiKey,
startGeofencingAsync,
startLocationUpdatesAsync,
stopGeofencingAsync,
stopLocationUpdatesAsync,
watchHeadingAsync,
watchPositionAsync,
} from 'expo-location';
describe('Enums', () => {
it('should include some values', () => {
const { Balanced } = Accuracy;
const { Fitness } = ActivityType;
const { Enter } = GeofencingEventType;
const { Outside } = GeofencingRegionState;
});
});
describe('getCurrentPositionAsync', () => {
it('should passes when used properly', () => {
getCurrentPositionAsync({
accuracy: Accuracy.High,
}).then(result => {
const { coords, timestamp } = result;
(timestamp: number);
(coords.latitude: number);
(coords.speed: number);
// $FlowExpectedError: check any
(coords.speed: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need an object
getCurrentPositionAsync(11);
// $FlowExpectedError: `__accuracy` is missing in enum
getCurrentPositionAsync({ __accuracy: 1 });
});
});
describe('getHeadingAsync', () => {
it('should passes when used properly', () => {
getHeadingAsync().then(result => {
(result.trueHeading: number);
(result.magHeading: number);
// $FlowExpectedError: check any
(result.magHeading: string);
});
});
});
describe('getProviderStatusAsync', () => {
it('should passes when used properly', () => {
getProviderStatusAsync().then(result => {
(result.locationServicesEnabled: boolean);
(result.backgroundModeEnabled: boolean);
(result.gpsAvailable: ?boolean);
(result.networkAvailable: ?boolean);
(result.passiveAvailable: ?boolean);
// $FlowExpectedError: check any
(result.backgroundModeEnabled: string);
// $FlowExpectedError: `abcd` is missing
(result.abcd: any);
});
});
});
describe('hasStartedGeofencingAsync', () => {
it('should passes when used properly', () => {
hasStartedGeofencingAsync('taskName').then(result => {
(result: boolean);
// $FlowExpectedError: check any
(result: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need a string
hasStartedGeofencingAsync(69);
});
});
describe('hasStartedLocationUpdatesAsync', () => {
it('should passes when used properly', () => {
hasStartedLocationUpdatesAsync('taskName').then(result => {
(result: boolean);
// $FlowExpectedError: check any
(result: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need a string
hasStartedLocationUpdatesAsync(69);
});
});
describe('setApiKey', () => {
it('should passes when used properly', () => {
(setApiKey('apiKey'): void);
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need a string
setApiKey(69);
});
});
describe('startGeofencingAsync', () => {
it('should passes when used properly', () => {
startGeofencingAsync('taskName', [
{
latitude: 14,
longitude: 48,
radius: 69,
},
]);
startGeofencingAsync('taskName', [
{
latitude: 14,
longitude: 48,
radius: 69,
identifier: 'id',
notifyOnEnter: false,
notifyOnExit: false,
},
]);
startGeofencingAsync('taskName').then(result => {
(result: void);
// $FlowExpectedError: check any
(result: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: first argument is required
startGeofencingAsync();
// $FlowExpectedError: first argument mush be a string
startGeofencingAsync(1337);
startGeofencingAsync('taskName', [
// $FlowExpectedError: must be a region object
69,
]);
startGeofencingAsync('taskName', [
{
latitude: 14,
longitude: 48,
// $FlowExpectedError: must be a number
radius: '69',
},
]);
startGeofencingAsync('taskName', [
// $FlowExpectedError: `abc` prop is missing in Region
{
latitude: 14,
longitude: 48,
radius: 666,
abc: 11,
},
]);
});
});
describe('reverseGeocodeAsync', () => {
it('should passes when used properly', () => {
reverseGeocodeAsync({
latitude: 1,
longitude: 1,
}).then(result => {
const address = result[0];
(address.city: string);
(address.street: string);
(address.region: string);
(address.country: string);
(address.postalCode: string);
// $FlowExpectedError: check any
(address.name: number);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: first argument is required
reverseGeocodeAsync();
// $FlowExpectedError: first must be an object
reverseGeocodeAsync(123);
// $FlowExpectedError: object do not include required props `latitude,longitude`
reverseGeocodeAsync({});
// $FlowExpectedError: `abc` is extra props
reverseGeocodeAsync({
latitude: 1,
longitude: 1,
abc: 1,
});
reverseGeocodeAsync({
// $FlowExpectedError: `latitude` must be a number
latitude: 'nned number',
longitude: 1,
});
});
});
describe('startLocationUpdatesAsync', () => {
it('should passes when used properly', () => {
startLocationUpdatesAsync('taskName', {
accuracy: Accuracy.Balanced,
activityType: ActivityType.Fitness,
timeInterval: 1000,
});
startLocationUpdatesAsync('taskName', {
foregroundService: {
notificationTitle: 'str',
notificationBody: 'str',
},
});
startLocationUpdatesAsync('taskName', {
foregroundService: {
notificationTitle: 'str',
notificationBody: 'str',
notificationColor: 'red',
},
});
startLocationUpdatesAsync('taskName').then(result => {
(result: void);
// $FlowExpectedError: check any
(result: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: first argument is required
startLocationUpdatesAsync();
// $FlowExpectedError: first argument mush be a string
startLocationUpdatesAsync(1337);
// $FlowExpectedError: second argument must be an object
startLocationUpdatesAsync('taskName', 69);
startLocationUpdatesAsync('taskName', {
// $FlowExpectedError: invalid accuracy
accuracy: 1,
// $FlowExpectedError: invalid activityType
activityType: 1,
// $FlowExpectedError: `notificationTitle` is required props
foregroundService: { notificationBody: 'str' },
});
});
});
describe('stopGeofencingAsync', () => {
it('should passes when used properly', () => {
stopGeofencingAsync('taskName').then(result => {
(result: void);
// $FlowExpectedError: check any
(result: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need a string
stopGeofencingAsync(69);
});
});
describe('stopLocationUpdatesAsync', () => {
it('should passes when used properly', () => {
stopLocationUpdatesAsync('taskName').then(result => {
(result: void);
// $FlowExpectedError: check any
(result: string);
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need a string
stopLocationUpdatesAsync(69);
});
});
describe('watchHeadingAsync', () => {
it('should passes when used properly', () => {
watchHeadingAsync(data => {
(data.trueHeading: number);
(data.magHeading: number);
(data.accuracy: number);
// $FlowExpectedError: check any
(data.accuracy: string);
});
watchHeadingAsync(async () => {}).then(result => {
result.remove();
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: need a function
watchHeadingAsync(69);
});
});
describe('watchPositionAsync', () => {
it('should passes when used properly', () => {
watchPositionAsync({}, data => {
const { coords, timestamp } = data;
(timestamp: number);
(coords.latitude: number);
(coords.speed: number);
// $FlowExpectedError: check any
(coords.speed: string);
});
watchPositionAsync({}, async () => {}).then(result => {
result.remove();
});
});
it('should raise an error when call function with invalid arguments', () => {
// $FlowExpectedError: first argument is required
watchPositionAsync();
// $FlowExpectedError: first argument must be a n object
watchPositionAsync(69);
// $FlowExpectedError: second argument must be a function
watchPositionAsync({}, 69);
watchPositionAsync(
{
// $FlowExpectedError: invalid accuracy value
accuracy: 1,
},
() => {}
);
});
});
it('should passes when used properly', () => {
(installWebGeolocationPolyfill(): void);
enableNetworkProviderAsync().then(result => {
(result: void);
// $FlowExpectedError: check any
(result: number);
});
requestPermissionsAsync().then(result => {
(result: void);
// $FlowExpectedError: check any
(result: number);
});
hasServicesEnabledAsync().then(result => {
(result: boolean);
// $FlowExpectedError: check any
(result: number);
});
isBackgroundLocationAvailableAsync().then(result => {
(result: boolean);
// $FlowExpectedError: check any
(result: number);
});
geocodeAsync('address').then(result => {
const geocodedLocation = result[0];
(geocodedLocation.latitude: number);
(geocodedLocation.longitude: number);
(geocodedLocation.altitude: ?number);
(geocodedLocation.accuracy: ?number);
// $FlowExpectedError: check any
(geocodedLocation.latitude: string);
});
});
| {
"pile_set_name": "Github"
} |
/* *********************************************************************** *
* project: org.matsim.*
* MatsimResource.java
* *
* *********************************************************************** *
* *
* copyright : (C) 2008 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package org.matsim.core.gbl;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
/**
* Helper class to load data from files in the resource directory
* (<code>./res/</code>). Because the resource directory may be included into
* jar-files in releases, one must not directly access them with the hard-coded
* path (e.g. <code>new File("res/foo.bar");</code>), as the file would not be
* found if it is inside a jar-file. Instead, use the methods in this class to
* access files in the resource directory. The methods in this class ensure
* that the files can be loaded no matter whether they are inside a jar-file or
* not.<br>
*
* All filenames must be given relative to the resource directory. This means,
* that the name of the resource-directory must not be part of the filenames
* passed to the methods. E.g., to access the file <code>res/foo/bar.txt</code>,
* where <code>res/</code> is the resource directory, one must only pass
* <code>foo/bar.txt</code> as filename.
*
* @author mrieser
*/
public abstract class MatsimResource {
/** The path where resources are located in jar-files. */
private static final String RES_PATH_JARFILE = "/res/";
/** The path where resources are located in a local file system. */
private static final String RES_PATH_LOCAL = "./res/"; //NOPMD // this line should be ignored for PMD analysis
private static final String RES_PATH_LOCAL2 = "./src/main/resources/res/"; //NOPMD // this line should be ignored for PMD analysis
private static final Logger log = Logger.getLogger(MatsimResource.class);
/**
* @param filename relative path from within the resource directory to a file to be loaded
* @return an URL pointing to the requested resource file, or <code>null</code> if no such file exists.
*/
public final static URL getAsURL(final String filename) {
// look for the file locally
{
File file = new File(RES_PATH_LOCAL + filename);
if (file.exists()) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
log.warn("Found resource-file, but could not return URL for it.", e); // just continue, maybe we have more luck in the classpath
}
}
}
{
File file = new File(RES_PATH_LOCAL2 + filename);
if (file.exists()) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
log.warn("Found resource-file, but could not return URL for it.", e); // just continue, maybe we have more luck in the classpath
}
}
}
// maybe we find the file in the classpath, possibly inside a jar-file
URL url = MatsimResource.class.getResource(RES_PATH_JARFILE + filename);
if (url == null) {
log.warn("Resource '" + filename + "' not found!");
}
return url;
}
/**
* @param filename relative path from within the resource directory to a file to be loaded
* @return a Stream to the requested resource file, or <code>null</code> if no such file exists.
*/
public final static InputStream getAsInputStream(final String filename) {
// look for the file locally
try {
return new FileInputStream(RES_PATH_LOCAL + filename);
} catch (FileNotFoundException e) {
log.info("Resource '" + filename + "' not found locally. May not be fatal.");
// just continue, maybe we have more luck in the classpath
}
// maybe we find the file in the classpath, possibly inside a jar-file
InputStream stream = MatsimResource.class.getResourceAsStream(RES_PATH_JARFILE + filename);
if (stream == null) {
log.warn("Resource '" + filename + "' not found!");
}
return stream;
}
/**
* @param filename relative path from within the resource directory to a file to be loaded
* @return a Stream to the requested resource file, or <code>null</code> if no such file exists.
*/
public final static Image getAsImage(final String filename) {
final URL url = getAsURL(filename);
if (url == null) {
return null;
}
try {
return ImageIO.read(url);
} catch (IOException e) {
log.error("Could not load requested image", e);
return null;
}
}
}
| {
"pile_set_name": "Github"
} |
// Underscore.js
// (c) 2009 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the terms of the MIT license.
// Portions of Underscore are inspired by or borrowed from Prototype.js,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore/
(function() {
/*------------------------- Baseline setup ---------------------------------*/
// Are we running in CommonJS or in the browser?
var commonJS = (typeof window === 'undefined' && typeof exports !== 'undefined');
// Save the previous value of the "_" variable.
var previousUnderscore = commonJS ? null : window._;
// Keep the identity function around for default iterators.
var identity = function(value) { return value; };
// Create a safe reference to the Underscore object for the functions below.
var _ = {};
// Export the Underscore object for CommonJS, assign it globally otherwise.
commonJS ? _ = exports : window._ = _;
// Current version.
_.VERSION = '0.3.0';
/*------------------------ Collection Functions: ---------------------------*/
// The cornerstone, an each implementation.
// Handles objects implementing forEach, each, arrays, and raw objects.
_.each = function(obj, iterator, context) {
var index = 0;
try {
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length) {
for (var i=0, l = obj.length; i<l; i++) iterator.call(context, obj[i], i);
} else if (obj.each) {
obj.each(function(value) { iterator.call(context, value, index++); });
} else {
var i = 0;
for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) {
var value = obj[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator.call(context, pair, i++);
}
}
} catch(e) {
if (e != '__break__') throw e;
}
return obj;
};
// Return the results of applying the iterator to each element. Use JavaScript
// 1.6's version of map, if possible.
_.map = function(obj, iterator, context) {
if (obj && obj.map) return obj.map(iterator, context);
var results = [];
_.each(obj, function(value, index) {
results.push(iterator.call(context, value, index));
});
return results;
};
// Reduce builds up a single result from a list of values. Also known as
// inject, or foldl.
_.reduce = function(obj, memo, iterator, context) {
_.each(obj, function(value, index) {
memo = iterator.call(context, memo, value, index);
});
return memo;
};
// Return the first value which passes a truth test.
_.detect = function(obj, iterator, context) {
var result;
_.each(obj, function(value, index) {
if (iterator.call(context, value, index)) {
result = value;
throw '__break__';
}
});
return result;
};
// Return all the elements that pass a truth test. Use JavaScript 1.6's
// filter(), if it exists.
_.select = function(obj, iterator, context) {
if (obj.filter) return obj.filter(iterator, context);
var results = [];
_.each(obj, function(value, index) {
iterator.call(context, value, index) && results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
_.each(obj, function(value, index) {
!iterator.call(context, value, index) && results.push(value);
});
return results;
};
// Determine whether all of the elements match a truth test. Delegate to
// JavaScript 1.6's every(), if it is present.
_.all = function(obj, iterator, context) {
iterator = iterator || identity;
if (obj.every) return obj.every(iterator, context);
var result = true;
_.each(obj, function(value, index) {
if (!(result = result && iterator.call(context, value, index))) throw '__break__';
});
return result;
};
// Determine if at least one element in the object matches a truth test. Use
// JavaScript 1.6's some(), if it exists.
_.any = function(obj, iterator, context) {
iterator = iterator || identity;
if (obj.some) return obj.some(iterator, context);
var result = false;
_.each(obj, function(value, index) {
if (result = iterator.call(context, value, index)) throw '__break__';
});
return result;
};
// Determine if a given value is included in the array or object,
// based on '==='.
_.include = function(obj, target) {
if (_.isArray(obj)) return _.indexOf(obj, target) != -1;
var found = false;
_.each(obj, function(pair) {
if (found = pair.value === target) {
throw '__break__';
}
});
return found;
};
// Invoke a method with arguments on every item in a collection.
_.invoke = function(obj, method) {
var args = _.toArray(arguments).slice(2);
return _.map(obj, function(value) {
return (method ? value[method] : value).apply(value, args);
});
};
// Optimized version of a common use case of map: fetching a property.
_.pluck = function(obj, key) {
var results = [];
_.each(obj, function(value){ results.push(value[key]); });
return results;
};
// Return the maximum item or (item-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
var result = {computed : -Infinity};
_.each(obj, function(value, index) {
var computed = iterator ? iterator.call(context, value, index) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
var result = {computed : Infinity};
_.each(obj, function(value, index) {
var computed = iterator ? iterator.call(context, value, index) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Sort the object's values by a criteria produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index) {
return {
value : value,
criteria : iterator.call(context, value, index)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator = iterator || identity;
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (_.isArray(iterable)) return iterable;
return _.map(iterable, function(val){ return val; });
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
/*-------------------------- Array Functions: ------------------------------*/
// Get the first element of an array.
_.first = function(array) {
return array[0];
};
// Get the last element of an array.
_.last = function(array) {
return array[array.length - 1];
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.select(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array) {
return _.reduce(array, [], function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value));
memo.push(value);
return memo;
});
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
var values = array.slice.call(arguments, 0);
return _.select(array, function(value){ return !_.include(values, value); });
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
_.uniq = function(array, isSorted) {
return _.reduce(array, [], function(memo, el, i) {
if (0 == i || (isSorted ? _.last(memo) != el : !_.include(memo, el))) memo.push(el);
return memo;
});
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersect = function(array) {
var rest = _.toArray(arguments).slice(1);
return _.select(_.uniq(array), function(item) {
return _.all(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = _.toArray(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i=0; i<length; i++) results[i] = _.pluck(args, String(i));
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, MSIE),
// we need this function. Return the position of the first occurence of an
// item in an array, or -1 if the item is not included in the array.
_.indexOf = function(array, item) {
if (array.indexOf) return array.indexOf(item);
for (i=0, l=array.length; i<l; i++) if (array[i] === item) return i;
return -1;
};
// Provide JavaScript 1.6's lastIndexOf, delegating to the native function,
// if possible.
_.lastIndexOf = function(array, item) {
if (array.lastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (array[i] === item) return i;
return -1;
};
/* ----------------------- Function Functions: -----------------------------*/
// Create a function bound to a given object (assigning 'this', and arguments,
// optionally). Binding with arguments is also known as 'curry'.
_.bind = function(func, context) {
if (!context) return func;
var args = _.toArray(arguments).slice(2);
return function() {
var a = args.concat(_.toArray(arguments));
return func.apply(context, a);
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function() {
var args = _.toArray(arguments);
var context = args.pop();
_.each(args, function(methodName) {
context[methodName] = _.bind(context[methodName], context);
});
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = _.toArray(arguments).slice(2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(_.toArray(arguments).slice(1)));
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(_.toArray(arguments));
return wrapper.apply(wrapper, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = _.toArray(arguments);
return function() {
for (var i=funcs.length-1; i >= 0; i--) {
arguments = [funcs[i].apply(this, arguments)];
}
return arguments[0];
};
};
/* ------------------------- Object Functions: ---------------------------- */
// Retrieve the names of an object's properties.
_.keys = function(obj) {
return _.pluck(obj, 'key');
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.pluck(obj, 'value');
};
// Extend a given object with all of the properties in a source object.
_.extend = function(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
return _.extend({}, obj);
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof(a), btype = typeof(b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One of them implements an isEqual()?
if (a.isEqual) return a.isEqual(b);
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Nothing else worked, deep compare the contents.
var aKeys = _.keys(a), bKeys = _.keys(b);
// Different object sizes?
if (aKeys.length != bKeys.length) return false;
// Recursive comparison of contents.
for (var key in a) if (!_.isEqual(a[key], b[key])) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value a real Array?
_.isArray = function(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
};
// Is a given value a Function?
_.isFunction = function(obj) {
return Object.prototype.toString.call(obj) == '[object Function]';
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return typeof obj == 'undefined';
};
/* -------------------------- Utility Functions: -------------------------- */
// Run Underscore.js in noConflict mode, returning the '_' variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
if (!commonJS) window._ = previousUnderscore;
return this;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
_.uniqueId = function(prefix) {
var id = this._idCounter = (this._idCounter || 0) + 1;
return prefix ? prefix + id : id;
};
// JavaScript templating a-la ERB, pilfered from John Resig's
// "Secrets of the JavaScript Ninja", page 83.
_.template = function(str, data) {
var fn = new Function('obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj){p.push(\'' +
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
return data ? fn(data) : fn;
};
/*------------------------------- Aliases ----------------------------------*/
_.forEach = _.each;
_.inject = _.reduce;
_.filter = _.select;
_.every = _.all;
_.some = _.any;
})();
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type UserRevokeSignInSessionsRequest.
/// </summary>
public partial class UserRevokeSignInSessionsRequest : BaseRequest, IUserRevokeSignInSessionsRequest
{
/// <summary>
/// Constructs a new UserRevokeSignInSessionsRequest.
/// </summary>
public UserRevokeSignInSessionsRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<bool> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<bool> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<bool>(null, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IUserRevokeSignInSessionsRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IUserRevokeSignInSessionsRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| {
"pile_set_name": "Github"
} |
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org Greg Messner and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
********************************************************************************/
package org.aoju.bus.gitlab.models;
import org.aoju.bus.gitlab.JacksonJson;
/**
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class WikiPage {
private String title;
private String content;
private String slug;
private String format;
public WikiPage() {
}
public WikiPage(String title, String slug, String content) {
this.title = title;
this.slug = slug;
this.content = content;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public String toString() {
return (JacksonJson.toJsonString(this));
}
}
| {
"pile_set_name": "Github"
} |
10
dir
1078
https://[email protected]/svn/WifiMusicPro/Android/SourceCode/ultra-pull-to-refresh/src/androidTest/java
https://[email protected]/svn/WifiMusicPro
2016-07-07T09:05:14.320397Z
439
zhaowl
f7554972-5f14-274d-98cb-8ab3248a4a47
cn
dir
| {
"pile_set_name": "Github"
} |
re8 re4 |
la2 fa4 |
sib4. la8 sib4 |
sol4 la2 |
re2 re'4 |
la2 sib4 |
fa2 fa4 |
mi4 fa4 re4 |
do2 do4 |
do'4 la2 |
sib4. la8 sol8 fa8 |
mi2 fa4 |
re2 re4 |
do2 re4 |
sib,2. |
la,2. |
la2 sol4 |
fa2 fa4 |
mi2 fa4 |
sol2 do4 |
do'4 si4 la4 |
sold4. sold8 la4 |
fa4 fa2 |
mi2. |
do2 do4 |
re2. |
mi2 mi,4 |
la,2. |
la4. sol8 fa8 mi8 |
re2 re4 |
sol2 mi4 |
fa2 fa4 |
sib2 sol4 |
do'4. sib8 la8 sol8 |
fa4. mib8 re4 |
sib,4 do2 |
fa,2. |
fa4. sol8 la8 sib8 |
do'2 do'4 |
do'2 si4 |
do'2 la4 |
sib2 sol4 |
la8 sib8 la8 sol8 fa8 mi8 |
re8 mib8 re8 do8 sib,8 la,8 |
sol,4 la,4. re8 |
re2. |
| {
"pile_set_name": "Github"
} |
var baseCreate = require('./baseCreate'),
baseLodash = require('./baseLodash');
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable chaining for all wrapper methods.
* @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
*/
function LodashWrapper(value, chainAll, actions) {
this.__wrapped__ = value;
this.__actions__ = actions || [];
this.__chain__ = !!chainAll;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
| {
"pile_set_name": "Github"
} |
/* =========================================================
* bootstrap-gtreetable v2.2.1-alpha
* https://github.com/gilek/bootstrap-gtreetable
* =========================================================
* Copyright 2014 Maciej Kłak
* Licensed under MIT (https://github.com/gilek/bootstrap-gtreetable/blob/master/LICENSE)
* ========================================================= */
/* =========================================================
* Russian translation by Dunaevsky Maxim
* ========================================================= */
(function ($) {
$.fn.gtreetable.defaults.languages.ru = {
save: 'Сохранить',
cancel: 'Отмена',
action: 'Действие',
actions: {
createBefore: 'Вставить до',
createAfter: 'Вставить после',
createFirstChild: 'Создать первого потомка',
createLastChild: 'Создать последнего потомка',
update: 'Обновить',
'delete': 'Удалить'
},
messages: {
onDelete: 'Вы уверены?',
onNewRootNotAllowed: 'Создание новых узлов в корне запрещено.',
onMoveInDescendant: 'Целевой узел не может быть потомком.',
onMoveAsRoot: 'Целевой узел не может быть корневым.'
}
};
}(jQuery)); | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{
"Info": [
{
"IsSuccess": "True",
"InAddress": "雲林縣東勢鄉東南村東勢東路12號",
"InSRS": "EPSG:4326",
"InFuzzyType": "[單雙號機制]+[最近門牌號機制]",
"InFuzzyBuffer": "0",
"InIsOnlyFullMatch": "False",
"InIsLockCounty": "True",
"InIsLockTown": "False",
"InIsLockVillage": "False",
"InIsLockRoadSection": "False",
"InIsLockLane": "False",
"InIsLockAlley": "False",
"InIsLockArea": "False",
"InIsSameNumber_SubNumber": "True",
"InCanIgnoreVillage": "True",
"InCanIgnoreNeighborhood": "True",
"InReturnMaxCount": "0",
"OutTotal": "1",
"OutMatchType": "完全比對",
"OutMatchCode": "[雲林縣]\tFULL:1",
"OutTraceInfo": "[雲林縣]\t { 完全比對 } 找到符合的門牌地址"
}
],
"AddressList": [
{
"FULL_ADDR": "雲林縣東勢鄉東南村14鄰東勢東路12號",
"COUNTY": "雲林縣",
"TOWN": "東勢鄉",
"VILLAGE": "東南村",
"NEIGHBORHOOD": "14鄰",
"ROAD": "東勢東路",
"SECTION": "",
"LANE": "",
"ALLEY": "",
"SUB_ALLEY": "",
"TONG": "",
"NUMBER": "12號",
"X": 120.253631,
"Y": 23.675027
}
]
}</string> | {
"pile_set_name": "Github"
} |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
let kImageDimension: UInt = 180
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
GIDSignIn.sharedInstance().delegate = self
return true
}
func application(application: UIApplication,
openURL url: NSURL,
options: [String: AnyObject]) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url,
sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
withError error: NSError!) {
if (error == nil) {
let fullName = user.profile.name
var picture: NSURL?
if user.profile.hasImage {
picture = user.profile.imageURLWithDimension(kImageDimension)
}
let email = user.profile.email
NSNotificationCenter.defaultCenter().postNotificationName(
"ToggleAuthUINotification",
object: nil,
userInfo: ["statusText": "\(fullName)",
"email": email,
"imageURL": picture!])
} else {
print("\(error.localizedDescription)")
NSNotificationCenter.defaultCenter().postNotificationName(
"ToggleAuthUINotification", object: nil, userInfo: nil)
}
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/python
from __future__ import print_function
import numpy as np
import h5py
import sys
data = np.loadtxt(sys.argv[1], dtype='float32')
h5f = h5py.File(sys.argv[2], 'w');
h5f.create_dataset('data', data=data)
h5f.close()
| {
"pile_set_name": "Github"
} |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public sealed class ConstructorAndRequiredTestClass
{
public ConstructorAndRequiredTestClass(string testProperty1)
{
TestProperty1 = testProperty1;
}
public string TestProperty1 { get; set; }
[JsonProperty(Required = Required.AllowNull)]
public int TestProperty2 { get; set; }
}
} | {
"pile_set_name": "Github"
} |
/*
* Infinitest, a Continuous Test Runner.
*
* Copyright (C) 2010-2013
* "Ben Rady" <[email protected]>,
* "Rod Coffin" <[email protected]>,
* "Ryan Breidenbach" <[email protected]>
* "David Gageot" <[email protected]>, et al.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.infinitest.testrunner;
public interface TestResultsListener {
void testCaseStarting(TestEvent event);
void testCaseComplete(TestCaseEvent event);
}
| {
"pile_set_name": "Github"
} |
---
# Check if CI_COMMIT_TAG is defined (only when making a release) to disable devel repositories
# that contain install dependencies
release_status: '{{ True if lookup("env", "CI_COMMIT_TAG")
else False }}'
# set to package name to avoid installing packetfence-release
# from inverse.ca website (already installed based on pipeline
# artifacts)
packetfence_install__centos_release_rpm: 'packetfence-release'
# only for dependencies, packetfence package is installed using local repo
packetfence_install__centos:
repos: '{{ ["packetfence"] if release_status|bool
else ["packetfence-devel"] }}'
# only for dependencies, packetfence packages are installed using local repo
packetfence_install__deb:
repos: '{{ ["debian"] if release_status|bool
else ["debian","debian-devel"] }}'
# we used Venom to pass through configurator
packetfence_install__configurator_status: 'enabled'
| {
"pile_set_name": "Github"
} |
# pylint: disable=expression-not-assigned,abstract-method,import-error
from __future__ import unicode_literals
from typing import Tuple, Text
import errno
from pathlib import Path
from django.conf import settings
from vstutils.utils import get_render, raise_context
from ._base import _Base, os
class Manual(_Base):
project_files = ['ansible.cfg', 'bootstrap.yml']
def generate_file(self, name: Text):
with open(os.path.join(self.path, name), 'w', encoding='utf-8') as fd:
with raise_context():
fd.write(get_render('polemarch/{}'.format(name), settings.MANUAL_PROJECT_VARS))
def make_clone(self, options) -> Tuple[Path, bool]:
try:
os.mkdir(self.path)
for file in self.project_files:
self.generate_file(file)
except OSError as oserror:
if oserror.errno == errno.EEXIST:
return Path(self.path), False
raise # nocv
return Path(self.path), True
def make_update(self, options) -> Tuple[Path, bool]:
if not os.path.exists(self.path): # nocv
os.mkdir(self.path)
return Path(self.path), True
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/util/type_resolver_util.h>
#include <google/protobuf/type.pb.h>
#include <google/protobuf/wrappers.pb.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/status.h>
namespace google {
namespace protobuf {
namespace util {
namespace {
using google::protobuf::BoolValue;
using google::protobuf::Enum;
using google::protobuf::EnumValue;
using google::protobuf::Field;
using google::protobuf::Option;
using google::protobuf::Type;
using util::Status;
using util::error::INVALID_ARGUMENT;
using util::error::NOT_FOUND;
bool SplitTypeUrl(const string& type_url, string* url_prefix,
string* message_name) {
size_t pos = type_url.find_last_of("/");
if (pos == string::npos) {
return false;
}
*url_prefix = type_url.substr(0, pos);
*message_name = type_url.substr(pos + 1);
return true;
}
class DescriptorPoolTypeResolver : public TypeResolver {
public:
DescriptorPoolTypeResolver(const string& url_prefix,
const DescriptorPool* pool)
: url_prefix_(url_prefix), pool_(pool) {}
Status ResolveMessageType(const string& type_url, Type* type) {
string url_prefix, message_name;
if (!SplitTypeUrl(type_url, &url_prefix, &message_name) ||
url_prefix != url_prefix_) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid type URL, type URLs must be of the form '",
url_prefix_, "/<typename>', got: ", type_url));
}
if (url_prefix != url_prefix_) {
return Status(INVALID_ARGUMENT,
"Cannot resolve types from URL: " + url_prefix);
}
const Descriptor* descriptor = pool_->FindMessageTypeByName(message_name);
if (descriptor == NULL) {
return Status(NOT_FOUND,
"Invalid type URL, unknown type: " + message_name);
}
ConvertDescriptor(descriptor, type);
return Status();
}
Status ResolveEnumType(const string& type_url, Enum* enum_type) {
string url_prefix, type_name;
if (!SplitTypeUrl(type_url, &url_prefix, &type_name) ||
url_prefix != url_prefix_) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid type URL, type URLs must be of the form '",
url_prefix_, "/<typename>', got: ", type_url));
}
if (url_prefix != url_prefix_) {
return Status(INVALID_ARGUMENT,
"Cannot resolve types from URL: " + url_prefix);
}
const EnumDescriptor* descriptor = pool_->FindEnumTypeByName(type_name);
if (descriptor == NULL) {
return Status(NOT_FOUND, "Invalid type URL, unknown type: " + type_name);
}
ConvertEnumDescriptor(descriptor, enum_type);
return Status();
}
private:
void ConvertDescriptor(const Descriptor* descriptor, Type* type) {
type->Clear();
type->set_name(descriptor->full_name());
for (int i = 0; i < descriptor->field_count(); ++i) {
const FieldDescriptor* field = descriptor->field(i);
if (field->type() == FieldDescriptor::TYPE_GROUP) {
// Group fields cannot be represented with Type. We discard them.
continue;
}
ConvertFieldDescriptor(descriptor->field(i), type->add_fields());
}
for (int i = 0; i < descriptor->oneof_decl_count(); ++i) {
type->add_oneofs(descriptor->oneof_decl(i)->name());
}
type->mutable_source_context()->set_file_name(descriptor->file()->name());
ConvertMessageOptions(descriptor->options(), type->mutable_options());
}
void ConvertMessageOptions(const MessageOptions& options,
RepeatedPtrField<Option>* output) {
if (options.map_entry()) {
Option* option = output->Add();
option->set_name("map_entry");
BoolValue value;
value.set_value(true);
option->mutable_value()->PackFrom(value);
}
// TODO(xiaofeng): Set other "options"?
}
void ConvertFieldDescriptor(const FieldDescriptor* descriptor, Field* field) {
field->set_kind(static_cast<Field::Kind>(descriptor->type()));
switch (descriptor->label()) {
case FieldDescriptor::LABEL_OPTIONAL:
field->set_cardinality(Field::CARDINALITY_OPTIONAL);
break;
case FieldDescriptor::LABEL_REPEATED:
field->set_cardinality(Field::CARDINALITY_REPEATED);
break;
case FieldDescriptor::LABEL_REQUIRED:
field->set_cardinality(Field::CARDINALITY_REQUIRED);
break;
}
field->set_number(descriptor->number());
field->set_name(descriptor->name());
field->set_json_name(descriptor->json_name());
if (descriptor->has_default_value()) {
field->set_default_value(DefaultValueAsString(descriptor));
}
if (descriptor->type() == FieldDescriptor::TYPE_MESSAGE) {
field->set_type_url(GetTypeUrl(descriptor->message_type()));
} else if (descriptor->type() == FieldDescriptor::TYPE_ENUM) {
field->set_type_url(GetTypeUrl(descriptor->enum_type()));
}
if (descriptor->containing_oneof() != NULL) {
field->set_oneof_index(descriptor->containing_oneof()->index() + 1);
}
if (descriptor->is_packed()) {
field->set_packed(true);
}
// TODO(xiaofeng): Set other field "options"?
}
void ConvertEnumDescriptor(const EnumDescriptor* descriptor,
Enum* enum_type) {
enum_type->Clear();
enum_type->set_name(descriptor->full_name());
enum_type->mutable_source_context()->set_file_name(
descriptor->file()->name());
for (int i = 0; i < descriptor->value_count(); ++i) {
const EnumValueDescriptor* value_descriptor = descriptor->value(i);
EnumValue* value = enum_type->mutable_enumvalue()->Add();
value->set_name(value_descriptor->name());
value->set_number(value_descriptor->number());
// TODO(xiaofeng): Set EnumValue options.
}
// TODO(xiaofeng): Set Enum "options".
}
string GetTypeUrl(const Descriptor* descriptor) {
return url_prefix_ + "/" + descriptor->full_name();
}
string GetTypeUrl(const EnumDescriptor* descriptor) {
return url_prefix_ + "/" + descriptor->full_name();
}
string DefaultValueAsString(const FieldDescriptor* descriptor) {
switch (descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return SimpleItoa(descriptor->default_value_int32());
break;
case FieldDescriptor::CPPTYPE_INT64:
return SimpleItoa(descriptor->default_value_int64());
break;
case FieldDescriptor::CPPTYPE_UINT32:
return SimpleItoa(descriptor->default_value_uint32());
break;
case FieldDescriptor::CPPTYPE_UINT64:
return SimpleItoa(descriptor->default_value_uint64());
break;
case FieldDescriptor::CPPTYPE_FLOAT:
return SimpleFtoa(descriptor->default_value_float());
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
return SimpleDtoa(descriptor->default_value_double());
break;
case FieldDescriptor::CPPTYPE_BOOL:
return descriptor->default_value_bool() ? "true" : "false";
break;
case FieldDescriptor::CPPTYPE_STRING:
if (descriptor->type() == FieldDescriptor::TYPE_BYTES) {
return CEscape(descriptor->default_value_string());
} else {
return descriptor->default_value_string();
}
break;
case FieldDescriptor::CPPTYPE_ENUM:
return descriptor->default_value_enum()->name();
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
GOOGLE_LOG(DFATAL) << "Messages can't have default values!";
break;
}
return "";
}
string url_prefix_;
const DescriptorPool* pool_;
};
} // namespace
TypeResolver* NewTypeResolverForDescriptorPool(const string& url_prefix,
const DescriptorPool* pool) {
return new DescriptorPoolTypeResolver(url_prefix, pool);
}
} // namespace util
} // namespace protobuf
} // namespace google
| {
"pile_set_name": "Github"
} |
(define (script-fu-shadows-highlights image drawable shadows highlights)
; create a highlights layer
(let ((highlights-layer (car (gimp-layer-copy drawable 1))))
(gimp-drawable-set-name highlights-layer "fix highlights (adjust opacity)")
(gimp-image-add-layer image highlights-layer -1)
;process shadows/highlights layer
(gimp-desaturate highlights-layer)
(gimp-invert highlights-layer)
(gimp-layer-set-mode highlights-layer 5)
(plug-in-gauss-iir2 1 image highlights-layer 25 25)
;copy highlights layer to create shadows layer
(define shadows-layer (car (gimp-layer-copy highlights-layer 1)))
(gimp-drawable-set-name shadows-layer "fix shadows (adjust opacity)")
(gimp-image-add-layer image shadows-layer -1)
;process highlights layer
(plug-in-colortoalpha 1 image highlights-layer '(255 255 255))
(gimp-layer-set-opacity highlights-layer highlights)
;process shadows layer
(plug-in-colortoalpha 1 image shadows-layer '(0 0 0))
(gimp-layer-set-opacity shadows-layer shadows)
;update image window
(gimp-displays-flush)))
(script-fu-register "script-fu-shadows-highlights"
_"<Image>/Filters/Light and Shadow/Shadows & Highlights"
"Removes shadows and highlights from a photograph - adapted from http://mailgate.supereva.com/comp/comp.graphics.apps.gimp/msg06394.html"
"Dennis Bond - thanks to Jozef Trawinski"
"Dennis Bond - thanks to Jozef Trawinski"
"October 24, 2007"
"RGB* GRAY*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-ADJUSTMENT "Shadows" '(50 0 100 1 1 0 0)
SF-ADJUSTMENT "Highlights" '(0 0 100 1 1 0 0))
| {
"pile_set_name": "Github"
} |
import fetch from 'node-fetch';
const METAWEATHER_API_URL = "https://www.metaweather.com/api/location/";
const getWeather = (data) => {
return fetch(METAWEATHER_API_URL + data.woeid)
.then(response => response.json())
};
// get woeid (where on earth id) using city name
const getWoeid = (place) => {
return fetch(`${METAWEATHER_API_URL}search/?query=${place}`)
.then(response => response.json())
.then(jsonResponse => jsonResponse[0])
};
// resolvers -> get where on earth id -> get consolidated_weather data and return
const resolvers = {
Query: {
cityWeather: (root, args, context, info) => {
return getWoeid(args.city_name).then( (response) => {
if (!response) {
return null;
}
return getWeather(response).then( (weather) => {
if (!weather) {
return null;
}
let consolidated_weather = weather.consolidated_weather;
// check for args applicable_date to apply filter
consolidated_weather = args.applicable_date ? consolidated_weather.find(item => item.applicable_date === args.applicable_date) : consolidated_weather[0];
const respObj = {'temp': consolidated_weather.the_temp.toString(), 'min_temp': consolidated_weather.min_temp.toString(), 'max_temp': consolidated_weather.max_temp.toString(), 'city_name': weather.title, 'applicable_date': consolidated_weather.applicable_date};
return respObj;
});
});
}
},
};
export default resolvers;
| {
"pile_set_name": "Github"
} |
/* global window, global */
const moduleExports = require('./index');
const _global = typeof window === 'undefined' ? global : window;
// @ts-ignore
_global.loaders = _global.loaders || {};
// @ts-ignore
module.exports = Object.assign(_global.loaders, moduleExports);
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.example.sharding.raw.jdbc;
import org.apache.shardingsphere.example.core.api.ExampleExecuteTemplate;
import org.apache.shardingsphere.example.core.api.service.ExampleService;
import org.apache.shardingsphere.example.core.jdbc.service.OrderServiceImpl;
import org.apache.shardingsphere.example.sharding.raw.jdbc.factory.YamlDataSourceFactory;
import org.apache.shardingsphere.example.type.ShardingType;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
/*
* Please make sure primary-replica-replication data sync on MySQL is running correctly. Otherwise this example will query empty data from replica.
*/
public final class YamlConfigurationExampleMain {
private static ShardingType shardingType = ShardingType.SHARDING_DATABASES;
// private static ShardingType shardingType = ShardingType.SHARDING_TABLES;
// private static ShardingType shardingType = ShardingType.SHARDING_DATABASES_AND_TABLES;
// private static ShardingType shardingType = ShardingType.PRIMARY_REPLICA_REPLICATION;
// private static ShardingType shardingType = ShardingType.SHARDING_PRIMARY_REPLICA_REPLICATION;
public static void main(final String[] args) throws SQLException, IOException {
DataSource dataSource = YamlDataSourceFactory.newInstance(shardingType);
ExampleExecuteTemplate.run(getExampleService(dataSource));
}
private static ExampleService getExampleService(final DataSource dataSource) {
return new OrderServiceImpl(dataSource);
}
}
| {
"pile_set_name": "Github"
} |
/*!
@file
Defines `boost::hana::take_front` and `boost::hana::take_front_c`.
@copyright Louis Dionne 2013-2016
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_TAKE_FRONT_HPP
#define BOOST_HANA_TAKE_FRONT_HPP
#include <boost/hana/fwd/take_front.hpp>
#include <boost/hana/at.hpp>
#include <boost/hana/concept/integral_constant.hpp>
#include <boost/hana/concept/sequence.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/core/make.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/length.hpp>
#include <cstddef>
#include <utility>
BOOST_HANA_NAMESPACE_BEGIN
//! @cond
template <typename Xs, typename N>
constexpr auto take_front_t::operator()(Xs&& xs, N const& n) const {
using S = typename hana::tag_of<Xs>::type;
using TakeFront = BOOST_HANA_DISPATCH_IF(take_front_impl<S>,
hana::Sequence<S>::value &&
hana::IntegralConstant<N>::value
);
#ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
static_assert(hana::Sequence<S>::value,
"hana::take_front(xs, n) requires 'xs' to be a Sequence");
static_assert(hana::IntegralConstant<N>::value,
"hana::take_front(xs, n) requires 'n' to be an IntegralConstant");
#endif
return TakeFront::apply(static_cast<Xs&&>(xs), n);
}
//! @endcond
template <typename S, bool condition>
struct take_front_impl<S, when<condition>> : default_ {
template <typename Xs, std::size_t ...n>
static constexpr auto take_front_helper(Xs&& xs, std::index_sequence<n...>) {
return hana::make<S>(hana::at_c<n>(static_cast<Xs&&>(xs))...);
}
template <typename Xs, typename N>
static constexpr auto apply(Xs&& xs, N const&) {
constexpr std::size_t n = N::value;
constexpr std::size_t size = decltype(hana::length(xs))::value;
return take_front_helper(static_cast<Xs&&>(xs),
std::make_index_sequence<(n < size ? n : size)>{});
}
};
template <std::size_t n>
struct take_front_c_t {
template <typename Xs>
constexpr auto operator()(Xs&& xs) const {
return hana::take_front(static_cast<Xs&&>(xs), hana::size_c<n>);
}
};
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_TAKE_FRONT_HPP
| {
"pile_set_name": "Github"
} |
# -*- mode: snippet -*-
# name: __rtruediv__
# key: __rtruediv__
# group: Special methods
# --
def __rtruediv__(self, other):
return $0
| {
"pile_set_name": "Github"
} |
#ifndef LOC_LOSS_LAYERS_HPP_
#define LOC_LOSS_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/loss_layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/* Input: theta
* Output: loss, one single value
*
* This loss layer tends to force the crops to be in the range
* of image space when performing spatial transformation
*/
template <typename Dtype>
class LocLossLayer : public LossLayer<Dtype> {
public:
explicit LocLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "LocLoss"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline bool AllowForceBackward(const int bottom_index) const {
return true;
}
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
private:
int N;
Dtype threshold;
Blob<Dtype> loss_;
};
} // namespace caffe
#endif // LOC_LOSS_LAYERS_HPP_
| {
"pile_set_name": "Github"
} |
package com.univocity.trader.exchange.binance.futures.impl;
import com.univocity.trader.exchange.binance.futures.impl.utils.JsonWrapper;
@FunctionalInterface
public interface RestApiJsonParser<T> {
T parseJson(JsonWrapper json);
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeeHive.Sample.FileImport.Impl.Events
{
public class ImportFileProcessed
{
public string FileId { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
# Send a Single Email to a Single Recipient
The following code assumes you are storing the API key in an environment variable (recommended).
This is the minimum code needed to send an email.
```java
import com.sendgrid.*;
import com.sendgrid.helpers.mail.*;
public class SendGridExample {
public static void main(String[] args) throws SendGridException {
From from = new From("[email protected]", "Example User");
To to = new To("[email protected]", "Example User");
Subject subject = new Subject("Sending with Twilio SendGrid is Fun");
PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java");
HtmlContent htmlContent = new HtmlContent("<strong>and easy to do anywhere, even with Java</strong>");
SendGridMessage email = new SendGridMessage(from,
to,
subject,
plainTextContent,
htmlContent);
SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY"));
try {
SendGridResponse response = sendgrid.send(email);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (SendGridException ex) {
System.err.println(ex);
throw ex;
}
}
}
```
# Send a Single Email to Multiple Recipients
The following code assumes you are storing the API key in an environment variable (recommended).
```java
import com.sendgrid.*;
import com.sendgrid.helpers.mail.*;
import java.util.ArrayList;
public class SendGridExample {
public static void main(String[] args) throws SendGridException {
From from = new From("[email protected]", "Example User");
ArrayList<To> tos = new ArrayList<To>();
tos.add(new To("[email protected]", "Example User1"));
tos.add(new To("[email protected]", "Example User2"));
tos.add(new To("[email protected]", "Example User3"));
Subject subject = new Subject("Sending with Twilio SendGrid is Fun");
PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java");
HtmlContent htmlContent = new HtmlContent("<strong>and easy to do anywhere, even with Java</strong>");
SendGridMessage email = new SendGridMessage(from,
tos,
subject,
plainTextContent,
htmlContent);
SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY"));
try {
SendGridResponse response = sendgrid.send(email);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (SendGridException ex) {
System.err.println(ex);
throw ex;
}
}
}
```
# Send Multiple Emails to Multiple Recipients
The following code assumes you are storing the API key in an environment variable (recommended).
```java
import com.sendgrid.*;
import com.sendgrid.helpers.mail.*;
import java.util.ArrayList;
public class SendGridExample {
public static void main(String[] args) throws SendGridException {
From from = new From("[email protected]", "Example User");
ArrayList<To> tos = new ArrayList<To>();
ArrayList<Substitution> sub = new ArrayList<Substitution>();
sub.add("-name-", "Alain");
sub.add("-github-", "http://github.com/ninsuo");
tos.add(new To("[email protected]", "Example User1"), sub);
sub.clear();
sub.add("-name-", "Elmer");
sub.add("-github-", "http://github.com/thinkingserious");
tos.add(new To("[email protected]", "Example User2"), sub);
sub.clear();
sub.add("-name-", "Casey");
sub.add("-github-", "http://github.com/caseyw");
tos.add(new To("[email protected]", "Example User3"), sub);
// Alternatively, you can pass in a collection of subjects OR add a subject to the `To` object
Subject subject = new Subject("Hi -name-!");
Substitution globalSubstitution = new Substitution("-time-", "<Current Time>");
PlainTextContent plainTextContent = new PlainTextContent("Hello -name-, your github is -github-, email sent at -time-");
HtmlContent htmlContent = new HtmlContent("<strong>Hello -name-, your github is <a href=\"-github-\">here</a></strong> email sent at -time-");
SendGridMessage email = new SendGridMessage(from,
subject, // or subjects,
tos,
plainTextContent,
htmlContent,
globalSubstitution); // or globalSubstitutions
SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY"));
try {
SendGridResponse response = sendgrid.send(email);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (SendGridException ex) {
System.err.println(ex);
throw ex;
}
}
}
```
# Kitchen Sink - an example with all settings used
The following code assumes you are storing the API key in an environment variable (recommended).
```java
import com.sendgrid.*;
import com.sendgrid.helpers.mail.*;
import java.util.ArrayList;
public class SendGridExample {
public static void main(String[] args) throws SendGridException {
From from = new From("[email protected]", "Example User");
To to = new To("[email protected]", "Example User");
Subject subject = new Subject("Sending with Twilio SendGrid is Fun");
PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java");
HtmlContent htmlContent = new HtmlContent("<strong>and easy to do anywhere, even with Java</strong>");
SendGridMessage email = new SendGridMessage(from,
to, // or tos
subject, // or subjects
plainTextContent,
htmlContent);
// For a detailed description of each of these settings, please see the [documentation](https://sendgrid.com/docs/API_Reference/api_v3.html).
email.addTo("[email protected]", "Example User1")
ArrayList<To> tos = new ArrayList<To>();
tos.add("[email protected]", "Example User2");
tos.add("[email protected]", "Example User3");
email.addTos(tos);
email.addCc("[email protected]", "Example User4")
ArrayList<Cc> ccs = new ArrayList<Cc>();
ccs.add("[email protected]", "Example User5");
ccs.add("[email protected]", "Example User6");
email.addCcs(ccs);
email.addBcc("[email protected]", "Example User7")
ArrayList<Bcc> bccs = new ArrayList<Bcc>();
bccs.add("[email protected]", "Example User8");
bccs.add("[email protected]", "Example User9");
email.addBccs(bccs);
email.addHeader("X-Test1", "Test1");
email.addHeader("X-Test2", "Test2");
ArrayList<Header> headers = new ArrayList<Header>();
headers.add("X-Test3", "Test3");
headers.add("X-Test4", "Test4");
email.addHeaders(headers)
email.addSubstitution("%name1%", "Example Name 1");
email.addSubstitution("%city1%", "Denver");
ArrayList<Substitution> substitutions = new ArrayList<Substitution>();
substitutions.add("%name2%", "Example Name 2");
substitutions.add("%city2%", "Orange" );
email.addSubstitutions(substitutions);
email.addCustomArg("marketing1", "false");
email.addCustomArg("transactional1", "true");
ArrayList<CustomArg> customArgs = new ArrayList<CustomArg>();
customArgs.add("marketing2", "true");
customArgs.add("transactional2", "false");
email.addCustomArgs(customArgs);
email.setSendAt(1461775051);
// If you need to add more [Personalizations](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html), here is an example of adding another Personalization by passing in a personalization index
email.addTo("[email protected]", "Example User 10", 1);
ArrayList<To> tos1 = new ArrayList<To>();
tos1.add("[email protected]", "Example User11");
tos1.add("[email protected]", "Example User12");
email.addTos(tos1, 1);
email.addCc("[email protected]", "Example User 13", 1);
ArrayList<Cc> ccs1 = new ArrayList<Cc>();
ccs1.add("[email protected]", "Example User14");
ccs1.add("[email protected]", "Example User15");
email.addCcs(ccs1, 1);
email.addBcc("[email protected]", "Example User 16", 1);
ArrayList<Bcc> bccs1 = new ArrayList<Bcc>();
bccs1.add("[email protected]", "Example User17");
bccs1.add("[email protected]", "Example User18");
email.addBccs(bccs1, 1);
email.addHeader("X-Test5", "Test5", 1);
email.addHeader("X-Test6", "Test6", 1);
ArrayList<Header> headers1 = new ArrayList<Header>();
headers1.add("X-Test7", "Test7");
headers1.add("X-Test8", "Test8");
email.addHeaders(headers1, 1);
email.addSubstitution("%name3%", "Example Name 3", 1);
email.addSubstitution("%city3%", "Redwood City", 1);
ArrayList<Substitution> substitutions1 = new ArrayList<Substitution>();
substitutions1.add("%name4%", "Example Name 4");
substitutions1.add("%city4%", "London");
var substitutions1 = new Dictionary<string, string>()
email.addSubstitutions(substitutions1, 1);
email.addCustomArg("marketing3", "true", 1);
email.addCustomArg("transactional3", "false", 1);
ArrayList<CustomArg> customArgs1 = new ArrayList<CustomArg>();
customArgs1.add("marketing4", "false");
customArgs1.add("transactional4", "true");
email.addCustomArgs(customArgs1, 1);
email.setSendAt(1461775052, 1);
// The values below this comment are global to entire message
email.setFrom("[email protected]", "Example User 0");
email.setSubject("this subject overrides the Global Subject");
email.setGlobalSubject("Sending with Twilio SendGrid is Fun");
email.addContent(MimeType.TEXT, "and easy to do anywhere, even with C#");
email.addContent(MimeType.HTML, "<strong>and easy to do anywhere, even with C#</strong>");
ArrayList<Content> contents = new ArrayList<Content>();
contents.add("text/calendar", "Party Time!!");
contents.add("text/calendar2", "Party Time2!!");
email.addContents(contents);
email.addAttachment("balance_001.pdf",
"base64 encoded string",
"application/pdf",
"attachment",
"Balance Sheet");
ArrayList<Attachment> attachments = new ArrayList<Attachment>();
attachments.add("banner.png",
"base64 encoded string",
"image/png",
"inline",
"Banner");
attachments.add("banner2.png",
"base64 encoded string",
"image/png",
"inline",
"Banner2");
email.addAttachments(attachments);
email.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");
email.addGlobalHeader("X-Day", "Monday");
ArrayList<Header> globalHeaders = new ArrayList<Header>();
globalHeaders.add("X-Month", "January" );
globalHeaders.add("X-Year", "2017");
email.addGlobalHeaders(globalHeaders);
email.addSection("%section1", "Substitution for Section 1 Tag");
ArrayList<Section> sections = new ArrayList<Section>();
sections.add("%section2%", "Substitution for Section 2 Tag");
sections.add("%section3%", "Substitution for Section 3 Tag");
email.addSections(sections);
email.addCategory("customer");
ArrayList<Category> categories = new ArrayList<Category>();
categories.add("vip");
categories.add("new_account");
email.addCategories(categories);
email.addGlobalCustomArg("campaign", "welcome");
ArrayList<CustomArg> globalCustomArgs = new ArrayList<CustomArg>();
globalCustomArgs.add("sequence2", "2");
globalCustomArgs.add("sequence3", "3");
email.addGlobalCustomArgs(globalCustomArgs);
ArrayList<int> asmGroups = new ArrayList<int>();
asmGroups.add(1);
asmGroups.add(4);
asmGroups.add(5);
email.setAsm(3, asmGroups);
email.setGlobalSendAt(1461775051);
email.setIpPoolName("23");
// This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html)
//email.setBatchId("some_batch_id");
email.setBccSetting(true, "[email protected]");
email.setBypassListManagement(true);
email.setFooterSetting(true, "Some Footer HTML", "Some Footer Text");
email.setSandBoxMode(true);
email.setSpamCheck(true, 1, "https://gotchya.example.com");
email.setClickTracking(true, false);
email.setOpenTracking(true, "Optional tag to replace with the open image in the body of the message");
email.setSubscriptionTracking(true,
"HTML to insert into the text / html portion of the message",
"text to insert into the text/plain portion of the message",
"substitution tag");
email.setGoogleAnalytics(true,
"some campaign",
"some content",
"some medium",
"some source",
"some term");
email.setReplyTo("[email protected]", "Reply To Me");
SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY"));
try {
SendGridResponse response = sendgrid.send(email);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (SendGridException ex) {
System.err.println(ex);
throw ex;
}
}
}
```
# Attachments
The following code assumes you are storing the API key in an environment variable (recommended).
```java
import com.sendgrid.*;
import com.sendgrid.helpers.mail.*;
public class SendGridExample {
public static void main(String[] args) throws SendGridException {
From from = new From("[email protected]", "Example User");
To to = new To("[email protected]", "Example User");
Subject subject = new Subject("Sending with Twilio SendGrid is Fun");
PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java");
HtmlContent htmlContent = new HtmlContent("<strong>and easy to do anywhere, even with Java</strong>");
SendGridMessage email = new SendGridMessage(from,
to,
subject,
plainTextContent,
htmlContent);
email.addAttachment("balance_001.pdf",
"base64 encoded string",
"application/pdf",
"attachment",
"Balance Sheet");
SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY"));
try {
SendGridResponse response = sendgrid.send(email);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (SendGridException ex) {
System.err.println(ex);
throw ex;
}
}
}
```
# Transactional Templates
The following code assumes you are storing the API key in an environment variable (recommended).
For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing.
Template ID (replace with your own):
```text
13b8f94f-bcae-4ec6-b752-70d6cb59f932
```
Email Subject:
```text
<%subject%>
```
Template Body:
```html
<html>
<head>
<title></title>
</head>
<body>
Hello -name-,
<br /><br/>
I'm glad you are trying out the template feature!
<br /><br/>
<%body%>
<br /><br/>
I hope you are having a great day in -city- :)
<br /><br/>
</body>
</html>
```
```java
import com.sendgrid.*;
import com.sendgrid.helpers.mail.*;
public class SendGridExample {
public static void main(String[] args) throws SendGridException {
From from = new From("[email protected]", "Example User");
To to = new To("[email protected]", "Example User");
Subject subject = new Subject("Sending with Twilio SendGrid is Fun");
PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java");
HtmlContent htmlContent = new HtmlContent("<strong>and easy to do anywhere, even with Java</strong>");
SendGridMessage email = new SendGridMessage(from,
to,
subject,
plainTextContent,
htmlContent);
// See `Send Multiple Emails to Multiple Recipients` for additional methods for adding substitutions
email.addSubstitution("-name-", "Example User");
email.addSubstitution("-city-", "Denver");
email.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");
SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY"));
try {
SendGridResponse response = sendgrid.send(email);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (SendGridException ex) {
System.err.println(ex);
throw ex;
}
}
}
```
| {
"pile_set_name": "Github"
} |
QA output created by 107
=== Updates should not write random data ===
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=65536
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 65528/65528 bytes at offset 196616
63.992 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
*** done
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.subdomains.base.applib.utils;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class MathUtilsTest {
public static class IsZeroOrNull extends MathUtilsTest {
@Test
public void testIsZeroOrNull() {
Assert.assertTrue(MathUtils.isZeroOrNull(null));
Assert.assertTrue(MathUtils.isZeroOrNull(BigDecimal.valueOf(0)));
Assert.assertFalse(MathUtils.isZeroOrNull(BigDecimal.valueOf(100)));
Assert.assertFalse(MathUtils.isNotZeroOrNull(null));
Assert.assertFalse(MathUtils.isNotZeroOrNull(BigDecimal.valueOf(0)));
Assert.assertTrue(MathUtils.isNotZeroOrNull(BigDecimal.valueOf(100)));
}
}
public static class Round extends MathUtilsTest {
@Test
public void roundDown() throws Exception {
assertThat(MathUtils.round(new BigDecimal("4.54"), 1), is(new BigDecimal("4.5")));
}
@Test
public void noRounding() throws Exception {
assertThat(MathUtils.round(new BigDecimal("4.54"), 2), is(new BigDecimal("4.54")));
}
@Test
public void roundUp() throws Exception {
assertThat(MathUtils.round(new BigDecimal("4.55"), 1), is(new BigDecimal("4.6")));
}
}
public static class Max extends MathUtilsTest {
@Test
public void happyCase() throws Exception {
assertThat(MathUtils.max(null, BigDecimal.ZERO, new BigDecimal("123.45"), new BigDecimal("123")), is(new BigDecimal("123.45")));
}
}
public static class SomeThing extends MathUtilsTest {
@Test
public void happyCase() throws Exception {
assertThat(MathUtils.maxUsingFirstSignum(new BigDecimal("-123.45"), new BigDecimal("-123")), is(new BigDecimal("-123.45")));
assertThat(MathUtils.maxUsingFirstSignum(null, BigDecimal.ZERO, new BigDecimal("-123.45"), new BigDecimal("-123")), is(new BigDecimal("-123.45")));
}
}
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=99:
*/
#include "tests.h"
#include "jsstr.h"
BEGIN_TEST(testIntString_bug515273)
{
jsvalRoot v(cx);
EVAL("'1';", v.addr());
JSString *str = JSVAL_TO_STRING(v.value());
CHECK(JSString::isStatic(str));
CHECK(JS_FlatStringEqualsAscii(JS_ASSERT_STRING_IS_FLAT(str), "1"));
EVAL("'42';", v.addr());
str = JSVAL_TO_STRING(v.value());
CHECK(JSString::isStatic(str));
CHECK(JS_FlatStringEqualsAscii(JS_ASSERT_STRING_IS_FLAT(str), "42"));
EVAL("'111';", v.addr());
str = JSVAL_TO_STRING(v.value());
CHECK(JSString::isStatic(str));
CHECK(JS_FlatStringEqualsAscii(JS_ASSERT_STRING_IS_FLAT(str), "111"));
/* Test other types of static strings. */
EVAL("'a';", v.addr());
str = JSVAL_TO_STRING(v.value());
CHECK(JSString::isStatic(str));
CHECK(JS_FlatStringEqualsAscii(JS_ASSERT_STRING_IS_FLAT(str), "a"));
EVAL("'bc';", v.addr());
str = JSVAL_TO_STRING(v.value());
CHECK(JSString::isStatic(str));
CHECK(JS_FlatStringEqualsAscii(JS_ASSERT_STRING_IS_FLAT(str), "bc"));
return true;
}
END_TEST(testIntString_bug515273)
| {
"pile_set_name": "Github"
} |
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'lib', 'whiskey_disk'))
integration_spec do
describe 'when configured for a remote deployment' do
before do
setup_deployment_area
end
describe 'with a single remote domain' do
before do
@config = scenario_config('remote/deploy.yml')
@args = "--path=#{@config} --to=project:remote"
end
describe 'performing a setup' do
it 'performs a checkout of the repository to the target path' do
run_setup(@args)
File.exists?(deployed_file('project/README')).should == true
end
it 'has the working copy set to the master branch' do
run_setup(@args)
current_branch('project').should == 'master'
end
it 'has the working copy set to the specified branch when one is available' do
@args = "--path=#{@config} --to=project:remote-on-other-branch"
run_setup(@args)
current_branch('project').should == 'no_rake_hooks'
end
it 'reports the remote setup as successful' do
run_setup(@args)
File.read(integration_log).should =~ /vagrant => succeeded/
end
it 'exits with a true status' do
run_setup(@args).should == true
end
end
describe 'performing a deployment' do
before do
checkout_repo('project')
File.unlink(deployed_file('project/README')) # modify the deployed checkout
end
it 'updates the checkout of the repository on the target path' do
run_deploy(@args)
File.exists?(deployed_file('project/README')).should == true
end
it 'has the working copy set to the master branch' do
run_deploy(@args)
current_branch('project').should == 'master'
end
it 'has the working copy set to the specified branch when one is available' do
@args = "--path=#{@config} --to=project:remote-on-other-branch"
checkout_branch('project', 'no_rake_hooks')
run_deploy(@args)
current_branch('project').should == 'no_rake_hooks'
end
it 'reports the remote deployment as successful' do
run_deploy(@args)
File.read(integration_log).should =~ /vagrant => succeeded/
end
it 'exits with a true status' do
run_deploy(@args).should == true
end
end
describe 'performing a deploy after a setup' do
describe 'and using the master branch' do
before do
run_setup(@args)
File.unlink(deployed_file('project/README')) # modify the deployed checkout
end
it 'updates the checkout of the repository on the target path' do
run_deploy(@args)
File.exists?(deployed_file('project/README')).should == true
end
it 'has the working copy set to the master branch' do
run_deploy(@args)
current_branch('project').should == 'master'
end
it 'has the working copy set to the specified branch when one is available' do
setup_deployment_area
@args = "--path=#{@config} --to=project:remote-on-other-branch"
run_setup(@args)
File.unlink(deployed_file('project/README'))
run_deploy(@args)
current_branch('project').should == 'no_rake_hooks'
end
it 'reports the remote deployment as successful' do
run_deploy(@args)
File.read(integration_log).should =~ /vagrant => succeeded/
end
it 'exits with a true status' do
run_deploy(@args).should == true
end
end
end
end
describe 'with ssh options specified' do
before do
@config = scenario_config('remote/deploy.yml')
@args = "--path=#{@config} --to=project:with_ssh_options"
end
describe 'performing a setup' do
# TODO FIXME -- this spec fails due to interplay between STDOUT and file buffering in ruby system() (*WTF*)
#
# it 'uses specified ssh options when performing the setup' do
# run_setup(@args)
# dump_log
# File.read(integration_log).should =~ /ssh.* -t /
# end
it 'reports the remote setup as successful' do
run_setup(@args)
File.read(integration_log).should =~ /vagrant => succeeded/
end
it 'exits with a true status' do
run_setup(@args).should == true
end
end
describe 'performing a deployment' do
before do
checkout_repo('project')
File.unlink(deployed_file('project/README')) # modify the deployed checkout
end
# TODO FIXME -- this spec fails due to interplay between STDOUT and file buffering in ruby system() (*WTF*)
#
# it 'uses specified ssh options when performing the setup' do
# run_deploy(@args, true)
# File.read(integration_log).should =~ /ssh.* -t /
# end
it 'reports the remote deployment as successful' do
run_deploy(@args)
File.read(integration_log).should =~ /vagrant => succeeded/
end
it 'exits with a true status' do
run_deploy(@args).should == true
end
end
end
end
end | {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>0.9.9 API documenation: GLM_GTC_round</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">0.9.9 API documenation
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">GLM_GTC_round<div class="ingroups"><a class="el" href="a00153.html">GTC Extensions (Stable)</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>rounding value to specific boundings
<a href="#details">More...</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:gac84898c466e609cdd2e81d9ba907d9e8"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:gac84898c466e609cdd2e81d9ba907d9e8"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gac84898c466e609cdd2e81d9ba907d9e8">ceilMultiple</a> (genType Source, genType Multiple)</td></tr>
<tr class="memdesc:gac84898c466e609cdd2e81d9ba907d9e8"><td class="mdescLeft"> </td><td class="mdescRight">Higher multiple number of Source. <a href="a00175.html#gac84898c466e609cdd2e81d9ba907d9e8">More...</a><br /></td></tr>
<tr class="separator:gac84898c466e609cdd2e81d9ba907d9e8"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gafe632af669ac57d670ca18e3665a12ca"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:gafe632af669ac57d670ca18e3665a12ca"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< T, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gafe632af669ac57d670ca18e3665a12ca">ceilMultiple</a> (vecType< T, P > const &Source, vecType< T, P > const &Multiple)</td></tr>
<tr class="memdesc:gafe632af669ac57d670ca18e3665a12ca"><td class="mdescLeft"> </td><td class="mdescRight">Higher multiple number of Source. <a href="a00175.html#gafe632af669ac57d670ca18e3665a12ca">More...</a><br /></td></tr>
<tr class="separator:gafe632af669ac57d670ca18e3665a12ca"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gaa73c7690c787086fa3ac1c312264acab"><td class="memTemplParams" colspan="2">template<typename genIUType > </td></tr>
<tr class="memitem:gaa73c7690c787086fa3ac1c312264acab"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genIUType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gaa73c7690c787086fa3ac1c312264acab">ceilPowerOfTwo</a> (genIUType Value)</td></tr>
<tr class="memdesc:gaa73c7690c787086fa3ac1c312264acab"><td class="mdescLeft"> </td><td class="mdescRight">Return the power of two number which value is just higher the input value, round up to a power of two. <a href="a00175.html#gaa73c7690c787086fa3ac1c312264acab">More...</a><br /></td></tr>
<tr class="separator:gaa73c7690c787086fa3ac1c312264acab"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga76ec9b214ea1376fe09a903e34bab847"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:ga76ec9b214ea1376fe09a903e34bab847"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< T, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga76ec9b214ea1376fe09a903e34bab847">ceilPowerOfTwo</a> (vecType< T, P > const &value)</td></tr>
<tr class="memdesc:ga76ec9b214ea1376fe09a903e34bab847"><td class="mdescLeft"> </td><td class="mdescRight">Return the power of two number which value is just higher the input value, round up to a power of two. <a href="a00175.html#ga76ec9b214ea1376fe09a903e34bab847">More...</a><br /></td></tr>
<tr class="separator:ga76ec9b214ea1376fe09a903e34bab847"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga9eafb9dbedf84e5cece65c2fe9d5631d"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:ga9eafb9dbedf84e5cece65c2fe9d5631d"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga9eafb9dbedf84e5cece65c2fe9d5631d">floorMultiple</a> (genType Source, genType Multiple)</td></tr>
<tr class="memdesc:ga9eafb9dbedf84e5cece65c2fe9d5631d"><td class="mdescLeft"> </td><td class="mdescRight">Lower multiple number of Source. <a href="a00175.html#ga9eafb9dbedf84e5cece65c2fe9d5631d">More...</a><br /></td></tr>
<tr class="separator:ga9eafb9dbedf84e5cece65c2fe9d5631d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga6912db42d43873fe1dedb3aed2b7a239"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:ga6912db42d43873fe1dedb3aed2b7a239"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< T, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga6912db42d43873fe1dedb3aed2b7a239">floorMultiple</a> (vecType< T, P > const &Source, vecType< T, P > const &Multiple)</td></tr>
<tr class="memdesc:ga6912db42d43873fe1dedb3aed2b7a239"><td class="mdescLeft"> </td><td class="mdescRight">Lower multiple number of Source. <a href="a00175.html#ga6912db42d43873fe1dedb3aed2b7a239">More...</a><br /></td></tr>
<tr class="separator:ga6912db42d43873fe1dedb3aed2b7a239"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gac80f6519c31baae10d8d7bea6735d1fa"><td class="memTemplParams" colspan="2">template<typename genIUType > </td></tr>
<tr class="memitem:gac80f6519c31baae10d8d7bea6735d1fa"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genIUType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gac80f6519c31baae10d8d7bea6735d1fa">floorPowerOfTwo</a> (genIUType Value)</td></tr>
<tr class="memdesc:gac80f6519c31baae10d8d7bea6735d1fa"><td class="mdescLeft"> </td><td class="mdescRight">Return the power of two number which value is just lower the input value, round down to a power of two. <a href="a00175.html#gac80f6519c31baae10d8d7bea6735d1fa">More...</a><br /></td></tr>
<tr class="separator:gac80f6519c31baae10d8d7bea6735d1fa"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga6a5a8f6dd1b2f755e4572bd039062c37"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:ga6a5a8f6dd1b2f755e4572bd039062c37"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< T, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga6a5a8f6dd1b2f755e4572bd039062c37">floorPowerOfTwo</a> (vecType< T, P > const &value)</td></tr>
<tr class="memdesc:ga6a5a8f6dd1b2f755e4572bd039062c37"><td class="mdescLeft"> </td><td class="mdescRight">Return the power of two number which value is just lower the input value, round down to a power of two. <a href="a00175.html#ga6a5a8f6dd1b2f755e4572bd039062c37">More...</a><br /></td></tr>
<tr class="separator:ga6a5a8f6dd1b2f755e4572bd039062c37"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gaf7444a7b2eb524f373463ceba76b9326"><td class="memTemplParams" colspan="2">template<typename genIUType > </td></tr>
<tr class="memitem:gaf7444a7b2eb524f373463ceba76b9326"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL bool </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gaf7444a7b2eb524f373463ceba76b9326">isMultiple</a> (genIUType Value, genIUType Multiple)</td></tr>
<tr class="memdesc:gaf7444a7b2eb524f373463ceba76b9326"><td class="mdescLeft"> </td><td class="mdescRight">Return true if the 'Value' is a multiple of 'Multiple'. <a href="a00175.html#gaf7444a7b2eb524f373463ceba76b9326">More...</a><br /></td></tr>
<tr class="separator:gaf7444a7b2eb524f373463ceba76b9326"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga50ea5d5dc33fffba39ad6002a3784123"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:ga50ea5d5dc33fffba39ad6002a3784123"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< bool, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga50ea5d5dc33fffba39ad6002a3784123">isMultiple</a> (vecType< T, P > const &Value, T Multiple)</td></tr>
<tr class="memdesc:ga50ea5d5dc33fffba39ad6002a3784123"><td class="mdescLeft"> </td><td class="mdescRight">Return true if the 'Value' is a multiple of 'Multiple'. <a href="a00175.html#ga50ea5d5dc33fffba39ad6002a3784123">More...</a><br /></td></tr>
<tr class="separator:ga50ea5d5dc33fffba39ad6002a3784123"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga7ae705574ef3e3ebfb4f537d8d285c48"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:ga7ae705574ef3e3ebfb4f537d8d285c48"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< bool, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga7ae705574ef3e3ebfb4f537d8d285c48">isMultiple</a> (vecType< T, P > const &Value, vecType< T, P > const &Multiple)</td></tr>
<tr class="memdesc:ga7ae705574ef3e3ebfb4f537d8d285c48"><td class="mdescLeft"> </td><td class="mdescRight">Return true if the 'Value' is a multiple of 'Multiple'. <a href="a00175.html#ga7ae705574ef3e3ebfb4f537d8d285c48">More...</a><br /></td></tr>
<tr class="separator:ga7ae705574ef3e3ebfb4f537d8d285c48"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gaebf826fbb6e0a70eeaab0792d89b25ec"><td class="memTemplParams" colspan="2">template<typename genIUType > </td></tr>
<tr class="memitem:gaebf826fbb6e0a70eeaab0792d89b25ec"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL bool </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gaebf826fbb6e0a70eeaab0792d89b25ec">isPowerOfTwo</a> (genIUType Value)</td></tr>
<tr class="memdesc:gaebf826fbb6e0a70eeaab0792d89b25ec"><td class="mdescLeft"> </td><td class="mdescRight">Return true if the value is a power of two number. <a href="a00175.html#gaebf826fbb6e0a70eeaab0792d89b25ec">More...</a><br /></td></tr>
<tr class="separator:gaebf826fbb6e0a70eeaab0792d89b25ec"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gad454e4c8d8cd73ddc7de855f733a1465"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:gad454e4c8d8cd73ddc7de855f733a1465"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< bool, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gad454e4c8d8cd73ddc7de855f733a1465">isPowerOfTwo</a> (vecType< T, P > const &value)</td></tr>
<tr class="memdesc:gad454e4c8d8cd73ddc7de855f733a1465"><td class="mdescLeft"> </td><td class="mdescRight">Return true if the value is a power of two number. <a href="a00175.html#gad454e4c8d8cd73ddc7de855f733a1465">More...</a><br /></td></tr>
<tr class="separator:gad454e4c8d8cd73ddc7de855f733a1465"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga6739d1de04b2cea7c78675b365644bce"><td class="memTemplParams" colspan="2">template<typename genType > </td></tr>
<tr class="memitem:ga6739d1de04b2cea7c78675b365644bce"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga6739d1de04b2cea7c78675b365644bce">roundMultiple</a> (genType Source, genType Multiple)</td></tr>
<tr class="memdesc:ga6739d1de04b2cea7c78675b365644bce"><td class="mdescLeft"> </td><td class="mdescRight">Lower multiple number of Source. <a href="a00175.html#ga6739d1de04b2cea7c78675b365644bce">More...</a><br /></td></tr>
<tr class="separator:ga6739d1de04b2cea7c78675b365644bce"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga10a8ab7b254257b607b6a3fc68c3e661"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:ga10a8ab7b254257b607b6a3fc68c3e661"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< T, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga10a8ab7b254257b607b6a3fc68c3e661">roundMultiple</a> (vecType< T, P > const &Source, vecType< T, P > const &Multiple)</td></tr>
<tr class="memdesc:ga10a8ab7b254257b607b6a3fc68c3e661"><td class="mdescLeft"> </td><td class="mdescRight">Lower multiple number of Source. <a href="a00175.html#ga10a8ab7b254257b607b6a3fc68c3e661">More...</a><br /></td></tr>
<tr class="separator:ga10a8ab7b254257b607b6a3fc68c3e661"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ga6d24a9e3abe3e6a908661b43acb8efe0"><td class="memTemplParams" colspan="2">template<typename genIUType > </td></tr>
<tr class="memitem:ga6d24a9e3abe3e6a908661b43acb8efe0"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genIUType </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#ga6d24a9e3abe3e6a908661b43acb8efe0">roundPowerOfTwo</a> (genIUType Value)</td></tr>
<tr class="memdesc:ga6d24a9e3abe3e6a908661b43acb8efe0"><td class="mdescLeft"> </td><td class="mdescRight">Return the power of two number which value is the closet to the input value. <a href="a00175.html#ga6d24a9e3abe3e6a908661b43acb8efe0">More...</a><br /></td></tr>
<tr class="separator:ga6d24a9e3abe3e6a908661b43acb8efe0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:gae95be3b384f3bbd00c6c1cf0a1f96485"><td class="memTemplParams" colspan="2">template<typename T , precision P, template< typename, precision > class vecType> </td></tr>
<tr class="memitem:gae95be3b384f3bbd00c6c1cf0a1f96485"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL vecType< T, P > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00175.html#gae95be3b384f3bbd00c6c1cf0a1f96485">roundPowerOfTwo</a> (vecType< T, P > const &value)</td></tr>
<tr class="memdesc:gae95be3b384f3bbd00c6c1cf0a1f96485"><td class="mdescLeft"> </td><td class="mdescRight">Return the power of two number which value is the closet to the input value. <a href="a00175.html#gae95be3b384f3bbd00c6c1cf0a1f96485">More...</a><br /></td></tr>
<tr class="separator:gae95be3b384f3bbd00c6c1cf0a1f96485"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<p>rounding value to specific boundings </p>
<p><<a class="el" href="a00096.html" title="GLM_GTC_round ">glm/gtc/round.hpp</a>> need to be included to use these functionalities. </p>
<h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="gac84898c466e609cdd2e81d9ba907d9e8"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genType glm::ceilMultiple </td>
<td>(</td>
<td class="paramtype">genType </td>
<td class="paramname"><em>Source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">genType </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Higher multiple number of Source. </p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">genType</td><td>Floating-point or integer scalar or vector types. </td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">Source</td><td></td></tr>
<tr><td class="paramname">Multiple</td><td>Must be a null or positive value</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gafe632af669ac57d670ca18e3665a12ca"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<T, P> glm::ceilMultiple </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Higher multiple number of Source. </p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">genType</td><td>Floating-point or integer scalar or vector types. </td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">Source</td><td></td></tr>
<tr><td class="paramname">Multiple</td><td>Must be a null or positive value</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gaa73c7690c787086fa3ac1c312264acab"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genIUType glm::ceilPowerOfTwo </td>
<td>(</td>
<td class="paramtype">genIUType </td>
<td class="paramname"><em>Value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return the power of two number which value is just higher the input value, round up to a power of two. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga76ec9b214ea1376fe09a903e34bab847"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<T, P> glm::ceilPowerOfTwo </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return the power of two number which value is just higher the input value, round up to a power of two. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga9eafb9dbedf84e5cece65c2fe9d5631d"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genType glm::floorMultiple </td>
<td>(</td>
<td class="paramtype">genType </td>
<td class="paramname"><em>Source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">genType </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Lower multiple number of Source. </p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">genType</td><td>Floating-point or integer scalar or vector types. </td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">Source</td><td></td></tr>
<tr><td class="paramname">Multiple</td><td>Must be a null or positive value</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga6912db42d43873fe1dedb3aed2b7a239"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<T, P> glm::floorMultiple </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Lower multiple number of Source. </p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">genType</td><td>Floating-point or integer scalar or vector types. </td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">Source</td><td></td></tr>
<tr><td class="paramname">Multiple</td><td>Must be a null or positive value</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gac80f6519c31baae10d8d7bea6735d1fa"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genIUType glm::floorPowerOfTwo </td>
<td>(</td>
<td class="paramtype">genIUType </td>
<td class="paramname"><em>Value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return the power of two number which value is just lower the input value, round down to a power of two. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga6a5a8f6dd1b2f755e4572bd039062c37"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<T, P> glm::floorPowerOfTwo </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return the power of two number which value is just lower the input value, round down to a power of two. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gaf7444a7b2eb524f373463ceba76b9326"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL bool glm::isMultiple </td>
<td>(</td>
<td class="paramtype">genIUType </td>
<td class="paramname"><em>Value</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">genIUType </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return true if the 'Value' is a multiple of 'Multiple'. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga50ea5d5dc33fffba39ad6002a3784123"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<bool, P> glm::isMultiple </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Value</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">T </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return true if the 'Value' is a multiple of 'Multiple'. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga7ae705574ef3e3ebfb4f537d8d285c48"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<bool, P> glm::isMultiple </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Value</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return true if the 'Value' is a multiple of 'Multiple'. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gaebf826fbb6e0a70eeaab0792d89b25ec"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL bool glm::isPowerOfTwo </td>
<td>(</td>
<td class="paramtype">genIUType </td>
<td class="paramname"><em>Value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return true if the value is a power of two number. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gad454e4c8d8cd73ddc7de855f733a1465"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<bool, P> glm::isPowerOfTwo </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return true if the value is a power of two number. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga6739d1de04b2cea7c78675b365644bce"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genType glm::roundMultiple </td>
<td>(</td>
<td class="paramtype">genType </td>
<td class="paramname"><em>Source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">genType </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Lower multiple number of Source. </p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">genType</td><td>Floating-point or integer scalar or vector types. </td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">Source</td><td></td></tr>
<tr><td class="paramname">Multiple</td><td>Must be a null or positive value</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga10a8ab7b254257b607b6a3fc68c3e661"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<T, P> glm::roundMultiple </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>Multiple</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Lower multiple number of Source. </p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">genType</td><td>Floating-point or integer scalar or vector types. </td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">Source</td><td></td></tr>
<tr><td class="paramname">Multiple</td><td>Must be a null or positive value</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="ga6d24a9e3abe3e6a908661b43acb8efe0"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL genIUType glm::roundPowerOfTwo </td>
<td>(</td>
<td class="paramtype">genIUType </td>
<td class="paramname"><em>Value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return the power of two number which value is the closet to the input value. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
<a class="anchor" id="gae95be3b384f3bbd00c6c1cf0a1f96485"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">GLM_FUNC_DECL vecType<T, P> glm::roundPowerOfTwo </td>
<td>(</td>
<td class="paramtype">vecType< T, P > const & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Return the power of two number which value is the closet to the input value. </p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="a00175.html" title="rounding value to specific boundings ">GLM_GTC_round</a> </dd></dl>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.10
</small></address>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* pkcs12.h */
/* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL
* project 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/
#ifndef HEADER_PKCS12_H
#define HEADER_PKCS12_H
#include <openssl/bio.h>
#include <openssl/x509.h>
#ifdef __cplusplus
extern "C" {
#endif
#define PKCS12_KEY_ID 1
#define PKCS12_IV_ID 2
#define PKCS12_MAC_ID 3
/* Default iteration count */
#ifndef PKCS12_DEFAULT_ITER
#define PKCS12_DEFAULT_ITER PKCS5_DEFAULT_ITER
#endif
#define PKCS12_MAC_KEY_LENGTH 20
#define PKCS12_SALT_LEN 8
/* Uncomment out next line for unicode password and names, otherwise ASCII */
/*#define PBE_UNICODE*/
#ifdef PBE_UNICODE
#define PKCS12_key_gen PKCS12_key_gen_uni
#define PKCS12_add_friendlyname PKCS12_add_friendlyname_uni
#else
#define PKCS12_key_gen PKCS12_key_gen_asc
#define PKCS12_add_friendlyname PKCS12_add_friendlyname_asc
#endif
/* MS key usage constants */
#define KEY_EX 0x10
#define KEY_SIG 0x80
typedef struct {
X509_SIG *dinfo;
ASN1_OCTET_STRING *salt;
ASN1_INTEGER *iter; /* defaults to 1 */
} PKCS12_MAC_DATA;
typedef struct {
ASN1_INTEGER *version;
PKCS12_MAC_DATA *mac;
PKCS7 *authsafes;
} PKCS12;
typedef struct {
ASN1_OBJECT *type;
union {
struct pkcs12_bag_st *bag; /* secret, crl and certbag */
struct pkcs8_priv_key_info_st *keybag; /* keybag */
X509_SIG *shkeybag; /* shrouded key bag */
STACK_OF(PKCS12_SAFEBAG) *safes;
ASN1_TYPE *other;
}value;
STACK_OF(X509_ATTRIBUTE) *attrib;
} PKCS12_SAFEBAG;
DECLARE_STACK_OF(PKCS12_SAFEBAG)
DECLARE_ASN1_SET_OF(PKCS12_SAFEBAG)
DECLARE_PKCS12_STACK_OF(PKCS12_SAFEBAG)
typedef struct pkcs12_bag_st {
ASN1_OBJECT *type;
union {
ASN1_OCTET_STRING *x509cert;
ASN1_OCTET_STRING *x509crl;
ASN1_OCTET_STRING *octet;
ASN1_IA5STRING *sdsicert;
ASN1_TYPE *other; /* Secret or other bag */
}value;
} PKCS12_BAGS;
#define PKCS12_ERROR 0
#define PKCS12_OK 1
/* Compatibility macros */
#define M_PKCS12_x5092certbag PKCS12_x5092certbag
#define M_PKCS12_x509crl2certbag PKCS12_x509crl2certbag
#define M_PKCS12_certbag2x509 PKCS12_certbag2x509
#define M_PKCS12_certbag2x509crl PKCS12_certbag2x509crl
#define M_PKCS12_unpack_p7data PKCS12_unpack_p7data
#define M_PKCS12_pack_authsafes PKCS12_pack_authsafes
#define M_PKCS12_unpack_authsafes PKCS12_unpack_authsafes
#define M_PKCS12_unpack_p7encdata PKCS12_unpack_p7encdata
#define M_PKCS12_decrypt_skey PKCS12_decrypt_skey
#define M_PKCS8_decrypt PKCS8_decrypt
#define M_PKCS12_bag_type(bg) OBJ_obj2nid((bg)->type)
#define M_PKCS12_cert_bag_type(bg) OBJ_obj2nid((bg)->value.bag->type)
#define M_PKCS12_crl_bag_type M_PKCS12_cert_bag_type
#define PKCS12_get_attr(bag, attr_nid) \
PKCS12_get_attr_gen(bag->attrib, attr_nid)
#define PKCS8_get_attr(p8, attr_nid) \
PKCS12_get_attr_gen(p8->attributes, attr_nid)
#define PKCS12_mac_present(p12) ((p12)->mac ? 1 : 0)
PKCS12_SAFEBAG *PKCS12_x5092certbag(X509 *x509);
PKCS12_SAFEBAG *PKCS12_x509crl2certbag(X509_CRL *crl);
X509 *PKCS12_certbag2x509(PKCS12_SAFEBAG *bag);
X509_CRL *PKCS12_certbag2x509crl(PKCS12_SAFEBAG *bag);
PKCS12_SAFEBAG *PKCS12_item_pack_safebag(void *obj, const ASN1_ITEM *it, int nid1,
int nid2);
PKCS12_SAFEBAG *PKCS12_MAKE_KEYBAG(PKCS8_PRIV_KEY_INFO *p8);
PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *p8, const char *pass, int passlen);
PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey(PKCS12_SAFEBAG *bag, const char *pass,
int passlen);
X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher,
const char *pass, int passlen,
unsigned char *salt, int saltlen, int iter,
PKCS8_PRIV_KEY_INFO *p8);
PKCS12_SAFEBAG *PKCS12_MAKE_SHKEYBAG(int pbe_nid, const char *pass,
int passlen, unsigned char *salt,
int saltlen, int iter,
PKCS8_PRIV_KEY_INFO *p8);
PKCS7 *PKCS12_pack_p7data(STACK_OF(PKCS12_SAFEBAG) *sk);
STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7data(PKCS7 *p7);
PKCS7 *PKCS12_pack_p7encdata(int pbe_nid, const char *pass, int passlen,
unsigned char *salt, int saltlen, int iter,
STACK_OF(PKCS12_SAFEBAG) *bags);
STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7encdata(PKCS7 *p7, const char *pass, int passlen);
int PKCS12_pack_authsafes(PKCS12 *p12, STACK_OF(PKCS7) *safes);
STACK_OF(PKCS7) *PKCS12_unpack_authsafes(PKCS12 *p12);
int PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name, int namelen);
int PKCS12_add_friendlyname_asc(PKCS12_SAFEBAG *bag, const char *name,
int namelen);
int PKCS12_add_CSPName_asc(PKCS12_SAFEBAG *bag, const char *name,
int namelen);
int PKCS12_add_friendlyname_uni(PKCS12_SAFEBAG *bag, const unsigned char *name,
int namelen);
int PKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage);
ASN1_TYPE *PKCS12_get_attr_gen(STACK_OF(X509_ATTRIBUTE) *attrs, int attr_nid);
char *PKCS12_get_friendlyname(PKCS12_SAFEBAG *bag);
unsigned char *PKCS12_pbe_crypt(X509_ALGOR *algor, const char *pass,
int passlen, unsigned char *in, int inlen,
unsigned char **data, int *datalen, int en_de);
void * PKCS12_item_decrypt_d2i(X509_ALGOR *algor, const ASN1_ITEM *it,
const char *pass, int passlen, ASN1_OCTET_STRING *oct, int zbuf);
ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor, const ASN1_ITEM *it,
const char *pass, int passlen,
void *obj, int zbuf);
PKCS12 *PKCS12_init(int mode);
int PKCS12_key_gen_asc(const char *pass, int passlen, unsigned char *salt,
int saltlen, int id, int iter, int n,
unsigned char *out, const EVP_MD *md_type);
int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type);
int PKCS12_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md_type,
int en_de);
int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen,
unsigned char *mac, unsigned int *maclen);
int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen);
int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen,
unsigned char *salt, int saltlen, int iter,
const EVP_MD *md_type);
int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt,
int saltlen, const EVP_MD *md_type);
unsigned char *OPENSSL_asc2uni(const char *asc, int asclen, unsigned char **uni, int *unilen);
char *OPENSSL_uni2asc(unsigned char *uni, int unilen);
DECLARE_ASN1_FUNCTIONS(PKCS12)
DECLARE_ASN1_FUNCTIONS(PKCS12_MAC_DATA)
DECLARE_ASN1_FUNCTIONS(PKCS12_SAFEBAG)
DECLARE_ASN1_FUNCTIONS(PKCS12_BAGS)
DECLARE_ASN1_ITEM(PKCS12_SAFEBAGS)
DECLARE_ASN1_ITEM(PKCS12_AUTHSAFES)
void PKCS12_PBE_add(void);
int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert,
STACK_OF(X509) **ca);
PKCS12 *PKCS12_create(char *pass, char *name, EVP_PKEY *pkey, X509 *cert,
STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter,
int mac_iter, int keytype);
PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert);
PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key,
int key_usage, int iter,
int key_nid, char *pass);
int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
int safe_nid, int iter, char *pass);
PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int p7_nid);
int i2d_PKCS12_bio(BIO *bp, PKCS12 *p12);
int i2d_PKCS12_fp(FILE *fp, PKCS12 *p12);
PKCS12 *d2i_PKCS12_bio(BIO *bp, PKCS12 **p12);
PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12);
int PKCS12_newpass(PKCS12 *p12, char *oldpass, char *newpass);
/* BEGIN ERROR CODES */
/* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_PKCS12_strings(void);
/* Error codes for the PKCS12 functions. */
/* Function codes. */
#define PKCS12_F_PARSE_BAG 129
#define PKCS12_F_PARSE_BAGS 103
#define PKCS12_F_PKCS12_ADD_FRIENDLYNAME 100
#define PKCS12_F_PKCS12_ADD_FRIENDLYNAME_ASC 127
#define PKCS12_F_PKCS12_ADD_FRIENDLYNAME_UNI 102
#define PKCS12_F_PKCS12_ADD_LOCALKEYID 104
#define PKCS12_F_PKCS12_CREATE 105
#define PKCS12_F_PKCS12_GEN_MAC 107
#define PKCS12_F_PKCS12_INIT 109
#define PKCS12_F_PKCS12_ITEM_DECRYPT_D2I 106
#define PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT 108
#define PKCS12_F_PKCS12_ITEM_PACK_SAFEBAG 117
#define PKCS12_F_PKCS12_KEY_GEN_ASC 110
#define PKCS12_F_PKCS12_KEY_GEN_UNI 111
#define PKCS12_F_PKCS12_MAKE_KEYBAG 112
#define PKCS12_F_PKCS12_MAKE_SHKEYBAG 113
#define PKCS12_F_PKCS12_NEWPASS 128
#define PKCS12_F_PKCS12_PACK_P7DATA 114
#define PKCS12_F_PKCS12_PACK_P7ENCDATA 115
#define PKCS12_F_PKCS12_PARSE 118
#define PKCS12_F_PKCS12_PBE_CRYPT 119
#define PKCS12_F_PKCS12_PBE_KEYIVGEN 120
#define PKCS12_F_PKCS12_SETUP_MAC 122
#define PKCS12_F_PKCS12_SET_MAC 123
#define PKCS12_F_PKCS12_UNPACK_AUTHSAFES 130
#define PKCS12_F_PKCS12_UNPACK_P7DATA 131
#define PKCS12_F_PKCS12_VERIFY_MAC 126
#define PKCS12_F_PKCS8_ADD_KEYUSAGE 124
#define PKCS12_F_PKCS8_ENCRYPT 125
/* Reason codes. */
#define PKCS12_R_CANT_PACK_STRUCTURE 100
#define PKCS12_R_CONTENT_TYPE_NOT_DATA 121
#define PKCS12_R_DECODE_ERROR 101
#define PKCS12_R_ENCODE_ERROR 102
#define PKCS12_R_ENCRYPT_ERROR 103
#define PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE 120
#define PKCS12_R_INVALID_NULL_ARGUMENT 104
#define PKCS12_R_INVALID_NULL_PKCS12_POINTER 105
#define PKCS12_R_IV_GEN_ERROR 106
#define PKCS12_R_KEY_GEN_ERROR 107
#define PKCS12_R_MAC_ABSENT 108
#define PKCS12_R_MAC_GENERATION_ERROR 109
#define PKCS12_R_MAC_SETUP_ERROR 110
#define PKCS12_R_MAC_STRING_SET_ERROR 111
#define PKCS12_R_MAC_VERIFY_ERROR 112
#define PKCS12_R_MAC_VERIFY_FAILURE 113
#define PKCS12_R_PARSE_ERROR 114
#define PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR 115
#define PKCS12_R_PKCS12_CIPHERFINAL_ERROR 116
#define PKCS12_R_PKCS12_PBE_CRYPT_ERROR 117
#define PKCS12_R_UNKNOWN_DIGEST_ALGORITHM 118
#define PKCS12_R_UNSUPPORTED_PKCS12_MODE 119
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (9.0.1) on Tue Oct 23 23:20:01 IST 2018 -->
<title>FloatSerializer (kafka 2.0.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-10-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="FloatSerializer (kafka 2.0.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/kafka/common/serialization/FloatDeserializer.html" title="class in org.apache.kafka.common.serialization"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/kafka/common/serialization/IntegerDeserializer.html" title="class in org.apache.kafka.common.serialization"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/kafka/common/serialization/FloatSerializer.html" target="_top">Frames</a></li>
<li><a href="FloatSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><span>SEARCH: </span>
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="../../../../../org/apache/kafka/common/serialization/package-summary.html">org.apache.kafka.common.serialization</a></div>
<h2 title="Class FloatSerializer" class="title">Class FloatSerializer</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.kafka.common.serialization.FloatSerializer</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><code>java.io.Closeable</code>, <code>java.lang.AutoCloseable</code>, <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html" title="interface in org.apache.kafka.common.serialization">Serializer</a><java.lang.Float></code></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">FloatSerializer</span>
extends java.lang.Object
implements <a href="../../../../../org/apache/kafka/common/serialization/Serializer.html" title="interface in org.apache.kafka.common.serialization">Serializer</a><java.lang.Float></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Constructor</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr class="altColor">
<th class="colConstructorName" scope="row"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/serialization/FloatSerializer.html#FloatSerializer--">FloatSerializer</a></span>​()</code></th>
<td class="colLast"> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/serialization/FloatSerializer.html#close--">close</a></span>​()</code></th>
<td class="colLast">
<div class="block">Close this serializer.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/serialization/FloatSerializer.html#configure-java.util.Map-boolean-">configure</a></span>​(java.util.Map<java.lang.String,?> configs,
boolean isKey)</code></th>
<td class="colLast">
<div class="block">Configure this class.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>byte[]</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/common/serialization/FloatSerializer.html#serialize-java.lang.String-java.lang.Float-">serialize</a></span>​(java.lang.String topic,
java.lang.Float data)</code></th>
<td class="colLast">
<div class="block">Convert <code>data</code> into a byte array.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="FloatSerializer--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>FloatSerializer</h4>
<pre>public FloatSerializer​()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="configure-java.util.Map-boolean-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>configure</h4>
<pre>public void configure​(java.util.Map<java.lang.String,?> configs,
boolean isKey)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html#configure-java.util.Map-boolean-">Serializer</a></code></span></div>
<div class="block">Configure this class.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html#configure-java.util.Map-boolean-">configure</a></code> in interface <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html" title="interface in org.apache.kafka.common.serialization">Serializer</a><java.lang.Float></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>configs</code> - configs in key/value pairs</dd>
<dd><code>isKey</code> - whether is for key or value</dd>
</dl>
</li>
</ul>
<a name="serialize-java.lang.String-java.lang.Float-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>serialize</h4>
<pre>public byte[] serialize​(java.lang.String topic,
java.lang.Float data)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html#serialize-java.lang.String-T-">Serializer</a></code></span></div>
<div class="block">Convert <code>data</code> into a byte array.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html#serialize-java.lang.String-T-">serialize</a></code> in interface <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html" title="interface in org.apache.kafka.common.serialization">Serializer</a><java.lang.Float></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>topic</code> - topic associated with data</dd>
<dd><code>data</code> - typed data</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>serialized bytes</dd>
</dl>
</li>
</ul>
<a name="close--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>close</h4>
<pre>public void close​()</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html#close--">Serializer</a></code></span></div>
<div class="block">Close this serializer.
This method must be idempotent as it may be called multiple times.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>close</code> in interface <code>java.lang.AutoCloseable</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>close</code> in interface <code>java.io.Closeable</code></dd>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html#close--">close</a></code> in interface <code><a href="../../../../../org/apache/kafka/common/serialization/Serializer.html" title="interface in org.apache.kafka.common.serialization">Serializer</a><java.lang.Float></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/kafka/common/serialization/FloatDeserializer.html" title="class in org.apache.kafka.common.serialization"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/kafka/common/serialization/IntegerDeserializer.html" title="class in org.apache.kafka.common.serialization"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/kafka/common/serialization/FloatSerializer.html" target="_top">Frames</a></li>
<li><a href="FloatSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
# Backward Incompatible Changes
This subdirectory consists of individual markdown files for each model, documenting the backward incompatible changes.
| {
"pile_set_name": "Github"
} |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.data.type;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.effect.sound.SoundType;
import org.spongepowered.api.util.annotation.CatalogedBy;
/**
* Represents a type of instrument.
*/
@CatalogedBy(InstrumentTypes.class)
public interface InstrumentType extends CatalogType {
/**
* Gets the {@link SoundType} that is used by
* this {@link InstrumentType}.
*
* @return The sound
*/
SoundType getSound();
}
| {
"pile_set_name": "Github"
} |
// Copyright Daniel Wallin 2005. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/dec.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#define N BOOST_PP_ITERATION()
#define BOOST_PARAMETER_PY_ARG_TYPES(z, n, _) \
typedef typename mpl::next< \
BOOST_PP_CAT(iter,BOOST_PP_DEC(n)) \
>::type BOOST_PP_CAT(iter,n); \
\
typedef typename mpl::deref<BOOST_PP_CAT(iter,n)>::type BOOST_PP_CAT(spec,n); \
typedef typename mpl::if_< \
mpl::and_< \
mpl::not_<typename BOOST_PP_CAT(spec,n)::required> \
, typename BOOST_PP_CAT(spec,n)::optimized_default \
> \
, parameter::aux::maybe<typename BOOST_PP_CAT(spec,n)::type> \
, typename BOOST_PP_CAT(spec,n)::type \
>::type BOOST_PP_CAT(arg,n); \
typedef typename BOOST_PP_CAT(spec,n)::keyword BOOST_PP_CAT(kw,n);
#if BOOST_PP_ITERATION_FLAGS() == 1
template <class M, class R, class Args>
struct invoker<N, M, R, Args>
#elif BOOST_PP_ITERATION_FLAGS() == 2
template <class T, class R, class Args>
struct call_invoker<N, T, R, Args>
#elif BOOST_PP_ITERATION_FLAGS() == 3
template <class T, class Args>
struct init_invoker<N, T, Args>
#elif BOOST_PP_ITERATION_FLAGS() == 4
template <class M, class R, class T, class Args>
struct member_invoker<N, M, R, T, Args>
#endif
{
typedef typename mpl::begin<Args>::type iter0;
typedef typename mpl::deref<iter0>::type spec0;
typedef typename mpl::if_<
mpl::and_<
mpl::not_<typename spec0::required>
, typename spec0::optimized_default
>
, parameter::aux::maybe<typename spec0::type>
, typename spec0::type
>::type arg0;
typedef typename spec0::keyword kw0;
BOOST_PP_REPEAT_FROM_TO(1, N, BOOST_PARAMETER_PY_ARG_TYPES, ~)
static
#if BOOST_PP_ITERATION_FLAGS() == 3
T*
#else
R
#endif
execute(
#if BOOST_PP_ITERATION_FLAGS() == 2 || BOOST_PP_ITERATION_FLAGS() == 4
T& self
,
#endif
BOOST_PP_ENUM_BINARY_PARAMS(N, arg, a)
)
{
return
#if BOOST_PP_ITERATION_FLAGS() == 1 || BOOST_PP_ITERATION_FLAGS() == 4
M()(
boost::type<R>()
# if BOOST_PP_ITERATION_FLAGS() == 4
, self
# endif
, BOOST_PP_ENUM_BINARY_PARAMS(N, parameter::keyword<kw, >::get() = a)
);
#elif BOOST_PP_ITERATION_FLAGS() == 2
self(
BOOST_PP_ENUM_BINARY_PARAMS(N, parameter::keyword<kw, >::get() = a)
);
#elif BOOST_PP_ITERATION_FLAGS() == 3
new T(
BOOST_PP_ENUM_BINARY_PARAMS(N, parameter::keyword<kw, >::get() = a)
);
#endif
}
};
#undef BOOST_PARAMETER_PY_ARG_TYPES
#undef N
| {
"pile_set_name": "Github"
} |
# Format: //devtools/kokoro/config/proto/build.proto
env_vars: {
key: "PACKAGE"
value: "google-cloud-functions"
}
| {
"pile_set_name": "Github"
} |
"use strict";
const assert = require("assert").strict;
const command = require("@clusterio/lib/command");
const errors = require("@clusterio/lib/errors");
const link = require("@clusterio/lib/link");
const mock = require("../mock");
describe("lib/command", function() {
let testRole = { id: 28, name: "Test Role", description: "Test", permissions: [] };
let mockConnector = new mock.MockConnector();
mockConnector.on("send", function(message) {
if (message.type === "list_slaves_request") {
this.emit("message", {
seq: 1, type: "list_slaves_response",
data: {
seq: message.seq,
list: [{ agent: "test", version: "0.1", id: 11, name: "Test Slave", connected: false }],
},
});
} else if (message.type === "list_instances_request") {
this.emit("message", {
seq: 1, type: "list_instances_response",
data: {
seq: message.seq,
list: [{ id: 57, assigned_slave: 4, name: "Test Instance", status: "stopped" }],
},
});
} else if (message.type === "list_roles_request") {
this.emit("message", {
seq: 1, type: "list_roles_response",
data: {
seq: message.seq,
list: [testRole],
},
});
}
});
let testControl = new mock.MockControl(mockConnector);
link.messages.listSlaves.attach(testControl);
link.messages.listInstances.attach(testControl);
link.messages.listRoles.attach(testControl);
describe("resolveSlave", function() {
it("should pass an integer like string back", async function() {
assert.equal(await command.resolveSlave(null, "123"), 123);
});
it("should resolve a slave name with the master server", async function() {
assert.equal(await command.resolveSlave(testControl, "Test Slave"), 11);
});
it("should throw if slave is not found", async function() {
await assert.rejects(
command.resolveSlave(testControl, "invalid"),
new errors.CommandError("No slave named invalid")
);
});
});
describe("resolveInstance", function() {
it("should pass an integer like string back", async function() {
assert.equal(await command.resolveInstance(null, "123"), 123);
});
it("should resolve an instance name with the master server", async function() {
assert.equal(await command.resolveInstance(testControl, "Test Instance"), 57);
});
it("should throw if instance is not found", async function() {
await assert.rejects(
command.resolveInstance(testControl, "invalid"),
new errors.CommandError("No instance named invalid")
);
});
});
describe("retrieveRole", function() {
it("should retrieve a role by id from an integer like string", async function() {
assert.deepEqual(await command.retrieveRole(testControl, "28"), testRole);
});
it("should retrieve a role by name from a string", async function() {
assert.deepEqual(await command.retrieveRole(testControl, "Test Role"), testRole);
});
it("should throw if role is not found", async function() {
await assert.rejects(
command.retrieveRole(testControl, "invalid"),
new errors.CommandError("No role named invalid")
);
});
});
});
| {
"pile_set_name": "Github"
} |
; RUN: opt < %s -S -ipsccp | FileCheck %s
; PR5596
; IPSCCP should propagate the 0 argument, eliminate the switch, and propagate
; the result.
; CHECK: define i32 @main() #0 {
; CHECK-NEXT: entry:
; CHECK-NOT: call
; CHECK-NEXT: ret i32 123
define i32 @main() noreturn nounwind {
entry:
%call2 = tail call i32 @wwrite(i64 0) nounwind
ret i32 %call2
}
define internal i32 @wwrite(i64 %i) nounwind readnone {
entry:
switch i64 %i, label %sw.default [
i64 3, label %return
i64 10, label %return
]
sw.default:
ret i32 123
return:
ret i32 0
}
; CHECK: attributes #0 = { noreturn nounwind }
; CHECK: attributes #1 = { nounwind readnone }
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002-2017 Jaakko Keränen <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __AMETHYST_GEM_CLASS_H__
#define __AMETHYST_GEM_CLASS_H__
#include "string.h"
#include "length.h"
// Style flags.
#define GSF_EMPHASIZE 0x00000001
#define GSF_DEFINITION 0x00000002
#define GSF_CODE 0x00000004
#define GSF_KEYBOARD 0x00000008
#define GSF_SAMPLE 0x00000010
#define GSF_VARIABLE 0x00000020
#define GSF_FILE 0x00000040
#define GSF_OPTION 0x00000080
#define GSF_COMMAND 0x00000100
#define GSF_CITE 0x00000200
#define GSF_ACRONYM 0x00000400
#define GSF_URL 0x00000800
#define GSF_EMAIL 0x00001000
#define GSF_STRONG 0x00002000
#define GSF_ENUMERATE 0x00004000
#define GSF_HEADER 0x00008000
#define GSF_BREAK_LINE 0x00010000
#define GSF_SINGLE 0x00020000
#define GSF_DOUBLE 0x00040000
#define GSF_THICK 0x00080000
#define GSF_THIN 0x00100000
#define GSF_ROMAN 0x00200000
#define GSF_LARGE 0x00400000
#define GSF_SMALL 0x00800000
#define GSF_HUGE 0x01000000
#define GSF_TINY 0x02000000
#define GSF_NOTE 0x04000000
#define GSF_WARNING 0x08000000
#define GSF_IMPORTANT 0x10000000
#define GSF_PREFORMATTED 0x20000000
#define GSF_CAPTION 0x40000000
#define GSF_TAG 0x80000000
#define GS_HIGHEST_TITLE GemClass::PartTitle
#define GS_LOWEST_TITLE GemClass::Sub4SectionTitle
class GemClass
{
public:
enum GemType {
None,
Gem,
Indent,
List,
DefinitionList,
Table,
PartTitle,
ChapterTitle,
SectionTitle,
SubSectionTitle,
Sub2SectionTitle,
Sub3SectionTitle,
Sub4SectionTitle,
Contents
};
enum FlushMode {
FlushInherit, // Same as FlushLeft, if not overridden.
FlushLeft,
FlushRight,
FlushCenter
};
public:
GemClass(GemType _type = Gem, int _style = 0, FlushMode = FlushInherit, const String& filterString = "");
GemClass(int _style, FlushMode mode = FlushInherit);
const Length &length() const { return _length; }
Length &length() { return _length; }
GemType type() const { return _type; }
String typeAsString() const;
int style() const { return _style; }
String styleAsString() const;
FlushMode flushMode() const { return _flush; }
const String& filter() const { return _filter; }
// Setters.
int modifyStyle(int setFlags = 0, int clearFlags = 0);
void setFlushMode(FlushMode mode) { _flush = mode; }
void setFilter(const String& flt) { _filter = flt; }
// Information.
bool hasStyle(int flags) const;
bool hasFilter() const { return !_filter.isEmpty(); }
bool isTitleType()
{ return _type >= GS_HIGHEST_TITLE && _type <= GS_LOWEST_TITLE; }
GemClass operator + (const GemClass &other) const;
private:
int _style; // Style flags.
GemType _type; // Type of gem.
FlushMode _flush;
String _filter;
Length _length;
};
#endif
| {
"pile_set_name": "Github"
} |
/**
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import { VanillaSwaggerDeepLink } from "@library/features/swagger/VanillaSwaggerDeepLink";
import { VanillaSwaggerLayout } from "@library/features/swagger/VanillaSwaggerLayout";
export function VanillaSwaggerPlugin() {
// Create the plugin that provides our layout component
return {
components: {
VanillaSwaggerLayout: VanillaSwaggerLayout,
DeepLink: VanillaSwaggerDeepLink,
},
};
}
| {
"pile_set_name": "Github"
} |
<?php namespace Laravel\Database\Query\Grammars;
class MySQL extends Grammar {
/**
* The keyword identifier for the database system.
*
* @var string
*/
protected $wrapper = '`%s`';
} | {
"pile_set_name": "Github"
} |
/* Base16 Atelier Heath Dark - Theme */
/* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/heath) */
/* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */
/* Atelier-Heath Comment */
.hljs-comment,
.hljs-quote {
color: #9e8f9e;
}
/* Atelier-Heath Red */
.hljs-variable,
.hljs-template-variable,
.hljs-attribute,
.hljs-tag,
.hljs-name,
.hljs-regexp,
.hljs-link,
.hljs-name,
.hljs-selector-id,
.hljs-selector-class {
color: #ca402b;
}
/* Atelier-Heath Orange */
.hljs-number,
.hljs-meta,
.hljs-built_in,
.hljs-builtin-name,
.hljs-literal,
.hljs-type,
.hljs-params {
color: #a65926;
}
/* Atelier-Heath Green */
.hljs-string,
.hljs-symbol,
.hljs-bullet {
color: #918b3b;
}
/* Atelier-Heath Blue */
.hljs-title,
.hljs-section {
color: #516aec;
}
/* Atelier-Heath Purple */
.hljs-keyword,
.hljs-selector-tag {
color: #7b59c0;
}
.hljs {
display: block;
overflow-x: auto;
background: #1b181b;
color: #ab9bab;
padding: 0.5em;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
| {
"pile_set_name": "Github"
} |
/**
* gobandroid
* by Marcus -Ligi- Bueschleb
* http://ligi.de
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation;
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see //www.gnu.org/licenses/>.
*/
package org.ligi.gobandroid_hd.logic
import org.greenrobot.eventbus.EventBus
import org.ligi.gobandroid_hd.events.GameChangedEvent
import org.ligi.gobandroid_hd.logic.GoDefinitions.*
import org.ligi.gobandroid_hd.logic.cell_gatherer.MustBeConnectedCellGatherer
import org.ligi.tracedroid.logging.Log
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* Class to represent a Go Game with its rules
*/
class GoGame @JvmOverloads constructor(size: Int, handicap: Int = 0) {
enum class MoveStatus {
VALID,
INVALID_NOT_ON_BOARD,
INVALID_CELL_NOT_FREE,
INVALID_CELL_NO_LIBERTIES,
INVALID_IS_KO
}
val statelessGoBoard: StatelessGoBoard = StatelessGoBoard(size)
val calcBoard: StatefulGoBoard = StatefulGoBoard(statelessGoBoard)// the board calculations are done in
lateinit var visualBoard: StatefulGoBoard
lateinit var handicapBoard: StatefulGoBoard
private var groups: Array<IntArray>? = null // array to build groups
var capturesWhite: Int = 0
var capturesBlack: Int = 0
var handicap = 0
var komi = 6.5f
lateinit var actMove: GoMove
lateinit var metaData: GoGameMetadata
private lateinit var all_handicap_positions: Array<BooleanArray>
init {
init(size, handicap)
}
var scorer: GoGameScorer? = null
private set
fun removeScorer() {
scorer = null
}
fun initScorer() {
scorer = GoGameScorer(this)
scorer!!.calculateScore()
}
private fun init(size: Int, handicap: Int) {
this.handicap = handicap
// create the boards
metaData = GoGameMetadata()
val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
metaData.date = format.format(Date())
handicapBoard = calcBoard.clone()
all_handicap_positions = Array(size) { BooleanArray(size) }
if (handicap > 0) komi = 0.5f
if (getHandicapArray(size) != null) {
val handicapArray = getHandicapArray(size)!!
for (i in 0..8) {
if (i < handicap) {
handicapBoard.setCell(CellImpl(handicapArray[i][0].toInt(), handicapArray[i][1].toInt()), STONE_BLACK)
if (i == 5 || i == 7) {
handicapBoard.setCell(CellImpl(handicapArray[4][0].toInt(), handicapArray[4][1].toInt()), STONE_NONE)
handicapBoard.setCell(CellImpl(handicapArray[i + 1][0].toInt(), handicapArray[i + 1][1].toInt()), STONE_BLACK)
} else if (i == 6 || i == 8) handicapBoard.setCell(CellImpl(handicapArray[4][0].toInt(), handicapArray[4][1].toInt()), STONE_BLACK)
}
all_handicap_positions[handicapArray[i][0].toInt()][handicapArray[i][1].toInt()] = true
}
}
apply_handicap()
copyVisualBoard()
// create the array for group calculations
groups = Array(size) { IntArray(size) }
actMove = GoMove(null)
actMove.setIsFirstMove()
actMove.player = if(handicap == 0) PLAYER_WHITE else PLAYER_BLACK
reset()
}
/**
* set the handicap stones on the calc board
*/
fun apply_handicap() {
calcBoard.applyBoardState(handicapBoard.board)
}
fun reset() {
capturesBlack = 0
capturesWhite = 0
}
fun pass() {
if (actMove.isPassMove) {
// finish game if both passed
actMove = GoMove(actMove)
actMove.setToPassMove()
buildGroups()
} else {
actMove = GoMove(actMove)
actMove.setToPassMove()
}
EventBus.getDefault().post(GameChangedEvent)
}
/**
* place a stone on the board
*/
fun do_move(cell: Cell): MoveStatus {
Log.i("do_move " + cell)
if(actMove.isFinalMove) {
// game is finished - players are marking dead stones
return MoveStatus.VALID
}
val nextMove: GoMove = GoMove(cell, actMove, calcBoard)
val errorStatus = nextMove.getErrorStatus(calcBoard)
if (errorStatus != null) {
return errorStatus
}
// check if the "new" move is in the variations - to not have 2 equal
// move as different variations
// if there is one matching use this move and we are done
val matching_move = actMove.getNextMoveOnCell(cell)
if (matching_move != null) {
redo(matching_move)
return MoveStatus.VALID
}
// if we reach this point it is a valid move
// -> do things needed to do after a valid move
actMove = nextMove
actMove.apply(calcBoard)
applyCaptures()
refreshBoards()
// if we reached this point this move must be valid
return MoveStatus.VALID
}
fun repositionActMove(cell: Cell): MoveStatus {
Log.i("repositionActMove " + cell)
if(cell == actMove.cell) {
return MoveStatus.VALID
}
undoCaptures()
val moveStatus = actMove.repostition(calcBoard, cell)
applyCaptures()
refreshBoards()
return moveStatus
}
fun canRedo(): Boolean {
return actMove.hasNextMove()
}
val possibleVariationCount: Int
get() {
return actMove.nextMoveVariationCount
}
fun canUndo(): Boolean {
return !actMove.isFirstMove// &&(!getGoMover().isMoversMove());
}
@JvmOverloads fun undo(keep_move: Boolean = true) {
undoCaptures()
actMove = actMove.undo(calcBoard, keep_move)
refreshBoards()
}
fun redo(pos: Int) {
actMove.getnextMove(pos)?.let {
redo(it)
}
}
fun redo(move: GoMove) {
actMove = actMove.redo(calcBoard, move)
applyCaptures()
refreshBoards()
}
fun applyCaptures() {
val local_captures = actMove.captures.size
if(local_captures > 0) {
actMove.cell?.let {
if (calcBoard.isCellKind(it, STONE_WHITE)) {
capturesWhite += local_captures
} else {
capturesBlack += local_captures
}
}
}
}
fun undoCaptures() {
val local_captures = actMove.captures.size
if(local_captures > 0) {
actMove.cell?.let {
if (calcBoard.isCellKind(it, STONE_WHITE)) {
capturesWhite -= local_captures
} else {
capturesBlack -= local_captures
}
}
}
}
fun nextVariationWithOffset(offset: Int): GoMove? {
if (actMove.isFirstMove) return null
val variations = actMove.parent!!.nextMoveVariations
val indexOf = variations.indexOf(actMove)
return variations.elementAtOrNull(indexOf + offset)
}
fun refreshBoards() {
copyVisualBoard()
EventBus.getDefault().post(GameChangedEvent)
}
fun findFollowingMove(f: (GoMove) -> Boolean): GoMove? {
return findMove({ it.getnextMove(0) }, f)
}
fun findPreviousMove(condition: (GoMove) -> Boolean): GoMove? {
return findMove({ it.parent }, condition)
}
fun findMove(nextMove: (GoMove) -> GoMove?, condition: (GoMove) -> Boolean): GoMove? {
var move: GoMove? = actMove
while (move!=null) {
if (condition(move)) return move
move = nextMove(move)
}
return null
}
fun findFirstMove(): GoMove {
return findPreviousMove { it.isFirstMove }!!
}
fun findLastMove(): GoMove {
return findFollowingMove { !it.hasNextMove() }!!
}
fun findNextJunction(): GoMove? {
return findFollowingMove { !it.hasNextMove() || it.hasNextMoveVariations() }
}
fun findPrevJunction(): GoMove? {
return findPreviousMove { it.isFirstMove || (it.hasNextMoveVariations() && !it.isContentEqual(actMove.parent) && !it.isContentEqual(actMove)) }
}
fun jump(move: GoMove?) {
if (move == null) {
Log.w("move is null #shouldnothappen")
return
}
clear_calc_board()
val replay_moves = ArrayList<GoMove>()
replay_moves.add(move)
var tmp_move: GoMove
while (true) {
tmp_move = replay_moves.last()
if (tmp_move.isFirstMove || tmp_move.parent == null) break
replay_moves.add(tmp_move.parent!!)
}
reset()
actMove = findFirstMove()
for (step in replay_moves.indices.reversed()) {
actMove = actMove.redo(calcBoard, replay_moves[step])
applyCaptures()
}
refreshBoards()
}
fun copyVisualBoard() {
visualBoard = calcBoard.clone()
}
/**
* check if a group has liberties via flood fill
* @return boolean weather the group has liberty
*/
fun hasGroupLiberties(cell: Cell): Boolean {
val startCell = statelessGoBoard.getCell(cell)
return MustBeConnectedCellGatherer(calcBoard, startCell).gatheredCells.any {
it.neighbors.any { neighbor -> calcBoard.isCellFree(neighbor) }
}
}
fun clear_calc_board() {
apply_handicap()
}
/**
* group the stones
*
*
* the result is written in groups[][]
*/
fun buildGroups() {
val group_count = AtomicInteger(0)
// reset groups
statelessGoBoard.withAllCells {
groups!![it.x][it.y] = -1
}
statelessGoBoard.withAllCells { statelessBoardCell ->
if (groups!![statelessBoardCell.x][statelessBoardCell.y] == -1 && !calcBoard.isCellKind(statelessBoardCell, STONE_NONE)) {
for (groupCell in MustBeConnectedCellGatherer(calcBoard, statelessBoardCell).gatheredCells) {
groups!![groupCell.x][groupCell.y] = group_count.get()
}
group_count.incrementAndGet()
}
}
}
/**
* return if it's a handicap stone so that the view can visualize it
*
* TODO: check rename ( general marker )
*/
fun isCellHoshi(cell: Cell) = all_handicap_positions[cell.x][cell.y]
// need at least 2 moves to finish a game ( 2 passes )
// w passes
val isFinished: Boolean
get() {
if (actMove.isFirstMove) return false
if (actMove.parent == null) return false
return actMove.isPassMove && actMove.parent!=null && actMove.parent!!.isPassMove
}
/**
* @return who has to do the next move
*/
val isBlackToMove: Boolean
get() = actMove.player == PLAYER_WHITE
// TODO cache?
val boardSize: Int
get() = calcBoard.size
fun setMetadata(metadata: GoGameMetadata) {
this.metaData = metadata
}
val size: Int
get() = visualBoard.size
/**
* just content as state is not checked ( position in game )
*
*
* checks:
* - size
* - moves
* - metadata ( TODO )
*/
fun isContentEqualTo(other: GoGame): Boolean {
return other.boardSize == boardSize && compareMovesRecursive(findFirstMove(), other.findFirstMove())
}
fun hasNextMove(move1: GoMove, expected: GoMove): Boolean {
return move1.nextMoveVariations.any { it.isContentEqual(expected) }
}
private fun compareMovesRecursive(move1: GoMove, move2: GoMove): Boolean {
if (!move1.isContentEqual(move2)) {
return false
}
if (move1.hasNextMove() != move2.hasNextMove()) {
return false
}
return !move1.nextMoveVariations.any { !hasNextMove(move1, it) }
}
}
| {
"pile_set_name": "Github"
} |
import { parseMetadata } from 'graphql-metadata'
/**
* Wraps `parseMetadata` to return empty object instead of undefined if no annotation is found.
*
* This is a compatibility function to ensure an empty object is r
* returned when there is no annotationn as graphql-migrations assumes an empty object will be
* returned and does not do any conditional checking for undefined annotation. This is because
* `parseAnnotations` (deprecated) from grapqhl-metadata returns an empty object, but parseMetadata
* returns undefined.
*
* Do not use this for new features
*
* @param namespace
* @param description
*/
export function parseAnnotationsCompat(namespace: string, description: string): any {
const annotation = parseMetadata(namespace, description) || {}
return annotation
}
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenPrFunction", "OpenPrFunction\OpenPrFunction.csproj", "{5A6476B2-18FC-4A93-8DA9-E4A667662EC5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{5DE80CA7-E47E-4262-8C8E-28C2CC2607F7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Install", "Install\Install.csproj", "{84422DBF-F2CA-4FAF-AE75-914E8C7B97E5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompressImagesFunction", "CompressImagesFunction\CompressImagesFunction.csproj", "{4DBC4C11-027B-44A6-86FC-84CB752DBB99}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RouterFunction", "RouterFunction\RouterFunction.csproj", "{C7DA8CA7-8540-4698-A7C0-5537565F345B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{478E346B-3F08-4D0F-8757-400E2C106B88}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrPoisonHandler", "PrPoisonHandler\PrPoisonHandler.csproj", "{2F780783-3651-4506-A8AA-D23E650F3DED}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebHook", "WebHook\WebHook.csproj", "{87E56493-AEB9-4257-90C0-FB7CE65C2816}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Auth", "Auth\Auth.csproj", "{9A4BAC64-E0FB-4EA4-B1E3-38143E847127}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MarketplaceSyncFunction", "MarketplaceSyncFunction\MarketplaceSyncFunction.csproj", "{31FB826F-41D7-4D06-B0DB-99F5DF3519DF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeleteBranchFunction", "DeleteBranchFunction\DeleteBranchFunction.csproj", "{B2E354C4-067D-40E9-A957-92FFFEB2E856}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5A6476B2-18FC-4A93-8DA9-E4A667662EC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5A6476B2-18FC-4A93-8DA9-E4A667662EC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5A6476B2-18FC-4A93-8DA9-E4A667662EC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5A6476B2-18FC-4A93-8DA9-E4A667662EC5}.Release|Any CPU.Build.0 = Release|Any CPU
{5DE80CA7-E47E-4262-8C8E-28C2CC2607F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5DE80CA7-E47E-4262-8C8E-28C2CC2607F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5DE80CA7-E47E-4262-8C8E-28C2CC2607F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5DE80CA7-E47E-4262-8C8E-28C2CC2607F7}.Release|Any CPU.Build.0 = Release|Any CPU
{84422DBF-F2CA-4FAF-AE75-914E8C7B97E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84422DBF-F2CA-4FAF-AE75-914E8C7B97E5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84422DBF-F2CA-4FAF-AE75-914E8C7B97E5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84422DBF-F2CA-4FAF-AE75-914E8C7B97E5}.Release|Any CPU.Build.0 = Release|Any CPU
{4DBC4C11-027B-44A6-86FC-84CB752DBB99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4DBC4C11-027B-44A6-86FC-84CB752DBB99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4DBC4C11-027B-44A6-86FC-84CB752DBB99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4DBC4C11-027B-44A6-86FC-84CB752DBB99}.Release|Any CPU.Build.0 = Release|Any CPU
{C7DA8CA7-8540-4698-A7C0-5537565F345B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C7DA8CA7-8540-4698-A7C0-5537565F345B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C7DA8CA7-8540-4698-A7C0-5537565F345B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C7DA8CA7-8540-4698-A7C0-5537565F345B}.Release|Any CPU.Build.0 = Release|Any CPU
{478E346B-3F08-4D0F-8757-400E2C106B88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{478E346B-3F08-4D0F-8757-400E2C106B88}.Debug|Any CPU.Build.0 = Debug|Any CPU
{478E346B-3F08-4D0F-8757-400E2C106B88}.Release|Any CPU.ActiveCfg = Release|Any CPU
{478E346B-3F08-4D0F-8757-400E2C106B88}.Release|Any CPU.Build.0 = Release|Any CPU
{2F780783-3651-4506-A8AA-D23E650F3DED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2F780783-3651-4506-A8AA-D23E650F3DED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2F780783-3651-4506-A8AA-D23E650F3DED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2F780783-3651-4506-A8AA-D23E650F3DED}.Release|Any CPU.Build.0 = Release|Any CPU
{87E56493-AEB9-4257-90C0-FB7CE65C2816}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{87E56493-AEB9-4257-90C0-FB7CE65C2816}.Debug|Any CPU.Build.0 = Debug|Any CPU
{87E56493-AEB9-4257-90C0-FB7CE65C2816}.Release|Any CPU.ActiveCfg = Release|Any CPU
{87E56493-AEB9-4257-90C0-FB7CE65C2816}.Release|Any CPU.Build.0 = Release|Any CPU
{9A4BAC64-E0FB-4EA4-B1E3-38143E847127}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9A4BAC64-E0FB-4EA4-B1E3-38143E847127}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9A4BAC64-E0FB-4EA4-B1E3-38143E847127}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9A4BAC64-E0FB-4EA4-B1E3-38143E847127}.Release|Any CPU.Build.0 = Release|Any CPU
{31FB826F-41D7-4D06-B0DB-99F5DF3519DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{31FB826F-41D7-4D06-B0DB-99F5DF3519DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{31FB826F-41D7-4D06-B0DB-99F5DF3519DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{31FB826F-41D7-4D06-B0DB-99F5DF3519DF}.Release|Any CPU.Build.0 = Release|Any CPU
{B2E354C4-067D-40E9-A957-92FFFEB2E856}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B2E354C4-067D-40E9-A957-92FFFEB2E856}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B2E354C4-067D-40E9-A957-92FFFEB2E856}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B2E354C4-067D-40E9-A957-92FFFEB2E856}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/benchmark/js/jquery.min.js"></script>
<script type="text/javascript" src="/benchmark/js/js.cookie.js"></script>
<title>BenchmarkTest00220</title>
</head>
<body>
<form action="/benchmark/pathtraver-00/BenchmarkTest00220" method="POST" id="FormBenchmarkTest00220">
<div><label>Please explain your answer:</label></div>
<br/>
<div><textarea rows="4" cols="50" id="BenchmarkTest00220Area" name="BenchmarkTest00220Area" value=""></textarea></div>
<div><label>Any additional note for the reviewer:</label></div>
<div><input type="text" id="answer" name="answer"></input></div>
<br/>
<div><label>An AJAX request will be sent with a header named <input type="text" id="BenchmarkTest00220" name="BenchmarkTest00220" value="FileName" class="safe"></input>
and value of BenchmarkTest00220.</label>
</div>
<div><input type="button" id="login-btn" value="Login" onclick="submitForm()" /></div>
</form>
<div id="ajax-form-msg1"><pre><code class="prettyprint" id="code"></code></pre></div>
<script>
$('.safe').keypress(function (e) {
if (e.which == 13) {
submitForm();
return false;
}
});
function submitForm() {
var formData = $("#FormBenchmarkTest00220").serialize();
var URL = $("#FormBenchmarkTest00220").attr("action");
var text = $("#FormBenchmarkTest00220 input[id=BenchmarkTest00220]").val();
var xhr = new XMLHttpRequest();
xhr.open("POST", URL, true);
xhr.setRequestHeader( text, 'BenchmarkTest00220');
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
$("#code").text((xhr.responseText).decodeEscapeSequence());
}else{
$("#code").html("Error " + xhr.status + " ocurred.");
}
}
xhr.send(formData);
}
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
String.prototype.decodeEscapeSequence = function() {
var txt = replaceAll(this,";","");
txt = replaceAll(txt,"&#","\\");
return txt.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
return String.fromCharCode(parseInt(arguments[1], 16));
});
};
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
export function applyCaptureIdToElement(element: Element, referenceCaptureId: string) {
element.setAttribute(getCaptureIdAttributeName(referenceCaptureId), '');
}
function getElementByCaptureId(referenceCaptureId: string) {
const selector = `[${getCaptureIdAttributeName(referenceCaptureId)}]`;
return document.querySelector(selector);
}
function getCaptureIdAttributeName(referenceCaptureId: string) {
return `_bl_${referenceCaptureId}`;
}
// Support receiving ElementRef instances as args in interop calls
const elementRefKey = '__internalId'; // Keep in sync with ElementRef.cs
DotNet.attachReviver((key, value) => {
if (value && typeof value === 'object' && value.hasOwnProperty(elementRefKey) && typeof value[elementRefKey] === 'string') {
return getElementByCaptureId(value[elementRefKey]);
} else {
return value;
}
});
| {
"pile_set_name": "Github"
} |
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package v1
import (
"encoding/json"
ucfg "github.com/elastic/go-ucfg"
)
// CfgOptions are config options for YAML config. Currently contains only support for dotted keys.
var CfgOptions = []ucfg.Option{ucfg.PathSep(".")}
// Config represents untyped YAML configuration.
// +kubebuilder:validation:Type=object
type Config struct {
// Data holds the configuration keys and values.
// This field exists to work around https://github.com/kubernetes-sigs/kubebuilder/issues/528
Data map[string]interface{} `json:"-"`
}
// NewConfig constructs a Config with the given unstructured configuration data.
func NewConfig(cfg map[string]interface{}) Config {
return Config{Data: cfg}
}
// MarshalJSON implements the Marshaler interface.
func (c *Config) MarshalJSON() ([]byte, error) {
return json.Marshal(c.Data)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (c *Config) UnmarshalJSON(data []byte) error {
var out map[string]interface{}
err := json.Unmarshal(data, &out)
if err != nil {
return err
}
c.Data = out
return nil
}
// DeepCopyInto is an ~autogenerated~ deepcopy function, copying the receiver, writing into out. in must be non-nil.
// This exists here to work around https://github.com/kubernetes/code-generator/issues/50
func (c *Config) DeepCopyInto(out *Config) {
bytes, err := json.Marshal(c.Data)
if err != nil {
// we assume that it marshals cleanly because otherwise the resource would not have been
// created in the API server
panic(err)
}
var copy map[string]interface{}
err = json.Unmarshal(bytes, ©)
if err != nil {
// we assume again optimistically because we just marshalled that the round trip works as well
panic(err)
}
out.Data = copy
}
| {
"pile_set_name": "Github"
} |
FROM balenalib/aarch64-ubuntu:cosmic-build
LABEL io.balena.device-type="astro-tx2"
RUN apt-get update && apt-get install -y --no-install-recommends \
less \
kmod \
nano \
net-tools \
ifupdown \
iputils-ping \
i2c-tools \
usbutils \
&& rm -rf /var/lib/apt/lists/*
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu cosmic \nVariant: build variant \nDefault variable(s): UDEV=off \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"pile_set_name": "Github"
} |
FROM golang:1.14-alpine AS build
RUN apk add --no-cache git
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-extldflags "-static"' \
-o /bin/a.out ./cmd/cloudshell_open
FROM gcr.io/cloudshell-images/cloudshell:latest
COPY --from=build /bin/a.out /bin/cloudshell_open
| {
"pile_set_name": "Github"
} |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for slim.slim_nets.resnet_v1."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from nets import resnet_utils
from nets import resnet_v1
slim = tf.contrib.slim
def create_test_input(batch_size, height, width, channels):
"""Create test input tensor.
Args:
batch_size: The number of images per batch or `None` if unknown.
height: The height of each image or `None` if unknown.
width: The width of each image or `None` if unknown.
channels: The number of channels per image or `None` if unknown.
Returns:
Either a placeholder `Tensor` of dimension
[batch_size, height, width, channels] if any of the inputs are `None` or a
constant `Tensor` with the mesh grid values along the spatial dimensions.
"""
if None in [batch_size, height, width, channels]:
return tf.placeholder(tf.float32, (batch_size, height, width, channels))
else:
return tf.to_float(
np.tile(
np.reshape(
np.reshape(np.arange(height), [height, 1]) +
np.reshape(np.arange(width), [1, width]),
[1, height, width, 1]),
[batch_size, 1, 1, channels]))
class ResnetUtilsTest(tf.test.TestCase):
def testSubsampleThreeByThree(self):
x = tf.reshape(tf.to_float(tf.range(9)), [1, 3, 3, 1])
x = resnet_utils.subsample(x, 2)
expected = tf.reshape(tf.constant([0, 2, 6, 8]), [1, 2, 2, 1])
with self.test_session():
self.assertAllClose(x.eval(), expected.eval())
def testSubsampleFourByFour(self):
x = tf.reshape(tf.to_float(tf.range(16)), [1, 4, 4, 1])
x = resnet_utils.subsample(x, 2)
expected = tf.reshape(tf.constant([0, 2, 8, 10]), [1, 2, 2, 1])
with self.test_session():
self.assertAllClose(x.eval(), expected.eval())
def testConv2DSameEven(self):
n, n2 = 4, 2
# Input image.
x = create_test_input(1, n, n, 1)
# Convolution kernel.
w = create_test_input(1, 3, 3, 1)
w = tf.reshape(w, [3, 3, 1, 1])
tf.get_variable('Conv/weights', initializer=w)
tf.get_variable('Conv/biases', initializer=tf.zeros([1]))
tf.get_variable_scope().reuse_variables()
y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv')
y1_expected = tf.to_float([[14, 28, 43, 26],
[28, 48, 66, 37],
[43, 66, 84, 46],
[26, 37, 46, 22]])
y1_expected = tf.reshape(y1_expected, [1, n, n, 1])
y2 = resnet_utils.subsample(y1, 2)
y2_expected = tf.to_float([[14, 43],
[43, 84]])
y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1])
y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv')
y3_expected = y2_expected
y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv')
y4_expected = tf.to_float([[48, 37],
[37, 22]])
y4_expected = tf.reshape(y4_expected, [1, n2, n2, 1])
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(y1.eval(), y1_expected.eval())
self.assertAllClose(y2.eval(), y2_expected.eval())
self.assertAllClose(y3.eval(), y3_expected.eval())
self.assertAllClose(y4.eval(), y4_expected.eval())
def testConv2DSameOdd(self):
n, n2 = 5, 3
# Input image.
x = create_test_input(1, n, n, 1)
# Convolution kernel.
w = create_test_input(1, 3, 3, 1)
w = tf.reshape(w, [3, 3, 1, 1])
tf.get_variable('Conv/weights', initializer=w)
tf.get_variable('Conv/biases', initializer=tf.zeros([1]))
tf.get_variable_scope().reuse_variables()
y1 = slim.conv2d(x, 1, [3, 3], stride=1, scope='Conv')
y1_expected = tf.to_float([[14, 28, 43, 58, 34],
[28, 48, 66, 84, 46],
[43, 66, 84, 102, 55],
[58, 84, 102, 120, 64],
[34, 46, 55, 64, 30]])
y1_expected = tf.reshape(y1_expected, [1, n, n, 1])
y2 = resnet_utils.subsample(y1, 2)
y2_expected = tf.to_float([[14, 43, 34],
[43, 84, 55],
[34, 55, 30]])
y2_expected = tf.reshape(y2_expected, [1, n2, n2, 1])
y3 = resnet_utils.conv2d_same(x, 1, 3, stride=2, scope='Conv')
y3_expected = y2_expected
y4 = slim.conv2d(x, 1, [3, 3], stride=2, scope='Conv')
y4_expected = y2_expected
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
self.assertAllClose(y1.eval(), y1_expected.eval())
self.assertAllClose(y2.eval(), y2_expected.eval())
self.assertAllClose(y3.eval(), y3_expected.eval())
self.assertAllClose(y4.eval(), y4_expected.eval())
def _resnet_plain(self, inputs, blocks, output_stride=None, scope=None):
"""A plain ResNet without extra layers before or after the ResNet blocks."""
with tf.variable_scope(scope, values=[inputs]):
with slim.arg_scope([slim.conv2d], outputs_collections='end_points'):
net = resnet_utils.stack_blocks_dense(inputs, blocks, output_stride)
end_points = slim.utils.convert_collection_to_dict('end_points')
return net, end_points
def testEndPointsV1(self):
"""Test the end points of a tiny v1 bottleneck network."""
blocks = [
resnet_v1.resnet_v1_block(
'block1', base_depth=1, num_units=2, stride=2),
resnet_v1.resnet_v1_block(
'block2', base_depth=2, num_units=2, stride=1),
]
inputs = create_test_input(2, 32, 16, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
_, end_points = self._resnet_plain(inputs, blocks, scope='tiny')
expected = [
'tiny/block1/unit_1/bottleneck_v1/shortcut',
'tiny/block1/unit_1/bottleneck_v1/conv1',
'tiny/block1/unit_1/bottleneck_v1/conv2',
'tiny/block1/unit_1/bottleneck_v1/conv3',
'tiny/block1/unit_2/bottleneck_v1/conv1',
'tiny/block1/unit_2/bottleneck_v1/conv2',
'tiny/block1/unit_2/bottleneck_v1/conv3',
'tiny/block2/unit_1/bottleneck_v1/shortcut',
'tiny/block2/unit_1/bottleneck_v1/conv1',
'tiny/block2/unit_1/bottleneck_v1/conv2',
'tiny/block2/unit_1/bottleneck_v1/conv3',
'tiny/block2/unit_2/bottleneck_v1/conv1',
'tiny/block2/unit_2/bottleneck_v1/conv2',
'tiny/block2/unit_2/bottleneck_v1/conv3']
self.assertItemsEqual(expected, end_points)
def _stack_blocks_nondense(self, net, blocks):
"""A simplified ResNet Block stacker without output stride control."""
for block in blocks:
with tf.variable_scope(block.scope, 'block', [net]):
for i, unit in enumerate(block.args):
with tf.variable_scope('unit_%d' % (i + 1), values=[net]):
net = block.unit_fn(net, rate=1, **unit)
return net
def testAtrousValuesBottleneck(self):
"""Verify the values of dense feature extraction by atrous convolution.
Make sure that dense feature extraction by stack_blocks_dense() followed by
subsampling gives identical results to feature extraction at the nominal
network output stride using the simple self._stack_blocks_nondense() above.
"""
block = resnet_v1.resnet_v1_block
blocks = [
block('block1', base_depth=1, num_units=2, stride=2),
block('block2', base_depth=2, num_units=2, stride=2),
block('block3', base_depth=4, num_units=2, stride=2),
block('block4', base_depth=8, num_units=2, stride=1),
]
nominal_stride = 8
# Test both odd and even input dimensions.
height = 30
width = 31
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
with slim.arg_scope([slim.batch_norm], is_training=False):
for output_stride in [1, 2, 4, 8, None]:
with tf.Graph().as_default():
with self.test_session() as sess:
tf.set_random_seed(0)
inputs = create_test_input(1, height, width, 3)
# Dense feature extraction followed by subsampling.
output = resnet_utils.stack_blocks_dense(inputs,
blocks,
output_stride)
if output_stride is None:
factor = 1
else:
factor = nominal_stride // output_stride
output = resnet_utils.subsample(output, factor)
# Make the two networks use the same weights.
tf.get_variable_scope().reuse_variables()
# Feature extraction at the nominal network rate.
expected = self._stack_blocks_nondense(inputs, blocks)
sess.run(tf.global_variables_initializer())
output, expected = sess.run([output, expected])
self.assertAllClose(output, expected, atol=1e-4, rtol=1e-4)
class ResnetCompleteNetworkTest(tf.test.TestCase):
"""Tests with complete small ResNet v1 networks."""
def _resnet_small(self,
inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
include_root_block=True,
reuse=None,
scope='resnet_v1_small'):
"""A shallow and thin ResNet v1 for faster tests."""
block = resnet_v1.resnet_v1_block
blocks = [
block('block1', base_depth=1, num_units=3, stride=2),
block('block2', base_depth=2, num_units=3, stride=2),
block('block3', base_depth=4, num_units=3, stride=2),
block('block4', base_depth=8, num_units=2, stride=1),
]
return resnet_v1.resnet_v1(inputs, blocks, num_classes,
is_training=is_training,
global_pool=global_pool,
output_stride=output_stride,
include_root_block=include_root_block,
reuse=reuse,
scope=scope)
def testClassificationEndPoints(self):
global_pool = True
num_classes = 10
inputs = create_test_input(2, 224, 224, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
logits, end_points = self._resnet_small(inputs, num_classes,
global_pool=global_pool,
scope='resnet')
self.assertTrue(logits.op.name.startswith('resnet/logits'))
self.assertListEqual(logits.get_shape().as_list(), [2, 1, 1, num_classes])
self.assertTrue('predictions' in end_points)
self.assertListEqual(end_points['predictions'].get_shape().as_list(),
[2, 1, 1, num_classes])
def testClassificationShapes(self):
global_pool = True
num_classes = 10
inputs = create_test_input(2, 224, 224, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
_, end_points = self._resnet_small(inputs, num_classes,
global_pool=global_pool,
scope='resnet')
endpoint_to_shape = {
'resnet/block1': [2, 28, 28, 4],
'resnet/block2': [2, 14, 14, 8],
'resnet/block3': [2, 7, 7, 16],
'resnet/block4': [2, 7, 7, 32]}
for endpoint in endpoint_to_shape:
shape = endpoint_to_shape[endpoint]
self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
def testFullyConvolutionalEndpointShapes(self):
global_pool = False
num_classes = 10
inputs = create_test_input(2, 321, 321, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
_, end_points = self._resnet_small(inputs, num_classes,
global_pool=global_pool,
scope='resnet')
endpoint_to_shape = {
'resnet/block1': [2, 41, 41, 4],
'resnet/block2': [2, 21, 21, 8],
'resnet/block3': [2, 11, 11, 16],
'resnet/block4': [2, 11, 11, 32]}
for endpoint in endpoint_to_shape:
shape = endpoint_to_shape[endpoint]
self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
def testRootlessFullyConvolutionalEndpointShapes(self):
global_pool = False
num_classes = 10
inputs = create_test_input(2, 128, 128, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
_, end_points = self._resnet_small(inputs, num_classes,
global_pool=global_pool,
include_root_block=False,
scope='resnet')
endpoint_to_shape = {
'resnet/block1': [2, 64, 64, 4],
'resnet/block2': [2, 32, 32, 8],
'resnet/block3': [2, 16, 16, 16],
'resnet/block4': [2, 16, 16, 32]}
for endpoint in endpoint_to_shape:
shape = endpoint_to_shape[endpoint]
self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
def testAtrousFullyConvolutionalEndpointShapes(self):
global_pool = False
num_classes = 10
output_stride = 8
inputs = create_test_input(2, 321, 321, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
_, end_points = self._resnet_small(inputs,
num_classes,
global_pool=global_pool,
output_stride=output_stride,
scope='resnet')
endpoint_to_shape = {
'resnet/block1': [2, 41, 41, 4],
'resnet/block2': [2, 41, 41, 8],
'resnet/block3': [2, 41, 41, 16],
'resnet/block4': [2, 41, 41, 32]}
for endpoint in endpoint_to_shape:
shape = endpoint_to_shape[endpoint]
self.assertListEqual(end_points[endpoint].get_shape().as_list(), shape)
def testAtrousFullyConvolutionalValues(self):
"""Verify dense feature extraction with atrous convolution."""
nominal_stride = 32
for output_stride in [4, 8, 16, 32, None]:
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
with tf.Graph().as_default():
with self.test_session() as sess:
tf.set_random_seed(0)
inputs = create_test_input(2, 81, 81, 3)
# Dense feature extraction followed by subsampling.
output, _ = self._resnet_small(inputs, None, is_training=False,
global_pool=False,
output_stride=output_stride)
if output_stride is None:
factor = 1
else:
factor = nominal_stride // output_stride
output = resnet_utils.subsample(output, factor)
# Make the two networks use the same weights.
tf.get_variable_scope().reuse_variables()
# Feature extraction at the nominal network rate.
expected, _ = self._resnet_small(inputs, None, is_training=False,
global_pool=False)
sess.run(tf.global_variables_initializer())
self.assertAllClose(output.eval(), expected.eval(),
atol=1e-4, rtol=1e-4)
def testUnknownBatchSize(self):
batch = 2
height, width = 65, 65
global_pool = True
num_classes = 10
inputs = create_test_input(None, height, width, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
logits, _ = self._resnet_small(inputs, num_classes,
global_pool=global_pool,
scope='resnet')
self.assertTrue(logits.op.name.startswith('resnet/logits'))
self.assertListEqual(logits.get_shape().as_list(),
[None, 1, 1, num_classes])
images = create_test_input(batch, height, width, 3)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
output = sess.run(logits, {inputs: images.eval()})
self.assertEqual(output.shape, (batch, 1, 1, num_classes))
def testFullyConvolutionalUnknownHeightWidth(self):
batch = 2
height, width = 65, 65
global_pool = False
inputs = create_test_input(batch, None, None, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
output, _ = self._resnet_small(inputs, None, global_pool=global_pool)
self.assertListEqual(output.get_shape().as_list(),
[batch, None, None, 32])
images = create_test_input(batch, height, width, 3)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
output = sess.run(output, {inputs: images.eval()})
self.assertEqual(output.shape, (batch, 3, 3, 32))
def testAtrousFullyConvolutionalUnknownHeightWidth(self):
batch = 2
height, width = 65, 65
global_pool = False
output_stride = 8
inputs = create_test_input(batch, None, None, 3)
with slim.arg_scope(resnet_utils.resnet_arg_scope()):
output, _ = self._resnet_small(inputs,
None,
global_pool=global_pool,
output_stride=output_stride)
self.assertListEqual(output.get_shape().as_list(),
[batch, None, None, 32])
images = create_test_input(batch, height, width, 3)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
output = sess.run(output, {inputs: images.eval()})
self.assertEqual(output.shape, (batch, 9, 9, 32))
if __name__ == '__main__':
tf.test.main()
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" ?>
<!DOCTYPE msxconfig SYSTEM 'msxconfig2.dtd'>
<msxconfig>
<info>
<manufacturer>National</manufacturer>
<code>FS-1300</code>
<release_year>1985</release_year>
<description/>
<type>MSX</type>
</info>
<!--
From Daniel Ravazzi's machine:
CPU: Zilog
PSG: GI AY-3-8910A
PPI: NEC D8255AC-2
-->
<CassettePort/>
<devices>
<PPI id="ppi">
<sound>
<volume>16000</volume>
</sound>
<io base="0xA8" num="4"/>
<keyboard_type>jp_ansi</keyboard_type>
<has_keypad>false</has_keypad>
<key_ghosting_sgc_protected>false</key_ghosting_sgc_protected>
<code_kana_locks>true</code_kana_locks>
<graph_locks>false</graph_locks>
</PPI>
<VDP id="VDP">
<version>TMS9918A</version>
<io base="0x98" num="2"/>
</VDP>
<PSG id="PSG">
<type>AY8910</type>
<keyboardlayout>50on</keyboardlayout>
<sound>
<volume>21000</volume>
</sound>
<io base="0xA0" num="2" type="O"/>
<io base="0xA2" num="1" type="I"/>
<ignorePortDirections>false</ignorePortDirections> <!-- not sure, but guess based on discrete PSG chip -->
</PSG>
<PrinterPort id="Printer Port">
<io base="0x90" num="2"/>
</PrinterPort>
<primary slot="0">
<ROM id="MSX BIOS with BASIC ROM">
<rom>
<filename>fs-1300_basic-bios1.rom</filename>
<sha1>c7a2c5baee6a9f0e1c6ee7d76944c0ab1886796c</sha1>
</rom>
<mem base="0x0000" size="0x8000"/>
</ROM>
</primary>
<primary external="true" slot="1"/>
<primary external="true" slot="2"/>
<primary slot="3">
<RAM id="Main RAM">
<mem base="0x0000" size="0x10000"/>
</RAM>
</primary>
</devices>
</msxconfig>
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u03c0.\u03bc.",
"\u03bc.\u03bc."
],
"DAY": [
"\u039a\u03c5\u03c1\u03b9\u03b1\u03ba\u03ae",
"\u0394\u03b5\u03c5\u03c4\u03ad\u03c1\u03b1",
"\u03a4\u03c1\u03af\u03c4\u03b7",
"\u03a4\u03b5\u03c4\u03ac\u03c1\u03c4\u03b7",
"\u03a0\u03ad\u03bc\u03c0\u03c4\u03b7",
"\u03a0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae",
"\u03a3\u03ac\u03b2\u03b2\u03b1\u03c4\u03bf"
],
"ERANAMES": [
"\u03c0\u03c1\u03bf \u03a7\u03c1\u03b9\u03c3\u03c4\u03bf\u03cd",
"\u03bc\u03b5\u03c4\u03ac \u03a7\u03c1\u03b9\u03c3\u03c4\u03cc\u03bd"
],
"ERAS": [
"\u03c0.\u03a7.",
"\u03bc.\u03a7."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u0399\u03b1\u03bd\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u03a6\u03b5\u03b2\u03c1\u03bf\u03c5\u03b1\u03c1\u03af\u03bf\u03c5",
"\u039c\u03b1\u03c1\u03c4\u03af\u03bf\u03c5",
"\u0391\u03c0\u03c1\u03b9\u03bb\u03af\u03bf\u03c5",
"\u039c\u03b1\u0390\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bd\u03af\u03bf\u03c5",
"\u0399\u03bf\u03c5\u03bb\u03af\u03bf\u03c5",
"\u0391\u03c5\u03b3\u03bf\u03cd\u03c3\u03c4\u03bf\u03c5",
"\u03a3\u03b5\u03c0\u03c4\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039f\u03ba\u03c4\u03c9\u03b2\u03c1\u03af\u03bf\u03c5",
"\u039d\u03bf\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5",
"\u0394\u03b5\u03ba\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5"
],
"SHORTDAY": [
"\u039a\u03c5\u03c1",
"\u0394\u03b5\u03c5",
"\u03a4\u03c1\u03af",
"\u03a4\u03b5\u03c4",
"\u03a0\u03ad\u03bc",
"\u03a0\u03b1\u03c1",
"\u03a3\u03ac\u03b2"
],
"SHORTMONTH": [
"\u0399\u03b1\u03bd",
"\u03a6\u03b5\u03b2",
"\u039c\u03b1\u03c1",
"\u0391\u03c0\u03c1",
"\u039c\u03b1\u0390",
"\u0399\u03bf\u03c5\u03bd",
"\u0399\u03bf\u03c5\u03bb",
"\u0391\u03c5\u03b3",
"\u03a3\u03b5\u03c0",
"\u039f\u03ba\u03c4",
"\u039d\u03bf\u03b5",
"\u0394\u03b5\u03ba"
],
"STANDALONEMONTH": [
"\u0399\u03b1\u03bd\u03bf\u03c5\u03ac\u03c1\u03b9\u03bf\u03c2",
"\u03a6\u03b5\u03b2\u03c1\u03bf\u03c5\u03ac\u03c1\u03b9\u03bf\u03c2",
"\u039c\u03ac\u03c1\u03c4\u03b9\u03bf\u03c2",
"\u0391\u03c0\u03c1\u03af\u03bb\u03b9\u03bf\u03c2",
"\u039c\u03ac\u03b9\u03bf\u03c2",
"\u0399\u03bf\u03cd\u03bd\u03b9\u03bf\u03c2",
"\u0399\u03bf\u03cd\u03bb\u03b9\u03bf\u03c2",
"\u0391\u03cd\u03b3\u03bf\u03c5\u03c3\u03c4\u03bf\u03c2",
"\u03a3\u03b5\u03c0\u03c4\u03ad\u03bc\u03b2\u03c1\u03b9\u03bf\u03c2",
"\u039f\u03ba\u03c4\u03ce\u03b2\u03c1\u03b9\u03bf\u03c2",
"\u039d\u03bf\u03ad\u03bc\u03b2\u03c1\u03b9\u03bf\u03c2",
"\u0394\u03b5\u03ba\u03ad\u03bc\u03b2\u03c1\u03b9\u03bf\u03c2"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "el-cy",
"localeID": "el_CY",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<Feral.label>페럴 무리</Feral.label>
<Feral.description>한계에 몰리면 많은 것을 포기해야 하는 법이지. 만약 한 문명이 몰락한다면 얼마나 많은 걸 포기해야 할까? 저들을 봐. 저들은 세상이 무너진 폐허 속에서 목숨을 부지해야만 했어.
결국 저들도 많은 걸 포기해야 했지. 기술, 문화, 역사, 그들이 쌓아올린 모든 걸. 그들이 포기한 것 중에는 말이야. 자기들의 인간성도 있었어.</Feral.description>
<Feral.pawnsPlural>페럴</Feral.pawnsPlural>
<Feral.leaderTitle>참주</Feral.leaderTitle>
</LanguageData> | {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
// This file contains code common to gen.go and the package code.
// The mapping from rune to string (i.e. offset and length in the data string)
// is encoded as a two level table. The first level maps from contiguous rune
// ranges [runeOffset, runeOffset+runeLength) to entries. Entries are either
// direct (for repeated names such as "<CJK Ideograph>") or indirect (for runs
// of unique names such as "SPACE", "EXCLAMATION MARK", "QUOTATION MARK", ...).
//
// Each first level table element is 64 bits. The runeOffset (21 bits) and
// runeLength (16 bits) take the 37 high bits. The entry takes the 27 low bits,
// with directness encoded in the least significant bit.
//
// A direct entry encodes a dataOffset (18 bits) and dataLength (8 bits) in the
// data string. 18 bits is too short to encode the entire data string's length,
// but the data string's contents are arranged so that all of the few direct
// entries' offsets come before all of the many indirect entries' offsets.
//
// An indirect entry encodes a dataBase (10 bits) and a table1Offset (16 bits).
// The table1Offset is the start of a range in the second level table. The
// length of that range is the same as the runeLength.
//
// Each second level table element is 16 bits, an index into data, relative to
// a bias equal to (dataBase << dataBaseUnit). That (bias + index) is the
// (dataOffset + dataLength) in the data string. The dataOffset is implied by
// the previous table element (with the same implicit bias).
const (
bitsRuneOffset = 21
bitsRuneLength = 16
bitsDataOffset = 18
bitsDataLength = 8
bitsDirect = 1
bitsDataBase = 10
bitsTable1Offset = 16
shiftRuneOffset = 0 + bitsDirect + bitsDataLength + bitsDataOffset + bitsRuneLength
shiftRuneLength = 0 + bitsDirect + bitsDataLength + bitsDataOffset
shiftDataOffset = 0 + bitsDirect + bitsDataLength
shiftDataLength = 0 + bitsDirect
shiftDirect = 0
shiftDataBase = 0 + bitsDirect + bitsTable1Offset
shiftTable1Offset = 0 + bitsDirect
maskRuneLength = 1<<bitsRuneLength - 1
maskDataOffset = 1<<bitsDataOffset - 1
maskDataLength = 1<<bitsDataLength - 1
maskDirect = 1<<bitsDirect - 1
maskDataBase = 1<<bitsDataBase - 1
maskTable1Offset = 1<<bitsTable1Offset - 1
dataBaseUnit = 10
)
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;
namespace PerfIt.WebApi
{
public abstract class InstrumentationContextProviderBaseAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
if (!actionExecutedContext.Request.Properties.ContainsKey(Constants.PerfItInstrumentationContextKey))
actionExecutedContext.Request.Properties.Add(Constants.PerfItInstrumentationContextKey,
ProvideInstrumentationContext(actionExecutedContext));
}
protected abstract string ProvideInstrumentationContext(HttpActionExecutedContext actionExecutedContext);
}
}
| {
"pile_set_name": "Github"
} |
/**
* 登陆页
*
*
* @date 2017-11-07
* @author liuzheng <[email protected]>
*/
import {Component, OnInit} from '@angular/core';
import {AppService, HttpService, LogService} from '@app/services';
import {NgForm} from '@angular/forms';
import {Router} from '@angular/router';
import {DataStore, User} from '@app/globals';
import * as jQuery from 'jquery/dist/jquery.min.js';
@Component({
selector: 'pages-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class PagesLoginComponent implements OnInit {
DataStore = DataStore;
User = User;
loginBotton = 'login to your account';
constructor(private _appService: AppService,
private _http: HttpService,
private _router: Router,
private _logger: LogService) {
this._logger.log('login.ts:LoginComponent');
DataStore.NavShow = false;
}
onSubmit(f: NgForm) {
if (f.valid) {
this.login();
} else {
this._logger.error('the form not valid');
}
}
login() {
this._logger.log('service.ts:AppService,login');
DataStore.error['login'] = '';
this._logger.log(User);
if (User.username.length > 0 && User.password.length > 6 && User.password.length < 100) {
this._http.checkLogin(JSON.stringify(User))
.subscribe(
data => {
User.logined = data['logined'];
User.name = data['name'];
User.username = data['username'];
User.logined = data['logined'];
},
err => {
this._logger.error(err);
User.logined = false;
this._router.navigate(['login']);
DataStore.error['login'] = '后端错误,请重试';
return '后端错误,请重试';
},
() => {
if (User.logined) {
if (jQuery.isEmptyObject(DataStore.Path)) {
this._router.navigate(['welcome']);
} else {
this._router.navigate([DataStore.Path['name'], DataStore.Path['res']]);
}
} else {
this._router.navigate(['login']);
DataStore.error['login'] = '请检查用户名和密码';
return '请检查用户名和密码';
}
// jQuery('angular2').show();
});
} else {
DataStore.error['login'] = '请检查用户名和密码';
return '请检查用户名和密码';
}
}
ngOnInit() {
jQuery('#form').fadeIn('slow');
// this._router.navigate(['login']);
// jQuery('nav').hide();
}
}
| {
"pile_set_name": "Github"
} |
use v6;
use Test;
plan 19;
=begin description
Rakudo had a bug which caused failures when a regex match happened inside the
body of a C<while> loop.
So now we test that you can use both a regex and its result object in any
kind of block, and in the condition, if any.
=end description
# https://github.com/Raku/old-issue-tracker/issues/276
if 1 {
ok 'a' ~~ /./, 'Can match in an if block';
is ~$/, 'a', '... and can use the match var';
}
ok defined($/), '$/ is a dynamic lexical, so it is set outside that block.';
my $loop = 1;
while $loop {
ok 'b' ~~ /./, 'Can match in a while block';
is ~$/, 'b', '... and can use the match var';
$loop = 0;
}
{
ok 'c' ~~ /./, 'Can match in a bare block';
is ~$/, 'c', '... and can use the match var';
}
my $discarded = do {
ok 'd' ~~ /./, 'Can match in a do block';
is ~$/, 'd', '... and can use the match var';
}
{
my $str = 'abc';
my $count = 0;
my $match = '';;
while $str ~~ /b/ {
$count++;
$match = "$/";
$str = '';
}
ok $count, 'Can match in the condition of a while loop';
is $match, 'b', '... and can use $/ in the block';
#?rakudo todo 'Assignment to matched string affects earlier match objects'
is "$/", 'b', '... and can use $/ outside the block';
}
{
my $match = '';
if 'xyc' ~~ /x/ {
$match = "$/";
}
is $match, 'x', 'Can match in the condition of an if statement';
is "$/", 'x', '... and can use $/ outside the block';
}
{
given '-Wall' {
if $_ ~~ /al/ {
ok $/ eq 'al', '$/ is properly set with explicit $_ in a given { } block';
}
else {
flunk 'regex did not match - $/ is properly set with explicit $_ in a given { } block';
}
if /\w+/ {
is $/, 'Wall', '$/ is properly set in a given { } block';
} else {
flunk 'regex did not match - $/ is properly set in a given { } block';
}
}
}
# TODO: repeat ... until, gather/take, lambdas, if/unless statement modifiers
# TODO: move to integration/
# test that a regex in an `if' matches against $_, not boolifies
{
my $s1 = 0;
my $s2 = 1;
given 'foo' {
if /foo/ { $s1 = 1 }
if /not/ { $s2 = 0 }
}
is $s1, 1, '/foo/ matched against $_ (successfully)';
is $s2, 1, '/not/ matched against $_ (no match)';
given 'foo' {
if /bar/ {
ok 0, 'match in /if/;'
} else {
ok 1, 'match in /if/;'
}
}
}
# vim: expandtab shiftwidth=4
| {
"pile_set_name": "Github"
} |
const string[,] FOO = {
{ "00", "01", "02" },
{ "10", "11", "12" },
{ "20", "21", "22" }
};
void main () {
const string[,] BAR = {
{ "00", "01", "02" },
{ "10", "11", "12" },
{ "20", "21", "22" }
};
for (int i = 0; i < FOO.length[0]; i++) {
assert (FOO[i,0] == "%d%d".printf (i, 0));
assert (FOO[i,1] == "%d%d".printf (i, 1));
assert (FOO[i,2] == "%d%d".printf (i, 2));
}
for (int i = 0; i < BAR.length[0]; i++) {
assert (BAR[i,0] == "%d%d".printf (i, 0));
assert (BAR[i,1] == "%d%d".printf (i, 1));
assert (BAR[i,2] == "%d%d".printf (i, 2));
}
assert (FOO[0,0] == "%d%d".printf (0, 0));
assert (FOO[1,1] == "%d%d".printf (1, 1));
assert (FOO[2,2] == "%d%d".printf (2, 2));
assert (BAR[0,0] == "%d%d".printf (0, 0));
assert (BAR[1,1] == "%d%d".printf (1, 1));
assert (BAR[2,2] == "%d%d".printf (2, 2));
}
| {
"pile_set_name": "Github"
} |
import webpack from 'webpack'
import path from 'path'
import fs from 'fs'
import rimraf from 'rimraf'
const testBundle = name => new Promise((resolve, reject) => {
const compiler = webpack({
context: __dirname,
entry: { [name]: [`./${name}.js`] },
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: JSON.parse(fs.readFileSync(path.join(__dirname, '../..', '.babelrc'))),
include: __dirname,
exclude: path.join(__dirname, '../..', 'node_modules')
}
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: `${name}.js`
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
mangle: { screw_ie8: true },
output: {
screw_ie8: true,
comments: false
},
compress: {
screw_ie8: true,
warnings: false
}
})
]
})
compiler.run((err) => {
if (err) {
reject(err)
} else {
console.log(
`Size ${name}`,
`${fs.statSync(path.join(__dirname, 'dist', `${name}.js`)).size / 1000.0}KB`
)
resolve()
}
})
})
Promise
.all([
testBundle('205-static'),
testBundle('300-static'),
testBundle('301-static'),
testBundle('302-static'),
testBundle('205-dynamic'),
testBundle('300-dynamic'),
testBundle('301-dynamic'),
testBundle('302-dynamic')
])
.then(() => {
rimraf(path.join(__dirname, 'dist'), (err) => {
if (err) {
throw err
}
})
})
.catch((err) => {
console.error(err)
throw err
})
| {
"pile_set_name": "Github"
} |
package ecs
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// RecycleBinModels is a nested struct in ecs response
type RecycleBinModels struct {
RecycleBinModel []RecycleBinModel `json:"RecycleBinModel" xml:"RecycleBinModel"`
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
""" The Frame Viewer for Faceswap's Manual Tool. """
from ._base import View # noqa
from .bounding_box import BoundingBox # noqa
from .extract_box import ExtractBox # noqa
from .landmarks import Landmarks, Mesh # noqa
from .mask import Mask # noqa
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<xs:schema targetNamespace="http://isis.apache.org/schema/ixn"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://isis.apache.org/schema/ixn"
xmlns:cmd="http://isis.apache.org/schema/cmd"
xmlns:com="http://isis.apache.org/schema/common"
>
<xs:import namespace="http://isis.apache.org/schema/common" schemaLocation="../common/common-1.1.xsd"/>
<xs:import namespace="http://isis.apache.org/schema/cmd" schemaLocation="../cmd/cmd-1.4.xsd"/>
<xs:element name="interactionDto">
<xs:annotation>
<xs:documentation>Represents v1.3 of this schema (as per majorVersion.minorVersion @default attribute, below); just updates to use cmd v1.4 schema.
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="majorVersion" type="xs:string" minOccurs="0" maxOccurs="1" default="1">
<xs:annotation>
<xs:documentation>The major version of the schema that an XML instance was created using.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="minorVersion" type="xs:string" minOccurs="0" maxOccurs="1" default="3">
<xs:annotation>
<xs:documentation>The minor version of the schema that an XML instance was created using.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="transactionId" type="xs:string">
<xs:annotation>
<xs:documentation>Unique identifier of the interaction which this member was interacted with (action invoked/property edited); can be used to locate the corresponding Command object (which may have been persisted).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="execution" type="memberExecutionDto"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="memberExecutionDto" abstract="true">
<xs:annotation>
<xs:documentation>Represents either an action invocation or a property edit. Is subclassed by both.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="sequence" type="xs:int">
<xs:annotation>
<xs:documentation>Unique sequence number of an individual member interaction within the overall interaction. There could be many such member interactions (within a single transaction) for two reasons: either a single top-level interaction could call sub-interactions (by virtue of WrapperFactory), or there may be a bulk action interaction against many targets.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="target" type="com:oidDto">
<xs:annotation>
<xs:documentation>For target domain object being interacted with. For regular actions/properties, represents the entity or view model upon which the action is to be invoked/property edited. For mixin actions/properties, is the object being mixed-into (the constructor arg to the mixin). For contributed actions/properties, is the domain service (the contributee object will be one of the action arguments within the payload).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="logicalMemberIdentifier" type="xs:string">
<xs:annotation>
<xs:documentation>Logical formal identifier (object type, as per @DomainObject(objectType=), and member name) of the member being interacted with (action or property).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="memberIdentifier" type="xs:string">
<xs:annotation>
<xs:documentation>Formal identifier (class name and member name) of the member being interacted with (action or property).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="user" type="xs:string">
<xs:annotation>
<xs:documentation>The name of the user that invoked this action. Note that this isn't necessarily the user that initiated the original command; the SudoService may be being used to temporarily switch the effective user.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="title" type="xs:string">
<xs:annotation>
<xs:documentation>User-friendly title of the 'target' object.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="metrics" type="metricsDto">
<xs:annotation>
<xs:documentation>Profiling metrics capturng the this time/number of objects affected as a result of performing this member interaction (invoke the action, or edit the property).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="threw" type="exceptionDto" minOccurs="0" maxOccurs="1">
<xs:annotation>
<xs:documentation>Captures any exception thrown by an action. Either the 'returned' or the 'threw' element will be populated.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="childExecutions" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="execution" type="memberExecutionDto" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>Capture interactions with other members from this interaction, using the WrapperFactory service. Typically this will be actions invoking other actions, but it is also possible for an action to perform a property edit, and - much rarer - for a property edit to invoke an action. Whatever; these interactions nest together into a call/stack, more generally into a graph.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="interactionType" type="com:interactionType">
<xs:annotation>
<xs:documentation>Indicates whether this is an intention to invoke an action, or edit a property.
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
<xs:complexType name="actionInvocationDto">
<xs:complexContent>
<xs:extension base="memberExecutionDto">
<xs:sequence>
<xs:element name="parameters" type="cmd:paramsDto">
<xs:annotation>
<xs:documentation>The list of parameter/argument values for this action invocation.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="returned" type="com:valueWithTypeDto" minOccurs="0" maxOccurs="1">
<xs:annotation>
<xs:documentation>The value returned by this action (including the type of that returned value). Either the 'returned' or the 'threw' element (from 'memberExecutionDto') will be populated.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="propertyEditDto">
<xs:complexContent>
<xs:extension base="memberExecutionDto">
<xs:sequence>
<xs:element name="newValue" type="com:valueWithTypeDto"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="metricsDto">
<xs:sequence>
<xs:element name="timings" type="com:periodDto">
<xs:annotation>
<xs:documentation>The time taken to perform the member interaction (invoke the action, or edit the property).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="objectCounts" type="objectCountsDto">
<xs:annotation>
<xs:documentation>How many objets were affected by the member interaction.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="objectCountsDto">
<xs:sequence>
<xs:element name="loaded" type="com:differenceDto">
<xs:annotation>
<xs:documentation>The number of objects loaded.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="dirtied" type="com:differenceDto">
<xs:annotation>
<xs:documentation>The number of objects dirtied (ie updated).
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="exceptionDto">
<xs:annotation>
<xs:documentation>Captures any exception thrown by an action invocation. Use as the xsd:type of the 'threw' element.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="message" type="xs:string"/>
<xs:element name="stackTrace" type="xs:string">
<xs:annotation>
<xs:documentation>A formatted stack trace. (A future version of the 'exceptionDto' element might refine this to more easily parseable stack trace elements).
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="causedBy" type="exceptionDto" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
| {
"pile_set_name": "Github"
} |
# clear
* set[meta header]
* std[meta namespace]
* set[meta class]
* function[meta id-type]
```cpp
void clear() noexcept;
```
## 概要
`set` コンテナ内の全ての要素を削除する。それぞれのデストラクタが呼ばれ、コンテナから削除される。[`size()`](size.md) は 0 になる。
## 計算量
線形時間
## 例外
投げない
## 例
```cpp example
#include <iostream>
#include <set>
int main ()
{
std::set<int> c;
c.insert(10);
c.insert(20);
c.insert(30);
std::cout << c.size() << std::endl;
c.clear();
std::cout << c.size() << std::endl;
}
```
* clear()[color ff0000]
* c.insert[link insert.md]
* c.size()[link size.md]
### 出力
```
3
0
```
## 関連項目
| 名前 | 説明 |
|-----------------------|------------------------------------|
| [`erase`](erase.md) | 要素を削除する |
| [`size`](size.md) | 要素数を取得する |
| [`empty`](empty.md) | コンテナが空であるかどうかを調べる |
| {
"pile_set_name": "Github"
} |
// --------------------------------------------------------------------------------------------------------------------
// <summary>
// Defines the Setup type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Awesome.Wpf
{
using System.Windows.Threading;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.Wpf.Platform;
using Cirrious.MvvmCross.Wpf.Views;
/// <summary>
/// Defines the Setup type.
/// </summary>
public class Setup : MvxWpfSetup
{
/// <summary>
/// Initializes a new instance of the <see cref="Setup"/> class.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="presenter">The presenter.</param>
public Setup(Dispatcher dispatcher, IMvxWpfViewPresenter presenter)
: base(dispatcher, presenter)
{
}
/// <summary>
/// Creates the app.
/// </summary>
/// <returns>An instance of MvxApplication</returns>
protected override IMvxApplication CreateApp()
{
return new Core.App();
}
}
}
| {
"pile_set_name": "Github"
} |
<!--
Description: iTunes explicit='no'
Expect: not bozo and entries[0]['itunes_explicit'] is None
-->
<rss xmlns:itunes="http://www.itunes.com/DTDs/Podcast-1.0.dtd">
<channel>
<item>
<itunes:explicit>no</itunes:explicit>
</item>
</channel>
</rss>
| {
"pile_set_name": "Github"
} |
# SecuML
# Copyright (C) 2016-2019 ANSSI
#
# SecuML is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# SecuML is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with SecuML. If not, see <http://www.gnu.org/licenses/>.
from . import Queries
class TopNQueries(Queries):
def __init__(self, iteration, num_annotations):
Queries.__init__(self, iteration)
self.num_annotations = num_annotations
def run_models(self):
return
def generate_queries(self, already_queried=None):
assert(not already_queried) # the list must be empty
selection = self.predictions.get_alerts(top_n=self.num_annotations)
for prediction in selection:
query = self.generate_query(prediction.instance_id,
prediction.proba, None, None)
self.add_query(query)
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: cf781e873d93b9f49a0a07788063c144
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
--TEST--
Test fprintf() function (variation - 7)
--SKIPIF--
<?php
$data_file = dirname(__FILE__) . '/dump.txt';
if (!($fp = fopen($data_file, 'w'))) {
die('skip File dump.txt could not be created');
}
if (PHP_INT_SIZE != 4) die("skip this test is for 32bit platform only");
?>
--FILE--
<?php
$int_numbers = array( 0, 1, -1, 2.7, -2.7, 23333333, -23333333, "1234" );
/* creating dumping file */
$data_file = dirname(__FILE__) . '/dump.txt';
if (!($fp = fopen($data_file, 'wt')))
return;
/* octal type variations */
fprintf($fp, "\n*** Testing fprintf() for octals ***\n");
foreach( $int_numbers as $octal_num ) {
fprintf( $fp, "\n");
fprintf( $fp, "%o", $octal_num );
}
fclose($fp);
print_r(file_get_contents($data_file));
echo "\nDone";
unlink($data_file);
?>
--EXPECTF--
*** Testing fprintf() for octals ***
0
1
37777777777
2
37777777776
131004725
37646773053
2322
Done
| {
"pile_set_name": "Github"
} |
// $Id$
/*
* CraftBook Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not,
* see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.craftbook.mechanics;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.Directional;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import com.sk89q.craftbook.AbstractCraftBookMechanic;
import com.sk89q.craftbook.util.EventUtil;
import com.sk89q.craftbook.util.events.SourcedBlockRedstoneEvent;
import com.sk89q.util.yaml.YAMLProcessor;
/**
* This mechanism allow players to toggle Jack-o-Lanterns.
*
* @author sk89q
*/
public class JackOLantern extends AbstractCraftBookMechanic {
@EventHandler(priority = EventPriority.HIGH)
public void onBlockRedstoneChange(SourcedBlockRedstoneEvent event) {
if(!EventUtil.passesFilter(event)) return;
if(event.isMinor())
return;
if (event.getBlock().getType() != Material.CARVED_PUMPKIN && event.getBlock().getType() != Material.JACK_O_LANTERN) return;
if(event.isOn() == (event.getBlock().getType() == Material.JACK_O_LANTERN))
return;
setPowered(event.getBlock(), event.isOn());
}
private static void setPowered(Block block, boolean on) {
BlockFace data = ((Directional) block.getBlockData()).getFacing();
block.setType(on ? Material.JACK_O_LANTERN : Material.CARVED_PUMPKIN);
Directional directional = (Directional) block.getBlockData();
directional.setFacing(data);
block.setBlockData(directional);
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event) {
if(!EventUtil.passesFilter(event)) return;
if (event.getBlock().getType() != Material.CARVED_PUMPKIN && event.getBlock().getType() != Material.JACK_O_LANTERN) return;
if (event.getBlock().getType() == Material.JACK_O_LANTERN && (event.getBlock().isBlockIndirectlyPowered() || event.getBlock().isBlockPowered()))
event.setCancelled(true);
}
@Override
public void loadConfiguration (YAMLProcessor config, String path) {
}
} | {
"pile_set_name": "Github"
} |
// Copyright 2016 The Linux Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package specs
import "fmt"
const (
// VersionMajor is for an API incompatible changes
VersionMajor = 1
// VersionMinor is for functionality in a backwards-compatible manner
VersionMinor = 0
// VersionPatch is for backwards-compatible bug fixes
VersionPatch = 1
// VersionDev indicates development branch. Releases will be empty string.
VersionDev = ""
)
// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
| {
"pile_set_name": "Github"
} |
### `require-readonly-react-props`
This rule validates that React props are marked as $ReadOnly. React props are immutable and modifying them could lead to unexpected results. Marking prop shapes as $ReadOnly avoids these issues.
The rule tries its best to work with both class and functional components. For class components, it does a fuzzy check for one of "Component", "PureComponent", "React.Component" and "React.PureComponent". It doesn't actually infer that those identifiers resolve to a proper `React.Component` object.
For example, this will NOT be checked:
```js
import MyReact from 'react';
class Foo extends MyReact.Component { }
```
As a result, you can safely use other classes without getting warnings from this rule:
```js
class MyClass extends MySuperClass { }
```
React's functional components are hard to detect statically. The way it's done here is by searching for JSX within a function. When present, a function is considered a React component:
```js
// this gets checked
type Props = { };
function MyComponent(props: Props) {
return <p />;
}
// this doesn't get checked since no JSX is present in a function
type Options = { };
function SomeHelper(options: Options) {
// ...
}
// this doesn't get checked since no JSX is present directly in a function
function helper() { return <p /> }
function MyComponent(props: Props) {
return helper();
}
```
The rule only works for locally defined props that are marked with a `$ReadOnly` or using covariant notation. It doesn't work with imported props:
```js
// the rule has no way of knowing whether ImportedProps are read-only
import { type ImportedProps } from './somewhere';
class Foo extends React.Component<ImportedProps> { }
// the rule also checks for covariant properties
type Props = {|
+foo: string
|};
class Bar extends React.Component<Props> { }
// this fails because the object is not fully read-only
type Props = {|
+foo: string,
bar: number,
|};
class Bar extends React.Component<Props> { }
// this fails because spreading makes object mutable (as of Flow 0.98)
// https://github.com/gajus/eslint-plugin-flowtype/pull/400#issuecomment-489813899
type Props = {|
+foo: string,
...bar,
|};
class Bar extends React.Component<Props> { }
```
```js
{
"rules": {
"flowtype/require-readonly-react-props": 2
}
}
```
<!-- assertions requireReadonlyReactProps -->
| {
"pile_set_name": "Github"
} |
(function() {
var $ = document.querySelector.bind(document)
$('#form-contact').addEventListener('submit', function(e) {
e.preventDefault()
// Store form field values
var name = $('input[name=name]').value,
email = $('input[name=email]').value,
subject = $('input[name=_subject]').value,
message = $('textarea[name=message]').value,
// AJAX request
request = new XMLHttpRequest(),
data = {
name: name,
_replyto: email,
email: email,
_subject: subject,
message: message
}
// Send to Formspree or Basin
request.open('POST', '{{ if .Site.Params.ajaxFormspree }}https://formspree.io/{{ .Site.Params.email }}{{ else if .Site.Params.ajaxBasin }}{{ .Site.Params.ajaxBasin }}.json{{ end }}', true)
request.setRequestHeader('Content-Type', 'application/json')
request.setRequestHeader('Accept', 'application/json')
// Call function when the state changes
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
// Reset form
$('#form-contact').reset()
var submit = $('#form-submit'),
thanks = $('#form-thankyou')
function thankYouFadeIn() {
// Fade out submit button
submit.style.visibility = 'hidden'
submit.classList.add('hide')
submit.classList.remove('show')
// Fade in thank you message
thanks.style.visibility = 'visible'
thanks.classList.add('show')
thanks.classList.remove('hide')
setTimeout(thankYouFadeOut, 6000)
};
function thankYouFadeOut() {
// Fade out thank you message
thanks.style.visibility = 'hidden'
thanks.classList.add('hide')
thanks.classList.remove('show')
// Fade in submit button
submit.style.visibility = 'visible'
submit.classList.add('show')
submit.classList.remove('hide')
};
thankYouFadeIn()
}
}
request.send(JSON.stringify(data))
})
})()
| {
"pile_set_name": "Github"
} |
Render a submit button
| {
"pile_set_name": "Github"
} |
@echo off
if "%2" equ "" goto fail
setlocal enabledelayedexpansion
set char=%1
set num=%2
for /l %%i in (1,1,%num%) do set res=!res!%char%
echo %res%
:fail
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016-2019, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __WHVCROUTER_H__
#define __WHVCROUTER_H__
// WormHole router with virtual channel and Multicast support.
// -Source Routing is assumed.
// -First flit stores route information.
// -Multi-cast to 1 remote port and many local ports.
// -Changing the destination format and route computation can allow multi-cast
// to all ports without distinction between local and remote ports.
// -Port numbers: local ports are numbered 0 to L-1, remote ports are numbered
// L to L+R-1.
// -1 hot encoding for local destination - send flit to port i if dest[i]=1.
// -Destination format per hop <Remote Dst> <Local Dst> .
// -Destination Width per Hop = r_dest_port_width_per_hop +
// l_dest_port_width_per_hop
// -Remote destination width is log_num_rports
// -Local destination width is num_lports
// -First flit format: <Dest-N> ... <Dest-2> <Dest-1>
// -This implementation assumes that virtual channel information is specified
// at the LSBs of packet id.
// -Termination condition: if dest of next hop is 0
#include <nvhls_packet.h>
#include <nvhls_vector.h>
#include <Arbiter.h>
#include <hls_globals.h>
#include <fifo.h>
#include <one_hot_to_bin.h>
#include <nvhls_assert.h>
#include <crossbar.h>
template <int NumLPorts, int NumRports, int NumVchannels, int BufferSize,
typename FlitType = Flit<64, 0, 0, 0, FlitId2bit, WormHole> >
class WHVCRouterBase : public sc_module {
public:
typedef FlitType Flit_t;
// Declare constants
enum {
num_lports = NumLPorts,
num_rports = NumRports,
num_ports = num_lports + num_rports,
num_vchannels = NumVchannels,
log_num_vchannels = nvhls::index_width<num_vchannels>::val,
log_num_lports = nvhls::index_width<num_lports>::val,
log_num_rports = nvhls::index_width<num_rports>::val,
log_num_ports = nvhls::index_width<num_ports>::val,
buffersize = BufferSize,
log_buffersize = nvhls::index_width<buffersize>::val,
log_buffersizeplus1 = nvhls::index_width<buffersize + 1>::val
};
typedef NVUINTW(log_buffersizeplus1) Credit_t;
typedef NVUINTW(1) Credit_ret_t;
// Input / Output ports
Connections::In<Flit_t> in_port[num_ports];
Connections::Out<Flit_t> out_port[num_ports];
// Credits
// Send out credit when buffer is popped
// Increment local credit when credits are read
// 1 credit counter per output port
Connections::In<Credit_ret_t> in_credit[num_ports * num_vchannels];
Connections::Out<Credit_ret_t> out_credit[num_ports * num_vchannels];
sc_in_clk clk;
sc_in<bool> rst;
// Input FIFO Buffer
FIFO<Flit_t, buffersize, num_ports * num_vchannels> ififo;
// Credit registers to store credits for both producer and consumer
Credit_t credit_recv[num_ports * num_vchannels];
Credit_t credit_send[num_ports * num_vchannels];
// Variable to register outputs
Flit_t flit_out[num_ports];
// Constructor
SC_HAS_PROCESS(WHVCRouterBase);
WHVCRouterBase(sc_module_name name_) : sc_module(name_) {
SC_THREAD(process);
sensitive << clk.pos();
NVHLS_NEG_RESET_SIGNAL_IS(rst);
}
// Function to receive credits from the consumers
void receive_credit() {
Credit_ret_t credit_in;
#pragma hls_unroll yes
for (int i = 0; i < num_ports * num_vchannels; i++) {
if (in_credit[i].PopNB(credit_in)) {
credit_recv[i] = credit_recv[i] + credit_in;
// DCOUT(sc_time_stamp() << ": " << name()
// << " Read credit from credit port-"
// << i << " " << credit_recv[i] << endl);
}
NVHLS_ASSERT_MSG(credit_recv[i] <= buffersize, "Total credits received cannot be larger than Buffer size");
}
}
void send_credit() {
#pragma hls_unroll yes
for (int i = 0; i < num_ports * num_vchannels; i++) {
if (credit_send[i] > 0) {
Credit_ret_t credit_out = 1;
bool temp = out_credit[i].PushNB(credit_out);
if (temp) {
credit_send[i]--;
}
// DCOUT(sc_time_stamp() << ": " << name() << " Returning credit to port
// "
// << i << " credit_send=" << credit_send[i]
// << " Success: " << temp << endl);
}
}
}
void fill_ififo() {
// Read input port if data is available and fill input buffers
Flit_t inflit[num_ports];
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) {
if (in_port[i].PopNB(inflit[i])) {
DCOUT(sc_time_stamp() << ": " << name() << " Read input from port-" << i
<< endl);
if (num_vchannels > 1) {
NVUINTW(log_num_vchannels) vcin_tmp = inflit[i].get_packet_id();
NVHLS_ASSERT_MSG(!ififo.isFull(i * num_vchannels + vcin_tmp), "Input fifo is full");
ififo.push(inflit[i], i * num_vchannels + vcin_tmp);
} else {
NVHLS_ASSERT_MSG(!ififo.isFull(i), "Input fifo is full");
ififo.push(inflit[i], i);
}
}
}
}
void peek_ififo(Flit_t flit_in[num_ports],
NVUINTW(log_num_vchannels) vcin[num_ports],
NVUINTW(num_ports) in_valid) {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the inputs here
// FIFO Read
if (in_valid[i]) {
flit_in[i] = ififo.peek(i * num_vchannels + vcin[i]);
DCOUT(sc_time_stamp()
<< ": " << name() << hex << " Read from FIFO:"
<< i * num_vchannels + vcin[i] << " Flit< " << flit_in[i].flit_id
<< "," << flit_in[i].data.to_uint64() << ">" << dec << endl);
}
}
}
void crossbar_traversal(Flit_t flit_in[num_ports], bool is_push[num_ports],
NVUINTW(log_num_ports) select_id[num_ports],
NVUINTW(log_num_vchannels) vcin[num_ports],
NVUINTW(log_num_vchannels) vcout[num_ports]) {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through output ports here
if (is_push[i]) {
flit_out[i] = flit_in[select_id[i]];
vcout[i] = vcin[select_id[i]];
}
}
}
virtual void reset() { }
virtual void run() { }
void process() {
for (int i = 0; i < num_ports; i++)
in_port[i].Reset();
for (int i = 0; i < num_ports; i++)
out_port[i].Reset();
for (int i = 0; i < num_ports * num_vchannels; i++)
out_credit[i].Reset();
for (int i = 0; i < num_ports * num_vchannels; i++)
in_credit[i].Reset();
ififo.reset();
reset();
// Reset credit registers
for (int i = 0; i < num_ports * num_vchannels; i++) {
credit_send[i] = 0;
credit_recv[i] = buffersize;
}
#pragma hls_pipeline_init_interval 1
while (1) {
wait();
run();
}
}
};
// Specialization for SourceRouting
/**
* \brief Wormhole Router with virtual channels
* \ingroup WHVCRouter
*
* \tparam NumLPorts Number of local ingress/egress ports
* \tparam NumRports Number of remote ports
* \tparam NumVchannels Number of virtual channels
* \tparam BufferSize Buffersize of input fifo
* \tparam FlitType Indicates the Flit type
* \tparam MaxHops Indicates Max. number of hops for SourceRouting
*
* \par A Simple Example
* \code
* #include <WHVCRouter.h>
*
* ...
*
* typedef Flit<64, 0, 0, 0, FlitId2bit, WormHole> Flit_t;
* WHVCRouter<kNumLPorts, kNumRPorts, kNumVChannels, kBufferSize, Flit_t, kNumMaxHops> router;
*
* Connections::In<Flit_t> in_port[kNumPorts];
* Connections::Out<Flit_t> out_port[kNumPorts];
* Connections::In<Credit_t> in_credit[kNumCredits];
* Connections::Out<Credit_t> out_credit[kNumCredits];
*
* for (int i = 0; i < kNumPorts; i++) {
* router.in_port[i](in_port[i]);
* router.out_port[i](out_port[i]);
* for (int j = 0; j < kNumVChannels; j++) {
* router.in_credit[i * kNumVChannels + j](
* in_credit[i * kNumVChannels + j]);
* router.out_credit[i * kNumVChannels + j](
* out_credit[i * kNumVChannels + j]);
* }
* }
* ...
*
* \endcode
* \par
*
*/
template <int NumLPorts, int NumRports, int NumVchannels, int BufferSize,
typename FlitType, int MaxHops>
class WHVCSourceRouter: public WHVCRouterBase<NumLPorts, NumRports, NumVchannels, BufferSize, FlitType> {
public:
// Declare constants
typedef WHVCRouterBase<NumLPorts, NumRports, NumVchannels, BufferSize, FlitType> BaseClass;
typedef FlitType Flit_t;
enum {
num_lports = BaseClass::num_lports,
num_rports = BaseClass::num_rports,
num_ports = BaseClass::num_ports,
num_vchannels = BaseClass::num_vchannels,
log_num_rports = BaseClass::log_num_rports,
log_num_ports = BaseClass::log_num_ports,
log_num_vchannels = BaseClass::log_num_vchannels,
dest_width_per_hop = log_num_rports + num_lports,
dest_width = MaxHops * dest_width_per_hop,
};
WHVCSourceRouter(sc_module_name name_): BaseClass(name_) {
}
Arbiter<num_ports> arbiter[num_ports];
// Store output destination for each port per virtual channel with 1hot
// encoding
NVUINTW(num_ports) out_dest[num_ports][num_vchannels];
// Variable to block output port until previous push is successful
NVUINTW(num_ports) out_stall;
// Variable that indicates if the output port is available to get new packet
bool is_get_new_packet[num_ports * num_vchannels];
void inputvc_arbiter(NVUINTW(log_num_vchannels) vcin[num_ports],
NVUINTW(num_ports) & in_valid) {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the inputs here
vcin[i] = 0;
// Doing static arbitration across input VCs here. VC0 has
// highest priority. We are assuming that input and output VCs
// are same.
if (num_vchannels > 1) {
NVUINTW(num_vchannels) vcin_valid = 0;
NVUINTW(log_num_vchannels) vcin_local = 0;
#pragma hls_unroll yes
for (int j = 0; j < num_vchannels; j++) {
if ((!this->ififo.isEmpty(i * num_vchannels + j))) {
vcin_valid[num_vchannels - j - 1] = 1;
in_valid[i] = 1;
}
}
if (in_valid[i] == 1) {
vcin_local =
nvhls::leading_ones<num_vchannels, NVUINTW(num_vchannels),
NVUINTW(log_num_vchannels)>(vcin_valid);
vcin[i] = num_vchannels - vcin_local - 1;
}
} else {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) {
vcin[i] = 0;
if (!this->ififo.isEmpty(i)) {
in_valid[i] = 1;
}
}
}
}
}
void compute_route(Flit_t flit_in[num_ports],
NVUINTW(log_num_vchannels) vcin[num_ports],
NVUINTW(num_ports) in_valid) {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the inputs here
if (in_valid[i]) {
// Route Computation: For source routing just copy from header flit
if (flit_in[i].flit_id.isHeader()) {
NVUINTW(dest_width)
route = nvhls::get_slc<dest_width>(flit_in[i].data, 0);
NVUINTW(dest_width_per_hop)
out_dest_local = nvhls::get_slc<dest_width_per_hop>(route, 0);
NVUINTW(dest_width) next_dests_local = route >> dest_width_per_hop;
flit_in[i].data =
nvhls::set_slc(flit_in[i].data, next_dests_local, 0);
NVUINTW(num_lports)
ldest = nvhls::get_slc<num_lports>(out_dest_local, 0);
NVUINTW(log_num_rports)
rdest = nvhls::get_slc<log_num_rports>(out_dest_local, num_lports);
NVUINTW(num_rports) rdest_1hot = 0;
if (next_dests_local != 0) {
rdest_1hot[rdest] = 1;
}
out_dest[i][vcin[i]] =
(static_cast<NVUINTW(num_ports)>(rdest_1hot) << num_lports) |
ldest;
}
}
}
}
void flit_output(bool is_push[num_ports],
NVUINTW(log_num_vchannels) vcout[num_ports]) {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating over outputs here
if (is_push[i] == true || out_stall[i] == 1) {
bool temp = this->out_port[i].PushNB(this->flit_out[i]);
if (this->flit_out[i].flit_id.isTail()) {
is_get_new_packet[i * num_vchannels + vcout[i]] = true;
} else {
is_get_new_packet[i * num_vchannels + vcout[i]] = false;
}
if (temp == 0)
out_stall[i] = 1;
else {
out_stall[i] = 0;
this->credit_recv[i * num_vchannels + vcout[i]]--;
}
DCOUT(sc_time_stamp()
<< ": " << this->name() << " OutPort " << i
<< " Push success??: " << temp << " Decrementing Credit status "
<< i * num_vchannels + vcout[i] << ": "
<< this->credit_recv[i * num_vchannels + vcout[i]]
<< " [Router] Out_stall: " << out_stall[i] << endl);
}
}
}
void arbitration(Flit_t flit_in[num_ports], NVUINTW(num_ports) in_valid,
NVUINTW(log_num_vchannels) vcin[num_ports],
NVUINTW(num_ports) valid[num_ports],
NVUINTW(num_ports) select[num_ports],
NVUINTW(log_num_ports) select_id[num_ports]) {
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the outputs here
valid[i] = 0; // valid of ith output is set to 0 here
}
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the inputs here
if (in_valid[i]) {
bool not_head_flit = (!flit_in[i].flit_id.isHeader());
#pragma hls_unroll yes
for (int k = 0; k < num_ports;
k++) { // Iterating through the outputs here
int out_idx = k * num_vchannels + vcin[i];
// Set valid bit to 1 for local ports only if credits are available at
// the output port for the virtual channel chosen
// also make sure that the output is requested, and that it is not
// head flit, or output[vc] accepts new headers
valid[k][i] =
(((this->credit_recv[out_idx] != 0) && (out_dest[i][vcin[i]][k] == 1) &&
(is_get_new_packet[out_idx] || not_head_flit) &&
(out_stall[k] == 0))
? 1
: 0);
// DCOUT(sc_time_stamp() << ": " << name() << " Input Port:" << i << "
// Output port: " << k << " VC: " << vcin[i] << " valid: "<<
// valid[k][i] << " OutStall: " << out_stall[k] << " Credit: " <<
// credit_recv[out_idx] << " GetnewPacket: " <<
// is_get_new_packet[out_idx] << hex << " Flit " << " <" <<
// flit_in[i].flit_id << "," << flit_in[i].data.to_uint64() << dec <<
// ">" << endl);
}
}
}
#ifdef ENABLE_MULTICAST
// For Multicast, supress local output valid if remote output is invalid
NVUINTW((num_ports * num_vchannels))
is_multicast = 0; // Store if an input is unicast or multicast
NVUINTW(log_num_ports) remote_portid[num_ports];
NVUINTW(log_num_lports) local_portid[num_ports];
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the inputs here
#pragma hls_unroll yes
for (int l = 0; l < num_lports;
l++) { // Iterating through the outputs here
#pragma hls_unroll yes
for (int r = num_lports; r < num_ports; r++) {
if (out_dest[i][vcin[i]][l] && out_dest[i][vcin[i]][r]) {
is_multicast[i * num_vchannels + vcin[i]] = 1;
remote_portid[i] = r;
local_portid[i] = l;
if (!(valid[l][i] && valid[r][i])) {
valid[l][i] = 0;
valid[r][i] = 0; // valid of local port is 1 only is valid of
// remote port is 1
// DCOUT(sc_time_stamp() << ": " << name() << " Input Port:" << i
// << " Local port: " << l << " Remote port: " << r << " VC: " <<
// vcin[i] << " valid: "<< valid[l][i] << " Multicast: " <<
// is_multicast[i*num_vchannels + vcin[i]] << endl);
}
}
}
}
}
#endif
// Arbitrate for output port if it is header flit
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating through the outputs here
select[i] = 0;
if (valid[i] != 0) { // There is an input waiting to send to output
// i, credits are available at output
select[i] = arbiter[i].pick(valid[i]);
NVUINTW(num_ports) select_temp = select[i];
NVUINTW(log_num_ports) select_id_temp;
one_hot_to_bin<num_ports, log_num_ports>(select_temp, select_id_temp);
select_id[i] = select_id_temp;
// DCOUT(sc_time_stamp() << ": " << name() << hex << " Output Port:" <<
// i
// << " Valid: " << valid[i].to_uint64()
// << " Select : " << select[i].to_int64() << dec << "
// Multicast: " <<
// is_multicast[(select_id[i]*num_vchannels+vcin[select_id[i]])]
// << endl);
}
}
#ifdef ENABLE_MULTICAST
// For Multicast, set remote select = local select
#pragma hls_unroll yes
for (int i = 0; i < num_lports;
i++) { // Iterating through the remote outputs here
if (select[i] != 0 &&
is_multicast[(select_id[i] * num_vchannels + vcin[select_id[i]])] &&
valid[remote_portid[select_id[i]]][select_id[i]]) {
select[remote_portid[select_id[i]]] = select[i];
select_id[remote_portid[select_id[i]]] = select_id[i];
// DCOUT(sc_time_stamp() << ": " << name() << " Output Port:" << i << "
// Input port: " << select_id[i] << " Remote port: " <<
// remote_portid[select_id[i]] << " VC: " << vcin[select_id[i]] << "
// Remote Select: " << select[remote_portid[select_id[i]]] << " Local
// Select: " << select[i] << endl);
}
}
// For Multicast, if remote port is selected and not local port, reset remote
// port
#pragma hls_unroll yes
for (int i = num_lports; i < num_ports;
i++) { // Iterating through the remote outputs here
if (select[i] != 0 &&
is_multicast[(select_id[i] * num_vchannels + vcin[select_id[i]])] &&
(valid[i][select_id[local_portid[select_id[i]]]] == 0)) {
select[i] = 0;
// DCOUT("Set Select = 0 for Output port: " << i << endl);
// DCOUT(sc_time_stamp() << ": " << name() << " Output Port:" << i << "
// Input port: " << select_id[i] << " Remote port: " <<
// remote_portid[select_id[i]] << " VC: " << vcin[select_id[i]] << "
// Remote Select: " << select[i] << " Local Select: " <<
// select[local_portid[select_id[i]]] << endl);
}
}
#endif
}
void reset() {
out_stall = 0;
for (int i = 0; i < num_ports * num_vchannels; i++) {
is_get_new_packet[i] = true;
}
}
void run() {
this->receive_credit();
this->fill_ififo();
Flit_t flit_in[num_ports];
NVUINTW(log_num_vchannels) vcin[num_ports];
NVUINTW(num_ports) in_valid = 0;
// pick a valid vc per input. VC0 has priority.
// output: vcin[x] - vc selcted for in port x, in_valid - bitmap of
// inports valid bits
inputvc_arbiter(vcin, in_valid);
// read top flit for each selected vc per in port
// output: flit_in[x] - top flit on selected vc on port x
this->peek_ififo(flit_in, vcin, in_valid);
// for each selected input, in case of valid header flit only, update
// out_dest[i][vcin[i]]
// side effect updating out_dest[x][vc] for each input port x with output
// port bitmap
compute_route(flit_in, vcin, in_valid);
// Variable to hold valid input requests. Set valid[i][j] = 1 if input j
// is sending flit to output i
NVUINTW(num_ports) valid[num_ports], select[num_ports];
NVUINTW(log_num_ports) select_id[num_ports];
// arbitrate for any top header flits on selected vcs
// outputs:
// valid[x] - bitmap of valid input ports to address output port x. valid
// means there is credit on output port(and vc), and no other packet in
// flight to that output vc
// select[x] - bitmap of selected input port (one hot) for output port x
// select_id[x] - selected input port for output port x
arbitration(flit_in, in_valid, vcin, valid, select, select_id);
// decide which port is going to push data out
// side effect updating is_push[x] to indicate that output port x is going
// to push a flit out
NVUINTW(num_ports) is_popfifo = 0;
bool is_push[num_ports];
#pragma hls_unroll yes
for (int i = 0; i < num_ports;
i++) { // Iterating through output ports here
is_push[i] = false;
if (select[i] != 0) {
is_popfifo[select_id[i]] = 1;
is_push[i] = true;
// DCOUT(sc_time_stamp() << ": " << name() << " Port:" << i << "
// Select: "
// << select[i] << " select_id " << select_id[i]
// << " Valid:" << valid[i] << "PopFifo: " <<
// is_popfifo[select_id[i]] << endl);
}
}
// pop input fifos and prepare credits to be returned to sources
#pragma hls_unroll yes
for (int i = 0; i < num_ports; i++) { // Iterating over inputs here
if (is_popfifo[i] == 1) {
this->ififo.incrHead(i * num_vchannels + vcin[i]);
// DCOUT(sc_time_stamp() << ": " << name() << " Popped FIFO of port-"
// << i
// << " VC-" << vcin[i] << endl);
this->credit_send[i * num_vchannels + vcin[i]]++;
NVHLS_ASSERT_MSG(this->credit_send[i * num_vchannels + vcin[i]] <= BaseClass::buffersize, "Total credits cannot be larger than buffer size");
}
}
// fill_ififo();
this->send_credit();
NVUINTW(log_num_vchannels) vcout[num_ports];
this->crossbar_traversal(flit_in, is_push, select_id, vcin, vcout);
// sends out flits to be sent
// side effect: updating is_get_new_packet[x] when tail goes through port
// x
// and out_stall when push_nb fails
flit_output(is_push, vcout);
}
};
#endif //__WHVCROUTER_H__
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This test insures that google/protobuf/descriptor.pb.{h,cc} match exactly
// what would be generated by the protocol compiler. These files are not
// generated automatically at build time because they are compiled into the
// protocol compiler itself. So, if they were auto-generated, you'd have a
// chicken-and-egg problem.
//
// If this test fails, run the script
// "generate_descriptor_proto.sh" and add
// descriptor.pb.{h,cc} to your changelist.
#include <map>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
class MockErrorCollector : public MultiFileErrorCollector {
public:
MockErrorCollector() {}
~MockErrorCollector() {}
string text_;
// implements ErrorCollector ---------------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
};
class MockGeneratorContext : public GeneratorContext {
public:
MockGeneratorContext() {}
~MockGeneratorContext() {
STLDeleteValues(&files_);
}
void ExpectFileMatches(const string& virtual_filename,
const string& physical_filename) {
string* expected_contents = FindPtrOrNull(files_, virtual_filename);
ASSERT_TRUE(expected_contents != NULL)
<< "Generator failed to generate file: " << virtual_filename;
string actual_contents;
GOOGLE_CHECK_OK(
File::GetContents(TestSourceDir() + "/" + physical_filename,
&actual_contents, true));
EXPECT_TRUE(actual_contents == *expected_contents)
<< physical_filename << " needs to be regenerated. Please run "
"generate_descriptor_proto.sh and add this file "
"to your CL.";
}
// implements GeneratorContext --------------------------------------
virtual io::ZeroCopyOutputStream* Open(const string& filename) {
string** map_slot = &files_[filename];
if (*map_slot != NULL) delete *map_slot;
*map_slot = new string;
return new io::StringOutputStream(*map_slot);
}
private:
map<string, string*> files_;
};
TEST(BootstrapTest, GeneratedDescriptorMatches) {
MockErrorCollector error_collector;
DiskSourceTree source_tree;
source_tree.MapPath("", TestSourceDir());
Importer importer(&source_tree, &error_collector);
const FileDescriptor* proto_file =
importer.Import("google/protobuf/descriptor.proto");
const FileDescriptor* plugin_proto_file =
importer.Import("google/protobuf/compiler/plugin.proto");
EXPECT_EQ("", error_collector.text_);
ASSERT_TRUE(proto_file != NULL);
ASSERT_TRUE(plugin_proto_file != NULL);
CppGenerator generator;
MockGeneratorContext context;
string error;
string parameter;
parameter = "dllexport_decl=LIBPROTOBUF_EXPORT";
ASSERT_TRUE(generator.Generate(proto_file, parameter,
&context, &error));
parameter = "dllexport_decl=LIBPROTOC_EXPORT";
ASSERT_TRUE(generator.Generate(plugin_proto_file, parameter,
&context, &error));
context.ExpectFileMatches("google/protobuf/descriptor.pb.h",
"google/protobuf/descriptor.pb.h");
context.ExpectFileMatches("google/protobuf/descriptor.pb.cc",
"google/protobuf/descriptor.pb.cc");
context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.h",
"google/protobuf/compiler/plugin.pb.h");
context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.cc",
"google/protobuf/compiler/plugin.pb.cc");
}
} // namespace
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
| {
"pile_set_name": "Github"
} |
<map id="TMC2209Stepper::semax" name="TMC2209Stepper::semax">
<area shape="rect" id="node1" title=" " alt="" coords="223,5,392,32"/>
<area shape="rect" id="node2" href="$class_t_m_c2209_stepper.html#aac6c2ffdb7ef1c6045f2e80e6224e076" title=" " alt="" coords="5,5,175,32"/>
</map>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software donated to Berkeley by
* Jan-Simon Pendry.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)null_subr.c 8.7 (Berkeley) 5/14/95
*
* $Id: lofs_subr.c,v 1.11 1992/05/30 10:05:43 jsp Exp jsp $
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <sys/namei.h>
#include <sys/malloc.h>
#include <miscfs/nullfs/null.h>
#define LOG2_SIZEVNODE 7 /* log2(sizeof struct vnode) */
#define NNULLNODECACHE 16
/*
* Null layer cache:
* Each cache entry holds a reference to the lower vnode
* along with a pointer to the alias vnode. When an
* entry is added the lower vnode is VREF'd. When the
* alias is removed the lower vnode is vrele'd.
*/
#define NULL_NHASH(vp) \
(&null_node_hashtbl[(((u_long)vp)>>LOG2_SIZEVNODE) & null_node_hash])
LIST_HEAD(null_node_hashhead, null_node) *null_node_hashtbl;
u_long null_node_hash;
/*
* Initialise cache headers
*/
nullfs_init()
{
#ifdef NULLFS_DIAGNOSTIC
printf("nullfs_init\n"); /* printed during system boot */
#endif
null_node_hashtbl = hashinit(NNULLNODECACHE, M_CACHE, &null_node_hash);
}
/*
* Return a VREF'ed alias for lower vnode if already exists, else 0.
*/
static struct vnode *
null_node_find(mp, lowervp)
struct mount *mp;
struct vnode *lowervp;
{
struct proc *p = curproc; /* XXX */
struct null_node_hashhead *hd;
struct null_node *a;
struct vnode *vp;
/*
* Find hash base, and then search the (two-way) linked
* list looking for a null_node structure which is referencing
* the lower vnode. If found, the increment the null_node
* reference count (but NOT the lower vnode's VREF counter).
*/
hd = NULL_NHASH(lowervp);
loop:
for (a = hd->lh_first; a != 0; a = a->null_hash.le_next) {
if (a->null_lowervp == lowervp && NULLTOV(a)->v_mount == mp) {
vp = NULLTOV(a);
/*
* We need vget for the VXLOCK
* stuff, but we don't want to lock
* the lower node.
*/
if (vget(vp, 0, p)) {
printf ("null_node_find: vget failed.\n");
goto loop;
};
return (vp);
}
}
return NULL;
}
/*
* Make a new null_node node.
* Vp is the alias vnode, lofsvp is the lower vnode.
* Maintain a reference to (lowervp).
*/
static int
null_node_alloc(mp, lowervp, vpp)
struct mount *mp;
struct vnode *lowervp;
struct vnode **vpp;
{
struct null_node_hashhead *hd;
struct null_node *xp;
struct vnode *othervp, *vp;
int error;
if (error = getnewvnode(VT_NULL, mp, null_vnodeop_p, vpp))
return (error);
vp = *vpp;
MALLOC(xp, struct null_node *, sizeof(struct null_node), M_TEMP, M_WAITOK);
vp->v_type = lowervp->v_type;
xp->null_vnode = vp;
vp->v_data = xp;
xp->null_lowervp = lowervp;
/*
* Before we insert our new node onto the hash chains,
* check to see if someone else has beaten us to it.
* (We could have slept in MALLOC.)
*/
if (othervp = null_node_find(lowervp)) {
FREE(xp, M_TEMP);
vp->v_type = VBAD; /* node is discarded */
vp->v_usecount = 0; /* XXX */
*vpp = othervp;
return 0;
};
VREF(lowervp); /* Extra VREF will be vrele'd in null_node_create */
hd = NULL_NHASH(lowervp);
LIST_INSERT_HEAD(hd, xp, null_hash);
return 0;
}
/*
* Try to find an existing null_node vnode refering
* to it, otherwise make a new null_node vnode which
* contains a reference to the lower vnode.
*/
int
null_node_create(mp, lowervp, newvpp)
struct mount *mp;
struct vnode *lowervp;
struct vnode **newvpp;
{
struct vnode *aliasvp;
if (aliasvp = null_node_find(mp, lowervp)) {
/*
* null_node_find has taken another reference
* to the alias vnode.
*/
#ifdef NULLFS_DIAGNOSTIC
vprint("null_node_create: exists", NULLTOV(ap));
#endif
/* VREF(aliasvp); --- done in null_node_find */
} else {
int error;
/*
* Get new vnode.
*/
#ifdef NULLFS_DIAGNOSTIC
printf("null_node_create: create new alias vnode\n");
#endif
/*
* Make new vnode reference the null_node.
*/
if (error = null_node_alloc(mp, lowervp, &aliasvp))
return error;
/*
* aliasvp is already VREF'd by getnewvnode()
*/
}
vrele(lowervp);
#ifdef DIAGNOSTIC
if (lowervp->v_usecount < 1) {
/* Should never happen... */
vprint ("null_node_create: alias ", aliasvp);
vprint ("null_node_create: lower ", lowervp);
panic ("null_node_create: lower has 0 usecount.");
};
#endif
#ifdef NULLFS_DIAGNOSTIC
vprint("null_node_create: alias", aliasvp);
vprint("null_node_create: lower", lowervp);
#endif
*newvpp = aliasvp;
return (0);
}
#ifdef NULLFS_DIAGNOSTIC
struct vnode *
null_checkvp(vp, fil, lno)
struct vnode *vp;
char *fil;
int lno;
{
struct null_node *a = VTONULL(vp);
#ifdef notyet
/*
* Can't do this check because vop_reclaim runs
* with a funny vop vector.
*/
if (vp->v_op != null_vnodeop_p) {
printf ("null_checkvp: on non-null-node\n");
while (null_checkvp_barrier) /*WAIT*/ ;
panic("null_checkvp");
};
#endif
if (a->null_lowervp == NULL) {
/* Should never happen */
int i; u_long *p;
printf("vp = %x, ZERO ptr\n", vp);
for (p = (u_long *) a, i = 0; i < 8; i++)
printf(" %x", p[i]);
printf("\n");
/* wait for debugger */
while (null_checkvp_barrier) /*WAIT*/ ;
panic("null_checkvp");
}
if (a->null_lowervp->v_usecount < 1) {
int i; u_long *p;
printf("vp = %x, unref'ed lowervp\n", vp);
for (p = (u_long *) a, i = 0; i < 8; i++)
printf(" %x", p[i]);
printf("\n");
/* wait for debugger */
while (null_checkvp_barrier) /*WAIT*/ ;
panic ("null with unref'ed lowervp");
};
#ifdef notyet
printf("null %x/%d -> %x/%d [%s, %d]\n",
NULLTOV(a), NULLTOV(a)->v_usecount,
a->null_lowervp, a->null_lowervp->v_usecount,
fil, lno);
#endif
return a->null_lowervp;
}
#endif
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.