code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
defaultEquals = function(a, b) {
return a[0] === b[0] && a[1] === b[1];
}
|
A* search function.
This function expects a `Map` implementation and the origin and destination
points given. If there is a path between the two it will return the optimal
path as a linked list. If there is no path it will return null.
The linked list is in reverse order: the first item is the destination and
the path to the origin follows.
@param {Map} map map instance, must follow interface defined in {Map}
@param {Array} origin
@param {Array} destination
@param {Number} timeout milliseconds after which search should be canceled
@returns {Object} the linked list leading from `to` to `from` (sic!).
|
defaultEquals
|
javascript
|
GameJs/gamejs
|
src/gamejs/pathfinding.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/pathfinding.js
|
MIT
|
defaultHash = function(a) {
return a[0] + '-' + a[1];
}
|
A* search function.
This function expects a `Map` implementation and the origin and destination
points given. If there is a path between the two it will return the optimal
path as a linked list. If there is no path it will return null.
The linked list is in reverse order: the first item is the destination and
the path to the origin follows.
@param {Map} map map instance, must follow interface defined in {Map}
@param {Array} origin
@param {Array} destination
@param {Number} timeout milliseconds after which search should be canceled
@returns {Object} the linked list leading from `to` to `from` (sic!).
|
defaultHash
|
javascript
|
GameJs/gamejs
|
src/gamejs/pathfinding.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/pathfinding.js
|
MIT
|
workerPrefix = function workerPrefix() {
__scripts.forEach(function(script) {
try {
importScripts(script);
} catch (e) {
// can't help the worker
}
});
}
|
executed in scope of worker before user's main module
@ignore
|
workerPrefix
|
javascript
|
GameJs/gamejs
|
src/gamejs/thread.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/thread.js
|
MIT
|
create = function(workerModuleId) {
var moduleRoot = uri.resolve(document.location.href, window.require.getModuleRoot());
var initialScripts = [];
Array.prototype.slice.apply(document.getElementsByTagName('script'), [0]).forEach(function(script) {
if (script.src) {
initialScripts.push(script.src);
}
});
var URL = window.URL || window.webkitURL;
var prefixString = workerPrefix.toString();
// don't be afraid...
prefixString = prefixString.substring(prefixString.indexOf("{") + 1, prefixString.lastIndexOf("}"));
var blob = new Blob([
'var __scripts = ["' + initialScripts.join('","') + '"];',
prefixString,
';self.require.setModuleRoot("' + moduleRoot + '");',
'self.require.run("'+ workerModuleId +'");'
], {type: 'application\/javascript'});
var blobURL = URL.createObjectURL(blob);
return new Worker(blobURL);
}
|
Setup a worker which has `require()` defined
@ignore
|
create
|
javascript
|
GameJs/gamejs
|
src/gamejs/thread.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/thread.js
|
MIT
|
function triggerCallbacks(callbacks, event) {
callbacks.forEach(function(c) {
c.trigger(event);
});
}
|
Unique id of this worker
@property {Number}
|
triggerCallbacks
|
javascript
|
GameJs/gamejs
|
src/gamejs/thread.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/thread.js
|
MIT
|
loadTileSet = function(tileSetNode) {
var tiles = [];
var tileWidth = tileSetNode.attribute('tilewidth');
var tileHeight = tileSetNode.attribute('tileheight');
var spacing = tileSetNode.attribute('spacing') || 0;
// broken in tiled?
var margin = 0;
var imageNode = tileSetNode.element('image');
var imageAtlasFile = imageNode.attribute('source');
var imageUrl = uri.makeRelative(uri.resolve(mapUrl, imageAtlasFile));
var atlas = gamejs.image.load(imageUrl);
// FIXME set transparency if imageNode.attribute('trans') is set
var tileNodes = tileSetNode.elements('tile');
var dims = atlas.getSize();
var imgSize = new gamejs.Rect([0,0], [tileWidth, tileHeight]);
var idx = 0;
var y = 0;
while (y + tileHeight <= dims[1]) {
var x = 0;
while (x + tileWidth <= dims[0]) {
var tileImage = new gamejs.graphics.Surface(tileWidth, tileHeight);
var rect = new gamejs.Rect([x, y], [tileWidth, tileHeight]);
tileImage.blit(atlas, imgSize, rect);
var tileProperties = {};
/* jshint ignore:start */
// function within loop
tileNodes.some(function(tileNode) {
if (tileNode.attribute('id') === idx) {
setProperties(tileProperties, tileNode);
return true;
}
}, this);
/* jshint ignore:end */
tiles.push({
surface: tileImage,
properties: tileProperties
});
x += tileWidth + spacing;
idx++;
}
y += tileHeight + spacing;
}
return tiles;
}
|
@param {Number} gid global tile id
@returns {Object} the Tile object for this gid
|
loadTileSet
|
javascript
|
GameJs/gamejs
|
src/gamejs/tiledmap.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/tiledmap.js
|
MIT
|
setProperties = function(object, node) {
var props = node.element('properties');
if (!props) {
return;
}
props.elements('property').forEach(function(propertyNode) {
var name = propertyNode.attribute('name');
var value = propertyNode.attribute('value');
object[name] = value;
});
return object;
}
|
set generic <properties><property name="" value="">... on given object
|
setProperties
|
javascript
|
GameJs/gamejs
|
src/gamejs/tiledmap.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/tiledmap.js
|
MIT
|
removeDotSegments = function(path) {
if (path == '..' || path == '.') {
return '';
}
var leadingSlash = path.indexOf('/') > -1;
var segments = path.split('/');
var out = [];
var pos;
for (pos = 0; pos < segments.length; ) {
var segment = segments[pos++];
if (segment == '.') {
if (leadingSlash && pos == segments.length) {
out.push('');
}
} else if (segment == '..') {
if (out.length > 1 || out.length !== 1 && out[0] !== '') {
out.pop();
}
if (leadingSlash && pos == segments.length) {
out.push('');
}
} else {
out.push(segment);
leadingSlash = true;
}
}
return out.join('/');
}
|
Removes dot segments in given path component
|
removeDotSegments
|
javascript
|
GameJs/gamejs
|
src/gamejs/utils/uri.js
|
https://github.com/GameJs/gamejs/blob/master/src/gamejs/utils/uri.js
|
MIT
|
function insideMap(point) {
return point[0] >= 0 && point[0] < HEIGHT_FIELD.length &&
point[1] >= 0 && point[1] < HEIGHT_FIELD.length;
}
|
This is an example implementation of a Map that can be passed to the `astar.findRoute()`
function.
|
insideMap
|
javascript
|
GameJs/gamejs
|
tests/pathfinding.js
|
https://github.com/GameJs/gamejs/blob/master/tests/pathfinding.js
|
MIT
|
function heightAt(point) {
return HEIGHT_FIELD[point[1]][point[0]];
}
|
This is an example implementation of a Map that can be passed to the `astar.findRoute()`
function.
|
heightAt
|
javascript
|
GameJs/gamejs
|
tests/pathfinding.js
|
https://github.com/GameJs/gamejs/blob/master/tests/pathfinding.js
|
MIT
|
errorString = function( error ) {
var name, message,
errorString = error.toString();
if ( errorString.substring( 0, 7 ) === "[object" ) {
name = error.name ? error.name.toString() : "Error";
message = error.message ? error.message.toString() : "";
if ( name && message ) {
return name + ": " + message;
} else if ( name ) {
return name;
} else if ( message ) {
return message;
} else {
return "Error";
}
} else {
return errorString;
}
}
|
Provides a normalized error string, correcting an issue
with IE 7 (and prior) where Error.prototype.toString is
not properly implemented
Based on http://es5.github.com/#x15.11.4.4
@param {String|Error} error
@return {String} error message
|
errorString
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
objectValues = function( obj ) {
// Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392.
/*jshint newcap: false */
var key, val,
vals = QUnit.is( "array", obj ) ? [] : {};
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
val = obj[key];
vals[key] = val === Object(val) ? objectValues(val) : val;
}
}
return vals;
}
|
Makes a clone of an object using only Array or Object as base,
and copies over the own enumerable properties.
@param {Object} obj
@return {Object} New object with only the own properties (recursively).
|
objectValues
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function Test( settings ) {
extend( this, settings );
this.assertions = [];
this.testNumber = ++Test.count;
}
|
Makes a clone of an object using only Array or Object as base,
and copies over the own enumerable properties.
@param {Object} obj
@return {Object} New object with only the own properties (recursively).
|
Test
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
|
Makes a clone of an object using only Array or Object as base,
and copies over the own enumerable properties.
@param {Object} obj
@return {Object} New object with only the own properties (recursively).
|
run
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function validTest( test ) {
var include,
filter = config.filter && config.filter.toLowerCase(),
module = config.module && config.module.toLowerCase(),
fullName = (test.module + ": " + test.testName).toLowerCase();
// Internally-generated tests are always valid
if ( test.callback && test.callback.validTest === validTest ) {
delete test.callback.validTest;
return true;
}
if ( config.testNumber ) {
return test.testNumber === config.testNumber;
}
if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) {
return false;
}
if ( !filter ) {
return true;
}
include = filter.charAt( 0 ) !== "!";
if ( !include ) {
filter = filter.slice( 1 );
}
// If the filter matches, we need to honour include
if ( fullName.indexOf( filter ) !== -1 ) {
return include;
}
// Otherwise, do the opposite
return !include;
}
|
@return Boolean: true if this test should be ran
|
validTest
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function extractStacktrace( e, offset ) {
offset = offset === undefined ? 3 : offset;
var stack, include, i;
if ( e.stacktrace ) {
// Opera
return e.stacktrace.split( "\n" )[ offset + 3 ];
} else if ( e.stack ) {
// Firefox, Chrome
stack = e.stack.split( "\n" );
if (/^error$/i.test( stack[0] ) ) {
stack.shift();
}
if ( fileName ) {
include = [];
for ( i = offset; i < stack.length; i++ ) {
if ( stack[ i ].indexOf( fileName ) !== -1 ) {
break;
}
include.push( stack[ i ] );
}
if ( include.length ) {
return include.join( "\n" );
}
}
return stack[ offset ];
} else if ( e.sourceURL ) {
// Safari, PhantomJS
// hopefully one day Safari provides actual stacktraces
// exclude useless self-reference for generated Error objects
if ( /qunit.js$/.test( e.sourceURL ) ) {
return;
}
// for actual exceptions, this is useful
return e.sourceURL + ":" + e.line;
}
}
|
@return Boolean: true if this test should be ran
|
extractStacktrace
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function sourceFromStacktrace( offset ) {
try {
throw new Error();
} catch ( e ) {
return extractStacktrace( e, offset );
}
}
|
@return Boolean: true if this test should be ran
|
sourceFromStacktrace
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function escapeText( s ) {
if ( !s ) {
return "";
}
s = s + "";
// Both single quotes and double quotes (for attributes)
return s.replace( /['"<>&]/g, function( s ) {
switch( s ) {
case '\'':
return ''';
case '"':
return '"';
case '<':
return '<';
case '>':
return '>';
case '&':
return '&';
}
});
}
|
Escape text for attribute or text content.
|
escapeText
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process( last );
}
}
|
Escape text for attribute or text content.
|
synchronize
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function process( last ) {
function next() {
process( last );
}
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
window.setTimeout( next, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
|
Escape text for attribute or text content.
|
process
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function next() {
process( last );
}
|
Escape text for attribute or text content.
|
next
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
// in Opera sometimes DOM element ids show up here, ignore them
if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
|
Escape text for attribute or text content.
|
saveGlobal
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function checkPollution() {
var newGlobals,
deletedGlobals,
old = config.pollution;
saveGlobal();
newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
}
deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
|
Escape text for attribute or text content.
|
checkPollution
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function diff( a, b ) {
var i, j,
result = a.slice();
for ( i = 0; i < result.length; i++ ) {
for ( j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice( i, 1 );
i--;
break;
}
}
}
return result;
}
|
Escape text for attribute or text content.
|
diff
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function extend( a, b ) {
for ( var prop in b ) {
if ( b[ prop ] === undefined ) {
delete a[ prop ];
// Avoid "Member not found" error in IE8 caused by setting window.constructor
} else if ( prop !== "constructor" || a !== window ) {
a[ prop ] = b[ prop ];
}
}
return a;
}
|
Escape text for attribute or text content.
|
extend
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function addEvent( elem, type, fn ) {
// Standards-based browsers
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
// IE
} else {
elem.attachEvent( "on" + type, fn );
}
}
|
@param {HTMLElement} elem
@param {string} type
@param {Function} fn
|
addEvent
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function addEvents( elems, type, fn ) {
var i = elems.length;
while ( i-- ) {
addEvent( elems[i], type, fn );
}
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
addEvents
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function hasClass( elem, name ) {
return (" " + elem.className + " ").indexOf(" " + name + " ") > -1;
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
hasClass
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function addClass( elem, name ) {
if ( !hasClass( elem, name ) ) {
elem.className += (elem.className ? " " : "") + name;
}
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
addClass
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function removeClass( elem, name ) {
var set = " " + elem.className + " ";
// Class name may appear multiple times
while ( set.indexOf(" " + name + " ") > -1 ) {
set = set.replace(" " + name + " " , " ");
}
// If possible, trim it for prettiness, but not neccecarily
elem.className = window.jQuery ? jQuery.trim( set ) : ( set.trim ? set.trim() : set );
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
removeClass
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function id( name ) {
return !!( typeof document !== "undefined" && document && document.getElementById ) &&
document.getElementById( name );
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
id
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function registerLoggingCallback( key ) {
return function( callback ) {
config[key].push( callback );
};
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
registerLoggingCallback
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function runLoggingCallbacks( key, scope, args ) {
var i, callbacks;
if ( QUnit.hasOwnProperty( key ) ) {
QUnit[ key ].call(scope, args );
} else {
callbacks = config[ key ];
for ( i = 0; i < callbacks.length; i++ ) {
callbacks[ i ].call( scope, args );
}
}
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
runLoggingCallbacks
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function bindCallbacks( o, callbacks, args ) {
var prop = QUnit.objectType( o );
if ( prop ) {
if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
return callbacks[ prop ].apply( callbacks, args );
} else {
return callbacks[ prop ]; // or undefined
}
}
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
bindCallbacks
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function useStrictEquality( b, a ) {
/*jshint eqeqeq:false */
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;
}
}
|
@param {Array|NodeList} elems
@param {string} type
@param {Function} fn
|
useStrictEquality
|
javascript
|
GameJs/gamejs
|
utils/qunit/qunit.js
|
https://github.com/GameJs/gamejs/blob/master/utils/qunit/qunit.js
|
MIT
|
function errorFormatter (err, ctx) {
const response = mercurius.defaultErrorFormatter(err, ctx)
response.statusCode = 200
return response
}
|
Define error formatter so we always return 200 OK
|
errorFormatter
|
javascript
|
mercurius-js/mercurius
|
examples/custom-http-behaviour.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/custom-http-behaviour.js
|
MIT
|
constructor () {
super()
this.sampleData = []
}
|
A data manager to collect the data.
|
constructor
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
getSampleData () {
return this.sampleData
}
|
A data manager to collect the data.
|
getSampleData
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
setSampleData (sampleData) {
this.sampleData = sampleData || []
this.dispatchEvent(new Event('updateSampleData'))
}
|
A data manager to collect the data.
|
setSampleData
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
useSampleData = () => {
const [sampleData, setSampleData] = React.useState(
sampleDataManager.getSampleData()
)
React.useEffect(() => {
const eventListener = sampleDataManager.addEventListener(
'updateSampleData',
(e, value) => {
setSampleData(_ => e.target.sampleData || [])
}
)
return () => {
sampleDataManager.removeEventListener('updateSampleData', eventListener)
}
}, [])
return {
sampleData
}
}
|
A data manager to collect the data.
|
useSampleData
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
useSampleData = () => {
const [sampleData, setSampleData] = React.useState(
sampleDataManager.getSampleData()
)
React.useEffect(() => {
const eventListener = sampleDataManager.addEventListener(
'updateSampleData',
(e, value) => {
setSampleData(_ => e.target.sampleData || [])
}
)
return () => {
sampleDataManager.removeEventListener('updateSampleData', eventListener)
}
}, [])
return {
sampleData
}
}
|
A data manager to collect the data.
|
useSampleData
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
function Content () {
const { sampleData } = useSampleData()
return (
React__default.default.createElement('div', { style: { maxWidth: '300px' } }, [
React__default.default.createElement('div', { style: { height: '100%' } }, ['This is a sample plugin']),
sampleData && React__default.default.createElement('pre', null, [JSON.stringify(sampleData, null, 2)])
])
)
}
|
A data manager to collect the data.
|
Content
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
function Icon () {
return React__default.default.createElement('p', null, ['GE'])
}
|
A data manager to collect the data.
|
Icon
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
function graphiqlSamplePlugin (props) {
return {
title: props.title || 'GraphiQL Sample',
icon: () => Icon(),
content: () => {
return Content()
}
}
}
|
A data manager to collect the data.
|
graphiqlSamplePlugin
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
function umdPlugin (props) {
return graphiqlSamplePlugin(props)
}
|
A data manager to collect the data.
|
umdPlugin
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
function parseFetchResponse (data) {
if (data.data) {
sampleDataManager.setSampleData(data.data)
}
return data
}
|
Intercept and store the data fetched by GQL in the DataManager.
|
parseFetchResponse
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin/samplePlugin.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin/samplePlugin.js
|
MIT
|
constructor () {
super()
this.sampleData = []
}
|
A data manager to collect the data.
|
constructor
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin-sources/src/sampleDataManager.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin-sources/src/sampleDataManager.js
|
MIT
|
getSampleData () {
return this.sampleData
}
|
A data manager to collect the data.
|
getSampleData
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin-sources/src/sampleDataManager.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin-sources/src/sampleDataManager.js
|
MIT
|
setSampleData (sampleData) {
this.sampleData = sampleData || []
this.dispatchEvent(new Event('updateSampleData'))
}
|
A data manager to collect the data.
|
setSampleData
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin-sources/src/sampleDataManager.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin-sources/src/sampleDataManager.js
|
MIT
|
function parseFetchResponse (data) {
if (data.data) {
sampleDataManager.setSampleData(data.data)
}
return data
}
|
Intercept and store the data fetched by GQL in the DataManager.
|
parseFetchResponse
|
javascript
|
mercurius-js/mercurius
|
examples/graphiql-plugin/plugin-sources/src/utils.js
|
https://github.com/mercurius-js/mercurius/blob/master/examples/graphiql-plugin/plugin-sources/src/utils.js
|
MIT
|
function isDuplicatedUrlArg (baseUrl) {
const checker = window.GRAPHQL_ENDPOINT.split('/')
return (checker[1] === baseUrl)
}
|
Verify if the baseUrl is already present in the first part of GRAPHQL_ENDPOINT url
to avoid unexpected duplication of paths
@param {string} baseUrl [comes from {@link render} function]
@returns boolean
|
isDuplicatedUrlArg
|
javascript
|
mercurius-js/mercurius
|
static/main.js
|
https://github.com/mercurius-js/mercurius/blob/master/static/main.js
|
MIT
|
function render () {
const host = window.location.host
const websocketProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
let url = ''
let subscriptionUrl = ''
let pathName = window.location.pathname
if (pathName.startsWith('/')) {
pathName = pathName.substring(1)
}
pathName = pathName.split('/')
const baseUrl = pathName[0]
if (baseUrl !== 'graphiql') {
url = `${window.location.protocol}//${host}/${baseUrl}${window.GRAPHQL_ENDPOINT}`
subscriptionUrl = `${websocketProtocol}//${host}/${baseUrl}${window.GRAPHQL_ENDPOINT}`
if (isDuplicatedUrlArg(baseUrl)) {
url = `${window.location.protocol}//${host}${window.GRAPHQL_ENDPOINT}`
subscriptionUrl = `${websocketProtocol}//${host}${window.GRAPHQL_ENDPOINT}`
}
} else {
url = `${window.location.protocol}//${host}${window.GRAPHQL_ENDPOINT}`
subscriptionUrl = `${websocketProtocol}//${host}${window.GRAPHQL_ENDPOINT}`
}
const availablePlugins = window.GRAPHIQL_PLUGIN_LIST
.map(plugin => window[`GRAPIHQL_PLUGIN_${plugin.toUpperCase()}`])
.filter(pluginData => pluginData && pluginData.umdUrl)
const fetcherWrapperPlugins = availablePlugins
.filter(plugin => plugin.fetcherWrapper)
.map(pluginData => window[pluginData.name][window[`GRAPIHQL_PLUGIN_${pluginData.name.toUpperCase()}`].fetcherWrapper])
const fetcher = fetcherWrapper(GraphiQL.createFetcher({
url,
subscriptionUrl
}), fetcherWrapperPlugins)
const plugins = availablePlugins.map(pluginData => window[pluginData.name].umdPlugin(window[`GRAPIHQL_PLUGIN_${pluginData.name.toUpperCase()}`].props))
ReactDOM.render(
React.createElement(GraphiQL, {
fetcher,
headerEditorEnabled: true,
shouldPersistHeaders: true,
plugins
}),
document.getElementById('main')
)
}
|
Verify if the baseUrl is already present in the first part of GRAPHQL_ENDPOINT url
to avoid unexpected duplication of paths
@param {string} baseUrl [comes from {@link render} function]
@returns boolean
|
render
|
javascript
|
mercurius-js/mercurius
|
static/main.js
|
https://github.com/mercurius-js/mercurius/blob/master/static/main.js
|
MIT
|
function importDependencies () {
const link = document.createElement('link')
link.href = 'https://unpkg.com/[email protected]/graphiql.min.css'
link.type = 'text/css'
link.rel = 'stylesheet'
link.media = 'screen,print'
link.crossOrigin = 'anonymous'
document.getElementsByTagName('head')[0].appendChild(link)
return importer.urls([
'https://unpkg.com/[email protected]/umd/react.production.min.js',
'https://unpkg.com/[email protected]/umd/react-dom.production.min.js',
'https://unpkg.com/[email protected]/graphiql.min.js'
]).then(function () {
const pluginUrls = window.GRAPHIQL_PLUGIN_LIST
.map(plugin => window[`GRAPIHQL_PLUGIN_${plugin.toUpperCase()}`].umdUrl)
.filter(url => !!url)
if (pluginUrls.length) {
return importer.urls(pluginUrls)
}
})
}
|
Verify if the baseUrl is already present in the first part of GRAPHQL_ENDPOINT url
to avoid unexpected duplication of paths
@param {string} baseUrl [comes from {@link render} function]
@returns boolean
|
importDependencies
|
javascript
|
mercurius-js/mercurius
|
static/main.js
|
https://github.com/mercurius-js/mercurius/blob/master/static/main.js
|
MIT
|
webpackProdConf = () => {
return {
mode: "production",
target: "web",
entry: Object.assign({
main: "./src/web/index.js"
}, moduleEntryPoints),
output: {
path: __dirname + "/build/prod",
filename: chunkData => {
return chunkData.chunk.name === "main" ? "assets/[name].js": "[name].js";
},
globalObject: "this"
},
resolve: {
alias: {
"./config/modules/OpModules.mjs": "./config/modules/Default.mjs"
}
},
plugins: [
new webpack.DefinePlugin(BUILD_CONSTANTS),
new HtmlWebpackPlugin({
filename: "index.html",
template: "./src/web/html/index.html",
chunks: ["main"],
compileYear: compileYear,
compileTime: compileTime,
version: pkg.version,
minify: {
removeComments: true,
collapseWhitespace: true,
minifyJS: true,
minifyCSS: true
}
}),
new BundleAnalyzerPlugin({
analyzerMode: "static",
reportFilename: "BundleAnalyzerReport.html",
openAnalyzer: false
}),
]
};
}
|
Configuration for Webpack production build. Defined as a function so that it
can be recalculated when new modules are generated.
|
webpackProdConf
|
javascript
|
gchq/CyberChef
|
Gruntfile.js
|
https://github.com/gchq/CyberChef/blob/master/Gruntfile.js
|
Apache-2.0
|
webpackProdConf = () => {
return {
mode: "production",
target: "web",
entry: Object.assign({
main: "./src/web/index.js"
}, moduleEntryPoints),
output: {
path: __dirname + "/build/prod",
filename: chunkData => {
return chunkData.chunk.name === "main" ? "assets/[name].js": "[name].js";
},
globalObject: "this"
},
resolve: {
alias: {
"./config/modules/OpModules.mjs": "./config/modules/Default.mjs"
}
},
plugins: [
new webpack.DefinePlugin(BUILD_CONSTANTS),
new HtmlWebpackPlugin({
filename: "index.html",
template: "./src/web/html/index.html",
chunks: ["main"],
compileYear: compileYear,
compileTime: compileTime,
version: pkg.version,
minify: {
removeComments: true,
collapseWhitespace: true,
minifyJS: true,
minifyCSS: true
}
}),
new BundleAnalyzerPlugin({
analyzerMode: "static",
reportFilename: "BundleAnalyzerReport.html",
openAnalyzer: false
}),
]
};
}
|
Configuration for Webpack production build. Defined as a function so that it
can be recalculated when new modules are generated.
|
webpackProdConf
|
javascript
|
gchq/CyberChef
|
Gruntfile.js
|
https://github.com/gchq/CyberChef/blob/master/Gruntfile.js
|
Apache-2.0
|
function listEntryModules() {
const entryModules = {};
glob.sync("./src/core/config/modules/*.mjs").forEach(file => {
const basename = path.basename(file);
if (basename !== "Default.mjs" && basename !== "OpModules.mjs")
entryModules["modules/" + basename.split(".mjs")[0]] = path.resolve(file);
});
return entryModules;
}
|
Generates an entry list for all the modules.
|
listEntryModules
|
javascript
|
gchq/CyberChef
|
Gruntfile.js
|
https://github.com/gchq/CyberChef/blob/master/Gruntfile.js
|
Apache-2.0
|
async function getDishAs(data) {
const value = await self.chef.getDishAs(data.dish, data.type);
const transferable = (data.type === "ArrayBuffer") ? [value] : undefined;
self.postMessage({
action: "dishReturned",
data: {
value: value,
id: data.id
}
}, transferable);
}
|
Translates the dish to a given type.
|
getDishAs
|
javascript
|
gchq/CyberChef
|
src/core/ChefWorker.js
|
https://github.com/gchq/CyberChef/blob/master/src/core/ChefWorker.js
|
Apache-2.0
|
async function getDishTitle(data) {
const title = await self.chef.getDishTitle(data.dish, data.maxLength);
self.postMessage({
action: "dishReturned",
data: {
value: title,
id: data.id
}
});
}
|
Gets the dish title
@param {object} data
@param {Dish} data.dish
@param {number} data.maxLength
@param {number} data.id
|
getDishTitle
|
javascript
|
gchq/CyberChef
|
src/core/ChefWorker.js
|
https://github.com/gchq/CyberChef/blob/master/src/core/ChefWorker.js
|
Apache-2.0
|
async function calculateHighlights(recipeConfig, direction, pos) {
pos = await self.chef.calculateHighlights(recipeConfig, direction, pos);
self.postMessage({
action: "highlightsCalculated",
data: pos
});
}
|
Calculates highlight offsets if possible.
@param {Object[]} recipeConfig
@param {string} direction
@param {Object[]} pos - The position object for the highlight.
@param {number} pos.start - The start offset.
@param {number} pos.end - The end offset.
|
calculateHighlights
|
javascript
|
gchq/CyberChef
|
src/core/ChefWorker.js
|
https://github.com/gchq/CyberChef/blob/master/src/core/ChefWorker.js
|
Apache-2.0
|
function main() {
const defaultFavourites = [
"To Base64",
"From Base64",
"To Hex",
"From Hex",
"To Hexdump",
"From Hexdump",
"URL Decode",
"Regular expression",
"Entropy",
"Fork",
"Magic"
];
const defaultOptions = {
updateUrl: true,
showHighlighter: true,
wordWrap: true,
showErrors: true,
errorTimeout: 4000,
attemptHighlight: true,
theme: "classic",
useMetaKey: false,
logLevel: "info",
autoMagic: true,
imagePreview: true,
syncTabs: true,
showCatCount: false,
};
document.removeEventListener("DOMContentLoaded", main, false);
window.app = new App(Categories, OperationConfig, defaultFavourites, defaultOptions);
window.app.setup();
}
|
Main function used to build the CyberChef web app.
|
main
|
javascript
|
gchq/CyberChef
|
src/web/index.js
|
https://github.com/gchq/CyberChef/blob/master/src/web/index.js
|
Apache-2.0
|
seek = function() {
if (offset >= file.size) {
self.postMessage({"fileBuffer": data.buffer, "inputNum": inputNum, "id": self.id}, [data.buffer]);
return;
}
self.postMessage({"progress": Math.round(offset / file.size * 100), "inputNum": inputNum});
const slice = file.slice(offset, offset + CHUNK_SIZE);
reader.readAsArrayBuffer(slice);
}
|
Loads a file object into an ArrayBuffer, then transfers it back to the parent thread.
@param {File} file
@param {string} inputNum
|
seek
|
javascript
|
gchq/CyberChef
|
src/web/workers/LoaderWorker.js
|
https://github.com/gchq/CyberChef/blob/master/src/web/workers/LoaderWorker.js
|
Apache-2.0
|
seek = function() {
if (offset >= file.size) {
self.postMessage({"fileBuffer": data.buffer, "inputNum": inputNum, "id": self.id}, [data.buffer]);
return;
}
self.postMessage({"progress": Math.round(offset / file.size * 100), "inputNum": inputNum});
const slice = file.slice(offset, offset + CHUNK_SIZE);
reader.readAsArrayBuffer(slice);
}
|
Loads a file object into an ArrayBuffer, then transfers it back to the parent thread.
@param {File} file
@param {string} inputNum
|
seek
|
javascript
|
gchq/CyberChef
|
src/web/workers/LoaderWorker.js
|
https://github.com/gchq/CyberChef/blob/master/src/web/workers/LoaderWorker.js
|
Apache-2.0
|
function loadOp(opName, browser) {
return browser
.useCss()
.click("#clr-recipe")
.urlHash("op=" + opName);
}
|
Clears the current recipe and loads a new operation.
@param {string} opName
@param {Browser} browser
|
loadOp
|
javascript
|
gchq/CyberChef
|
tests/browser/00_nightwatch.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/00_nightwatch.js
|
Apache-2.0
|
function bakeOp(browser, opName, input, args=[]) {
browser.perform(function() {
console.log(`Current test: ${opName}`);
});
utils.loadRecipe(browser, opName, input, args);
browser.waitForElementVisible("#stale-indicator", 5000);
utils.bake(browser);
}
|
@function
Clears the current recipe and bakes a new operation.
@param {Browser} browser - Nightwatch client
@param {string|Array<string>} opName - name of operation to be tested, array for multiple ops
@param {string} input - input text for test
@param {Array<string>|Array<Array<string>>} [args=[]] - arguments, nested if multiple ops
|
bakeOp
|
javascript
|
gchq/CyberChef
|
tests/browser/02_ops.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/02_ops.js
|
Apache-2.0
|
function testOp(browser, opName, input, output, args=[]) {
bakeOp(browser, opName, input, args);
utils.expectOutput(browser, output, true);
}
|
@function
Clears the current recipe and tests a new operation.
@param {Browser} browser - Nightwatch client
@param {string|Array<string>} opName - name of operation to be tested, array for multiple ops
@param {string} input - input text
@param {string|RegExp} output - expected output
@param {Array<string>|Array<Array<string>>} [args=[]] - arguments, nested if multiple ops
|
testOp
|
javascript
|
gchq/CyberChef
|
tests/browser/02_ops.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/02_ops.js
|
Apache-2.0
|
function testOpHtml(browser, opName, input, cssSelector, output, args=[]) {
bakeOp(browser, opName, input, args);
if (typeof output === "string") {
browser.expect.element("#output-html " + cssSelector).text.that.equals(output);
} else if (output instanceof RegExp) {
browser.expect.element("#output-html " + cssSelector).text.that.matches(output);
}
}
|
@function
Clears the current recipe and tests a new operation with HTML output.
@param {Browser} browser - Nightwatch client
@param {string|Array<string>} opName - name of operation to be tested array for multiple ops
@param {string} input - input text
@param {string} cssSelector - CSS selector for HTML output
@param {string|RegExp} output - expected output
@param {Array<string>|Array<Array<string>>} [args=[]] - arguments, nested if multiple ops
|
testOpHtml
|
javascript
|
gchq/CyberChef
|
tests/browser/02_ops.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/02_ops.js
|
Apache-2.0
|
function testOpImage(browser, opName, filename, args=[]) {
browser.perform(function() {
console.log(`Current test: ${opName}`);
});
utils.loadRecipe(browser, opName, "", args);
utils.uploadFile(browser, filename);
browser.waitForElementVisible("#stale-indicator", 5000);
utils.bake(browser);
browser
.waitForElementVisible("#output-html img")
.expect.element("#output-html img").to.have.css("width").which.matches(/^[^0]\d*px/);
}
|
@function
Clears the current recipe and tests a new Image-based operation.
@param {Browser} browser - Nightwatch client
@param {string|Array<string>} opName - name of operation to be tested array for multiple ops
@param {string} filename - filename of image file from samples directory
@param {Array<string>|Array<Array<string>>} [args=[]] - arguments, nested if multiple ops
|
testOpImage
|
javascript
|
gchq/CyberChef
|
tests/browser/02_ops.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/02_ops.js
|
Apache-2.0
|
function testOpFile(browser, opName, filename, cssSelector, output, args=[], waitWindow=1000) {
browser.perform(function() {
console.log(`Current test: ${opName}`);
});
utils.loadRecipe(browser, opName, "", args);
utils.uploadFile(browser, filename);
browser.pause(100).waitForElementVisible("#stale-indicator", 5000);
utils.bake(browser);
if (!cssSelector) {
// Text output
utils.expectOutput(browser, output, true, waitWindow);
} else if (typeof output === "string") {
// HTML output - string match
browser.expect.element("#output-html " + cssSelector).text.that.equals(output);
} else if (output instanceof RegExp) {
// HTML output - RegEx match
browser.expect.element("#output-html " + cssSelector).text.that.matches(output);
}
}
|
@function
Clears the current recipe and tests a new File-based operation.
@param {Browser} browser - Nightwatch client
@param {string|Array<string>} opName - name of operation to be tested array for multiple ops
@param {string} filename - filename of file from samples directory
@param {string|boolean} cssSelector - CSS selector for HTML output or false for normal text output
@param {string|RegExp} output - expected output
@param {Array<string>|Array<Array<string>>} [args=[]] - arguments, nested if multiple ops
@param {number} [waitWindow=1000] - The number of milliseconds to wait for the output to be correct
|
testOpFile
|
javascript
|
gchq/CyberChef
|
tests/browser/02_ops.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/02_ops.js
|
Apache-2.0
|
function clear(browser) {
browser
.useCss()
.click("#clr-recipe")
.click("#clr-io")
.waitForElementNotPresent("#rec-list li.operation")
.expect.element("#input-text .cm-content").text.that.equals("");
}
|
@function
Clears the recipe and input
@param {Browser} browser - Nightwatch client
|
clear
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function setInput(browser, input, type=true) {
clear(browser);
if (type) {
browser
.useCss()
.sendKeys("#input-text .cm-content", input)
.pause(100);
} else {
browser.execute(text => {
window.app.setInput(text);
}, [input]);
browser.pause(100);
}
expectInput(browser, input);
}
|
@function
Sets the input to the desired string
@param {Browser} browser - Nightwatch client
@param {string} input - The text to populate the input with
@param {boolean} [type=true] - Whether to type the characters in by using sendKeys,
or to set the value of the editor directly (useful for special characters)
|
setInput
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function bake(browser) {
browser
// Ensure we're not currently busy
.waitForElementNotVisible("#output-loader", 5000)
.expect.element("#bake span").text.to.equal("BAKE!");
browser
.click("#bake")
.waitForElementNotVisible("#stale-indicator", 5000)
.waitForElementNotVisible("#output-loader", 5000);
}
|
@function
Triggers a bake
@param {Browser} browser - Nightwatch client
|
bake
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function setChrEnc(browser, io, enc) {
io = `#${io}-text`;
browser
.useCss()
.waitForElementNotVisible("#snackbar-container", 6000)
.click(io + " .chr-enc-value")
.waitForElementVisible(io + " .chr-enc-select .cm-status-bar-select-scroll")
.click("link text", enc)
.waitForElementNotVisible(io + " .chr-enc-select .cm-status-bar-select-scroll")
.expect.element(io + " .chr-enc-value").text.that.equals(enc);
}
|
@function
Sets the character encoding in the input or output
@param {Browser} browser - Nightwatch client
@param {string} io - Either "input" or "output"
@param {string} enc - The encoding to be set
|
setChrEnc
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function setEOLSeq(browser, io, eol) {
io = `#${io}-text`;
browser
.useCss()
.waitForElementNotVisible("#snackbar-container", 6000)
.click(io + " .eol-value")
.waitForElementVisible(io + " .eol-select .cm-status-bar-select-content")
.click(`${io} .cm-status-bar-select-content a[data-val=${eol}]`)
.waitForElementNotVisible(io + " .eol-select .cm-status-bar-select-content")
.expect.element(io + " .eol-value").text.that.equals(eol);
}
|
@function
Sets the end of line sequence in the input or output
@param {Browser} browser - Nightwatch client
@param {string} io - Either "input" or "output"
@param {string} eol - The sequence to set
|
setEOLSeq
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function copy(browser) {
browser.perform(function() {
const actions = this.actions({async: true});
// Ctrl + Ins used as this works on Windows, Linux and Mac
return actions
.keyDown(browser.Keys.CONTROL)
.keyDown(browser.Keys.INSERT)
.keyUp(browser.Keys.INSERT)
.keyUp(browser.Keys.CONTROL);
});
}
|
@function
Copies whatever is currently selected
@param {Browser} browser - Nightwatch client
|
copy
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function paste(browser, el) {
browser
.click(el)
.perform(function() {
const actions = this.actions({async: true});
// Shift + Ins used as this works on Windows, Linux and Mac
return actions
.keyDown(browser.Keys.SHIFT)
.keyDown(browser.Keys.INSERT)
.keyUp(browser.Keys.INSERT)
.keyUp(browser.Keys.SHIFT);
})
.pause(100);
}
|
@function
Pastes into the target element
@param {Browser} browser - Nightwatch client
@param {string} el - Target element selector
|
paste
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function loadRecipe(browser, opName, input, args) {
let recipeConfig;
if (typeof(opName) === "string") {
recipeConfig = JSON.stringify([{
"op": opName,
"args": args
}]);
} else if (opName instanceof Array) {
recipeConfig = JSON.stringify(
opName.map((op, i) => {
return {
op: op,
args: args.length ? args[i] : []
};
})
);
} else {
throw new Error("Invalid operation type. Must be string or array of strings. Received: " + typeof(opName));
}
setInput(browser, input, false);
browser
.urlHash("recipe=" + recipeConfig)
.waitForElementPresent("#rec-list li.operation");
}
|
@function
Loads a recipe and input
@param {Browser} browser - Nightwatch client
@param {string|Array<string>} opName - name of operation to be loaded, array for multiple ops
@param {string} input - input text for test
@param {Array<string>|Array<Array<string>>} args - arguments, nested if multiple ops
|
loadRecipe
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function expectOutput(browser, expected, waitNotNull=false, waitWindow=1000) {
if (waitNotNull && expected !== "") {
browser.waitUntil(async function() {
const output = await this.execute(function() {
return window.app.manager.output.outputEditorView.state.doc.toString();
});
return output.length;
}, waitWindow);
}
browser.execute(expected => {
return window.app.manager.output.outputEditorView.state.doc.toString();
}, [expected], function({value}) {
if (expected instanceof RegExp) {
browser.expect(value).match(expected);
} else {
browser.expect(value).to.be.equal(expected);
}
});
}
|
@function
Tests whether the output matches a given value
@param {Browser} browser - Nightwatch client
@param {string|RegExp} expected - The expected output value
@param {boolean} [waitNotNull=false] - Wait for the output to not be empty before testing the value
@param {number} [waitWindow=1000] - The number of milliseconds to wait for the output to be correct
|
expectOutput
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function expectInput(browser, expected) {
browser.execute(expected => {
return window.app.manager.input.inputEditorView.state.doc.toString();
}, [expected], function({value}) {
if (expected instanceof RegExp) {
browser.expect(value).match(expected);
} else {
browser.expect(value).to.be.equal(expected);
}
});
}
|
@function
Tests whether the input matches a given value
@param {Browser} browser - Nightwatch client
@param {string|RegExp} expected - The expected input value
|
expectInput
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function uploadFile(browser, filename) {
const filepath = require("path").resolve(__dirname + "/../samples/" + filename);
// The file input cannot be interacted with by nightwatch while it is hidden,
// so we temporarily expose it for the purposes of this test.
browser.execute(() => {
document.getElementById("open-file").style.display = "block";
});
browser
.pause(100)
.setValue("#open-file", filepath)
.pause(100);
browser.execute(() => {
document.getElementById("open-file").style.display = "none";
});
browser.waitForElementVisible("#input-text .cm-file-details");
}
|
@function
Uploads a file using the #open-file input
@param {Browser} browser - Nightwatch client
@param {string} filename - A path to a file in the samples directory
|
uploadFile
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
function uploadFolder(browser, foldername) {
const folderpath = require("path").resolve(__dirname + "/../samples/" + foldername);
// The folder input cannot be interacted with by nightwatch while it is hidden,
// so we temporarily expose it for the purposes of this test.
browser.execute(() => {
document.getElementById("open-folder").style.display = "block";
});
browser
.pause(100)
.setValue("#open-folder", folderpath)
.pause(500);
browser.execute(() => {
document.getElementById("open-folder").style.display = "none";
});
browser.waitForElementVisible("#input-text .cm-file-details");
}
|
@function
Uploads a folder using the #open-folder input
@param {Browser} browser - Nightwatch client
@param {string} foldername - A path to a folder in the samples directory
|
uploadFolder
|
javascript
|
gchq/CyberChef
|
tests/browser/browserUtils.js
|
https://github.com/gchq/CyberChef/blob/master/tests/browser/browserUtils.js
|
Apache-2.0
|
destroyAssetAndFile = (asset, req) => AssetService
.destroy(asset, req)
.then(AssetService.deleteFile(asset))
.then(() => sails.log.info('Destroyed asset:', asset))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyAssetAndFile
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyAssetAndFile = (asset, req) => AssetService
.destroy(asset, req)
.then(AssetService.deleteFile(asset))
.then(() => sails.log.info('Destroyed asset:', asset))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyAssetAndFile
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyAssetsAndFiles = (version, req) => version.assets
.map(asset => destroyAssetAndFile(asset, req))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyAssetsAndFiles
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyAssetsAndFiles = (version, req) => version.assets
.map(asset => destroyAssetAndFile(asset, req))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyAssetsAndFiles
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyVersion = (version, req) => VersionService
.destroy(version, req)
.then(() => sails.log.info('Destroyed version:', version))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyVersion
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyVersion = (version, req) => VersionService
.destroy(version, req)
.then(() => sails.log.info('Destroyed version:', version))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyVersion
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyVersionAssetsAndFiles = (version, req) => Promise
.all(destroyAssetsAndFiles(version, req))
.then(destroyVersion(version, req))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyVersionAssetsAndFiles
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyVersionAssetsAndFiles = (version, req) => Promise
.all(destroyAssetsAndFiles(version, req))
.then(destroyVersion(version, req))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyVersionAssetsAndFiles
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyFlavor = (flavor, req) => FlavorService
.destroy(flavor, req)
.then(() => sails.log.info('Destroyed flavor:', flavor))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyFlavor
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
destroyFlavor = (flavor, req) => FlavorService
.destroy(flavor, req)
.then(() => sails.log.info('Destroyed flavor:', flavor))
|
FlavorController
@description :: Server-side logic for managing Flavors
@help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
|
destroyFlavor
|
javascript
|
ArekSredzki/electron-release-server
|
api/controllers/FlavorController.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/controllers/FlavorController.js
|
MIT
|
function hashPrerelease(s) {
if (_.isString(s[0])) {
return (_.indexOf(PRERELEASE_CHANNELS, s[0]) + 1) * PRERELEASE_CHANNEL_MAGINITUDE + (s[1] || 0);
} else {
return s[0];
}
}
|
Hash a prerelease
@param {String} s [description]
@return {String} [description]
|
hashPrerelease
|
javascript
|
ArekSredzki/electron-release-server
|
api/services/WindowsReleaseService.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/api/services/WindowsReleaseService.js
|
MIT
|
updateVersionAssets = function() {
var updatedVersion = _.find(DataService.data, {
id: version.id
});
if (!updatedVersion) {
// The version no longer exists
return $uibModalInstance.close();
}
$scope.version.assets = updatedVersion.assets;
}
|
Updates the modal's knowlege of this version's assets from the one
maintained by DataService (which should be up to date with the server
because of SocketIO's awesomeness.
|
updateVersionAssets
|
javascript
|
ArekSredzki/electron-release-server
|
assets/js/admin/edit-version-modal/edit-version-modal-controller.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/assets/js/admin/edit-version-modal/edit-version-modal-controller.js
|
MIT
|
showAttributeWarnings = function(response) {
if (!_.has(response, 'data.invalidAttributes')) {
return;
}
_.forEach(response.data.invalidAttributes,
function(attribute, attributeName) {
let warningMessage = '';
_.forEach(attribute, function(attributeError) {
warningMessage += (attributeError.message || '') + '<br />';
});
Notification.warning({
title: 'Invalid attribute: ' + attributeName,
message: warningMessage
});
});
}
|
Shows an appropriate error notification method for every invalid
attribute.
@param {Object} response A response object returned by sails after a
erroneous blueprint request.
|
showAttributeWarnings
|
javascript
|
ArekSredzki/electron-release-server
|
assets/js/core/data/data-service.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/assets/js/core/data/data-service.js
|
MIT
|
showErrors = function(response, errorTitle) {
if (!response) {
return Notification.error({
title: errorTitle,
message: UNKNOWN_ERROR_MESSAGE
});
}
Notification.error({
title: errorTitle,
message: response.summary || UNKNOWN_ERROR_MESSAGE
});
showAttributeWarnings(response);
}
|
Shows notifications detailing the various errors described by the
response object
@param {Object} response A response object returned by sails after a
erroneous request.
@param {String} errorTitle The string to be used as a title for the
main error notification.
|
showErrors
|
javascript
|
ArekSredzki/electron-release-server
|
assets/js/core/data/data-service.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/assets/js/core/data/data-service.js
|
MIT
|
normalizeVersion = function(version) {
if (!version) {
return;
}
if (_.isString(version.channel)) {
version.channel = {
name: version.channel
};
}
if (typeof version.flavor === 'string') {
version.flavor = {
name: version.flavor
};
}
if (!_.isArrayLike(version.assets)) {
version.assets = [];
}
if (new Date(version.availability) < new Date(version.createdAt)) {
version.availability = version.createdAt;
}
return version;
}
|
Normalize the version object returned by sails over SocketIO.
Note: Sails will not populate related models on update
Specifically:
- The channel parameter will sometimes only contain the channel name.
- The assets parameter will not be included if empty.
- The availability parameter will sometimes be dated before the createdAt date.
@param {Object} version Unnormalized version object
@return {Object} Normalized version object
|
normalizeVersion
|
javascript
|
ArekSredzki/electron-release-server
|
assets/js/core/data/data-service.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/assets/js/core/data/data-service.js
|
MIT
|
normalizeAsset = function(asset) {
if (!asset) {
return;
}
if (_.isString(asset.version)) {
asset.version = {
id: asset.version
};
}
return asset;
}
|
Normalize the asset object returned by sails over SocketIO.
Note: Sails will not populate related models on update
Specifically:
- The version parameter will sometimes only contain the version id.
@param {Object} asset Unnormalized asset object
@return {Object} Normalized asset object
|
normalizeAsset
|
javascript
|
ArekSredzki/electron-release-server
|
assets/js/core/data/data-service.js
|
https://github.com/ArekSredzki/electron-release-server/blob/master/assets/js/core/data/data-service.js
|
MIT
|
function watch() {
gulp.watch(['src/*', 'src/adapters/*'], build);
gulp.watch(['src/*', 'src/adapters/*'], buildJquery);
}
|
The UMD wrapper expects an exports() string for an expression the factory() should return,
and a namespace() string for a global value that should be set when no loader is present.
However, since jquery_pressure.js mutates $ several times instead of returning a value,
it does not need to use these features, so we set them to harmless no-ops.
|
watch
|
javascript
|
stuyam/pressure
|
gulpfile.js
|
https://github.com/stuyam/pressure/blob/master/gulpfile.js
|
MIT
|
function unpackConfig()
{
if (typeof _config !== 'object')
return;
if (typeof _config.delimiter === 'string'
&& !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length)
{
_delimiter = _config.delimiter;
}
if (typeof _config.quotes === 'boolean'
|| typeof _config.quotes === 'function'
|| Array.isArray(_config.quotes))
_quotes = _config.quotes;
if (typeof _config.skipEmptyLines === 'boolean'
|| typeof _config.skipEmptyLines === 'string')
_skipEmptyLines = _config.skipEmptyLines;
if (typeof _config.newline === 'string')
_newline = _config.newline;
if (typeof _config.quoteChar === 'string')
_quoteChar = _config.quoteChar;
if (typeof _config.header === 'boolean')
_writeHeader = _config.header;
if (Array.isArray(_config.columns)) {
if (_config.columns.length === 0) throw new Error('Option columns is empty');
_columns = _config.columns;
}
if (_config.escapeChar !== undefined) {
_escapedQuote = _config.escapeChar + _quoteChar;
}
if (_config.escapeFormulae instanceof RegExp) {
_escapeFormulae = _config.escapeFormulae;
} else if (typeof _config.escapeFormulae === 'boolean' && _config.escapeFormulae) {
_escapeFormulae = /^[=+\-@\t\r].*$/;
}
}
|
whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice)
|
unpackConfig
|
javascript
|
mholt/PapaParse
|
papaparse.js
|
https://github.com/mholt/PapaParse/blob/master/papaparse.js
|
MIT
|
function serialize(fields, data, skipEmptyLines)
{
var csv = '';
if (typeof fields === 'string')
fields = JSON.parse(fields);
if (typeof data === 'string')
data = JSON.parse(data);
var hasHeader = Array.isArray(fields) && fields.length > 0;
var dataKeyedByField = !(Array.isArray(data[0]));
// If there a header row, write it first
if (hasHeader && _writeHeader)
{
for (var i = 0; i < fields.length; i++)
{
if (i > 0)
csv += _delimiter;
csv += safe(fields[i], i);
}
if (data.length > 0)
csv += _newline;
}
// Then write out the data
for (var row = 0; row < data.length; row++)
{
var maxCol = hasHeader ? fields.length : data[row].length;
var emptyLine = false;
var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0;
if (skipEmptyLines && !hasHeader)
{
emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0;
}
if (skipEmptyLines === 'greedy' && hasHeader) {
var line = [];
for (var c = 0; c < maxCol; c++) {
var cx = dataKeyedByField ? fields[c] : c;
line.push(data[row][cx]);
}
emptyLine = line.join('').trim() === '';
}
if (!emptyLine)
{
for (var col = 0; col < maxCol; col++)
{
if (col > 0 && !nullLine)
csv += _delimiter;
var colIdx = hasHeader && dataKeyedByField ? fields[col] : col;
csv += safe(data[row][colIdx], col);
}
if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine)))
{
csv += _newline;
}
}
}
return csv;
}
|
The double for loop that iterates the data and writes out a CSV string including header row
|
serialize
|
javascript
|
mholt/PapaParse
|
papaparse.js
|
https://github.com/mholt/PapaParse/blob/master/papaparse.js
|
MIT
|
function safe(str, col)
{
if (typeof str === 'undefined' || str === null)
return '';
if (str.constructor === Date)
return JSON.stringify(str).slice(1, 25);
var needsQuotes = false;
if (_escapeFormulae && typeof str === "string" && _escapeFormulae.test(str)) {
str = "'" + str;
needsQuotes = true;
}
var escapedQuoteStr = str.toString().replace(quoteCharRegex, _escapedQuote);
needsQuotes = needsQuotes
|| _quotes === true
|| (typeof _quotes === 'function' && _quotes(str, col))
|| (Array.isArray(_quotes) && _quotes[col])
|| hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS)
|| escapedQuoteStr.indexOf(_delimiter) > -1
|| escapedQuoteStr.charAt(0) === ' '
|| escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' ';
return needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr;
}
|
Encloses a value around quotes if needed (makes a value safe for CSV insertion)
|
safe
|
javascript
|
mholt/PapaParse
|
papaparse.js
|
https://github.com/mholt/PapaParse/blob/master/papaparse.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.