_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q35200 | sphereVsPoint | train | function sphereVsPoint(sphere, point) {
return vec3.squaredDistance(point, sphere.centerOfVolume) <= sphere.radius * sphere.radius;
} | javascript | {
"resource": ""
} |
q35201 | _haversineCalculation | train | function _haversineCalculation(coordinateOne, coordinateTwo) {
// Credits
// https://www.movable-type.co.uk/scripts/latlong.html
// https://en.wikipedia.org/wiki/Haversine_formula
let latitudeOneRadians = _convertDegreesToRadians(coordinateOne.latitude);
let latitudeTwoRadians = _convertDegreesToRadians(coordinateTwo.latitude);
let longitudeOneRadians = _convertDegreesToRadians(coordinateOne.longitude);
let longitudeTwoRadians = _convertDegreesToRadians(coordinateTwo.longitude);
let differenceOfLatitude = latitudeOneRadians - latitudeTwoRadians;
let differenceOfLongitude = longitudeOneRadians - longitudeTwoRadians;
// The square of half the chord length between the points
let a = Math.sin(differenceOfLatitude / 2) * Math.sin(differenceOfLatitude / 2)
+ Math.sin(differenceOfLongitude / 2) * Math.sin(differenceOfLongitude / 2)
* Math.cos(latitudeOneRadians) * Math.cos(latitudeTwoRadians);
let angularDistanceInRadians = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let distanceBetweenKM = EARTH_RADIUS_KM * angularDistanceInRadians;
return distanceBetweenKM;
} | javascript | {
"resource": ""
} |
q35202 | join | train | function join(args) {
var arg;
var i = 0;
var path = '';
if (arguments.length === 0) {
return utils.sep;
}
while ((arg = arguments[i++])) {
if (typeof arg !== 'string') {
throw new TypeError('utils.join() expects string arguments');
}
path += utils.sep + arg;
}
path = path.replace(/\/+/g, utils.sep);
if (path[path.length - 1] === utils.sep) {
path = path.substring(0, path.length - 1);
}
return path;
} | javascript | {
"resource": ""
} |
q35203 | extractMetadata | train | function extractMetadata (content, callback) {
var end;
var result;
var metadata = '';
var body = content;
// Metadata is defined by either starting and ending line,
if (content.slice(0, 3) === '---') {
result = content.match(/^-{3,}\s([\s\S]*?)-{3,}(\s[\s\S]*|\s?)$/);
if (result && result.length === 3) {
metadata = result[1];
body = result[2];
}
}
// or Markdown metadata section at beginning of file.
else if (content.slice(0, 12) === '```metadata\n') {
end = content.indexOf('\n```\n');
if (end !== -1) {
metadata = content.substring(12, end);
body = content.substring(end + 5);
}
}
parseMetadata(metadata, function (error, parsed) {
if (error) return callback(error);
callback(null, {
metadata: parsed,
body: body
});
});
} | javascript | {
"resource": ""
} |
q35204 | Client | train | function Client(host, port) {
// Invokes with new if called without
if (false === (this instanceof Client)) {
return new Client(host, port)
}
this.host = host;
this.port = port;
} | javascript | {
"resource": ""
} |
q35205 | Client | train | function Client(settings, callback) {
this.debug('new Client', settings.url);
var self = this;
// Mixing settings and emitter into instance.
require('object-emitter').mixin(this);
require('object-settings').mixin(this);
// Set defaults and instance settings.
this.set(Client.defaults).set(settings);
// Set properties from parsed URL.
this.set('hostname', this.common.parseURL(this.get('url')).hostname);
this.set('auth', this.common.parseURL(this.get('url')).auth);
this.set('blog', this.get('blog') || this.get('blogId'));
// Instance Properties.
Object.defineProperties(this, {
__client: {
value: this.common.createClient({
url: settings.url,
username: settings.username,
password: settings.password,
blogId: self.get('blog')
}),
enumerable: false,
configurable: true,
writable: false
},
__queue: {
value: [],
enumerable: false,
configurable: true,
writable: false
}
});
this.detectBlog(function (err, blog, response) {
if (err) {
return self.onceReady.call(self, err);
}
self.set('blogs', response);
// Schedule initial RPC call to verify target is valid.
self.listMethods(self.onceReady.bind(self));
// Schedule callback, if provided.
if (_.isFunction(callback)) {
self.once('connected', callback);
}
// Emit ready event on next tick.
self.nextTick(self.emit, 'ready', null, self);
});
// @chainable
return this;
} | javascript | {
"resource": ""
} |
q35206 | onceReady | train | function onceReady(error, methods) {
this.debug(error ? 'No methods (%d) found, unable to connect to %s.' : 'onceReady: Found %d methods on %s.', ( methods ? methods.length : 0 ), this.get('url'));
// Set Methods.
this.set('methods', this.common.trim(methods));
if (error) {
this.emit('error', error, this);
}
this.emit('connected', error, this);
// @chainable
return this;
} | javascript | {
"resource": ""
} |
q35207 | callbackWrapper | train | function callbackWrapper(error, response) {
self.debug('methodCall->callbackWrapper', error, response);
// TODO: error should be customized to handle more error types
if (error /*&& error.code === "ENOTFOUND" && error.syscall === "getaddrinfo"*/) {
error.message = "Unable to connect to WordPress.";
return callback.call(self, error);
}
// Parse Response.
if (_.isString(response) && self.common.is_numeric(response)) {
response = parseInt(response);
}
callback.call(self, error, response);
} | javascript | {
"resource": ""
} |
q35208 | nextTick | train | function nextTick(callback) {
var context = this;
var args = Array.prototype.slice.call(arguments, 1);
// Do not schedule callback if not a valid function.
if ('function' !== typeof callback) {
return this;
}
// Execute callback on next tick.
process.nextTick(function nextTickHandler() {
context.debug('nextTick', callback.name);
callback.apply(context, args);
});
// @chainable
return this;
} | javascript | {
"resource": ""
} |
q35209 | capsuleVsSphere | train | function capsuleVsSphere(contactPoint, contactNormal, capsule, sphere) {
const sphereCenter = sphere.centerOfVolume;
findClosestPointOnSegmentToPoint(contactPoint, capsule.segment, sphereCenter);
vec3.subtract(contactNormal, sphereCenter, contactPoint);
vec3.normalize(contactNormal, contactNormal);
vec3.scaleAndAdd(contactPoint, contactPoint, contactNormal, capsule.radius);
} | javascript | {
"resource": ""
} |
q35210 | capsuleVsAabb | train | function capsuleVsAabb(contactPoint, contactNormal, capsule, aabb) {
// tmpVec1 represents the closest point on the capsule to the AABB. tmpVec2
// represents the closest point on the AABB to the capsule.
//
// Check whether the two capsule ends intersect the AABB (sphere vs AABB) (addresses the
// capsule-vs-AABB-face case).
//
const squaredRadius = capsule.radius * capsule.radius;
let doesAabbIntersectAnEndPoint = false;
let endPoint = capsule.segment.start;
findClosestPointFromAabbToPoint(tmpVec2, aabb, endPoint);
if (vec3.squaredDistance(tmpVec2, endPoint) <= squaredRadius) {
doesAabbIntersectAnEndPoint = true;
} else {
endPoint = capsule.segment.end;
findClosestPointFromAabbToPoint(tmpVec2, aabb, endPoint);
if (vec3.squaredDistance(tmpVec2, endPoint) <= squaredRadius) {
doesAabbIntersectAnEndPoint = true;
}
}
if (!doesAabbIntersectAnEndPoint) {
//
// Check whether the capsule intersects with any AABB edge (addresses the capsule-vs-AABB-edge
// case).
//
aabb.someEdge(edge => {
findClosestPointsFromSegmentToSegment(tmpVec1, tmpVec2,
capsule.segment, edge);
const distance = vec3.squaredDistance(tmpVec1, tmpVec2);
return distance <= squaredRadius;
});
}
// (The capsule-vs-AABB-vertex case is covered by the capsule-vs-AABB-edge case).
findClosestPointOnSegmentToPoint(tmpVec1, capsule.segment, tmpVec2);
vec3.subtract(contactNormal, tmpVec2, tmpVec1);
vec3.normalize(contactNormal, contactNormal);
vec3.scaleAndAdd(contactPoint, tmpVec1, contactNormal, capsule.radius);
} | javascript | {
"resource": ""
} |
q35211 | capsuleVsCapsule | train | function capsuleVsCapsule(contactPoint, contactNormal, capsuleA, capsuleB) {
findClosestPointsFromSegmentToSegment(tmpVec1, tmpVec2,
capsuleA.segment, capsuleB.segment);
vec3.subtract(contactNormal, tmpVec2, tmpVec1);
vec3.normalize(contactNormal, contactNormal);
vec3.scaleAndAdd(contactPoint, tmpVec1, contactNormal, capsuleA.radius);
} | javascript | {
"resource": ""
} |
q35212 | loadSchema | train | function loadSchema(uri) {
return new Promise(function(resolve, reject) {
request.get(uri).end(function(error, response) {
if (error || !response.ok) {
error = error || new Error(response.body);
debug("error fetching remote schema:", error);
return reject(error);
}
return resolve(response.body);
});
});
} | javascript | {
"resource": ""
} |
q35213 | requireAll | train | function requireAll(schemaDir, options, callback) {
debug("loading schemas");
if (!callback) {
callback = options;
options = {};
}
const opts = _.assign({
extensions: ["json"],
}, options);
let files;
try {
files = fs.readdirSync(schemaDir);
} catch(errReaddir) {
return callback(errReaddir);
}
let schemas = [];
for (let index = 0; index < files.length; index++) {
const file = files[index];
const ext = path.extname(file).slice(1);
if (opts.extensions.indexOf(ext) === -1) {
continue;
}
const abspath = path.join(schemaDir, file);
let schema;
// try load the schema! If it fails, stop immediately
try {
schema = require(abspath);
} catch (errRequire) {
return callback(errRequire);
}
schema.filepath = abspath;
schemas.push(schema);
}
return callback(null, schemas);
} | javascript | {
"resource": ""
} |
q35214 | expandVars | train | function expandVars(target, options) {
const vars = options.vars || {};
const regexp = /\$\{(\w+)\}/g;
if (typeof target === "string") {
return _expand(target);
}
for (let key in target) {
target[key] = _expand(target[key]);
}
return target;
function _expand(val) {
let expanded = val;
let match;
while (match = regexp.exec(val)) {
const varname = match[1];
const varval = vars[varname] || process.env[varname];
if (!varval) {
debug(`could not expand variable \${${varname}}`);
continue;
}
expanded = expanded.replace(`\${${varname}}`, varval);
}
return expanded;
}
} | javascript | {
"resource": ""
} |
q35215 | validateResponse | train | function validateResponse(schema, response, options, done) {
debug(`validating response for ${schema.endpoint}`);
// testing status code
if (schema.status) {
should(response.status).eql(schema.status);
}
return validator.compileAsync(schema).then((validate) => {
const valid = validate(response.body);
if (!valid) {
const errors = validate.errors;
should(errors).not.be.ok();
return done(errors);
}
if (schema.export) {
const body = response.body;
options.vars = options.vars || {};
for (let dest in schema.export) {
const propPath = schema.export[dest];
_.set(options.vars, dest, _.get(body, propPath));
}
}
return done(null, response);
}).catch(done);
} | javascript | {
"resource": ""
} |
q35216 | makeRequest | train | function makeRequest(baseUrl, method, schema, options, done) {
debug(`making ${method.toUpperCase()} request to ${schema.endpoint}`);
const endpoint = expandVars(schema.endpoint, options);
const apiPath = url.resolve(baseUrl + "/", _.trimStart(endpoint, "/"));
const headers = Object.assign({}, options.headers, schema.headers);
const query = Object.assign({}, options.query, schema.query);
const body = Object.assign({}, options.body, schema.body);
let req = request[getMethodFuncName(method)](apiPath);
// NOTE/deprecate: params
if (schema.params) {
deprecate("'params' property/extension in schema is deprecated. Use 'headers', 'query' or 'body' instead.");
req = req[getParamFuncName(method)](schema.params);
}
if (Object.keys(headers).length) {
expandVars(headers, options);
for (let key in headers) {
req = req.set(key, headers[key]);
}
}
if (Object.keys(query).length) {
expandVars(query, options);
req = req.query(query);
}
if (Object.keys(body).length) {
expandVars(body, options);
req = req.send(body);
}
return req.end(function(error, response) {
// catch network errors, etc.
if (!response) {
should(error).not.be.ok();
}
should(response).be.ok();
should(response.body).be.ok();
return validateResponse(schema, response, options, done);
});
} | javascript | {
"resource": ""
} |
q35217 | getNextSourceNode | train | function getNextSourceNode( node, startFromSibling, lastNode )
{
var next = node.getNextSourceNode( startFromSibling, null, lastNode );
while ( !bookmarkGuard( next ) )
next = next.getNextSourceNode( startFromSibling, null, lastNode );
return next;
} | javascript | {
"resource": ""
} |
q35218 | train | function( domObject, eventName )
{
return function( domEvent )
{
// In FF, when reloading the page with the editor focused, it may
// throw an error because the CKEDITOR global is not anymore
// available. So, we check it here first. (#2923)
if ( typeof CKEDITOR != 'undefined' )
domObject.fire( eventName, new CKEDITOR.dom.event( domEvent ) );
};
} | javascript | {
"resource": ""
} | |
q35219 | train | function()
{
var nativeListeners = this.getCustomData( '_cke_nativeListeners' );
for ( var eventName in nativeListeners )
{
var listener = nativeListeners[ eventName ];
if ( this.$.detachEvent )
this.$.detachEvent( 'on' + eventName, listener );
else if ( this.$.removeEventListener )
this.$.removeEventListener( eventName, listener, false );
delete nativeListeners[ eventName ];
}
} | javascript | {
"resource": ""
} | |
q35220 | train | function( languageCode, defaultLanguage, callback )
{
// If no languageCode - fallback to browser or default.
// If languageCode - fallback to no-localized version or default.
if ( !languageCode || !CKEDITOR.lang.languages[ languageCode ] )
languageCode = this.detect( defaultLanguage, languageCode );
if ( !this[ languageCode ] )
{
CKEDITOR.scriptLoader.load( CKEDITOR.getUrl(
'_source/' + // @Packager.RemoveLine
'lang/' + languageCode + '.js' ),
function()
{
callback( languageCode, this[ languageCode ] );
}
, this );
}
else
callback( languageCode, this[ languageCode ] );
} | javascript | {
"resource": ""
} | |
q35221 | train | function( defaultLanguage, probeLanguage )
{
var languages = this.languages;
probeLanguage = probeLanguage || navigator.userLanguage || navigator.language || defaultLanguage;
var parts = probeLanguage
.toLowerCase()
.match( /([a-z]+)(?:-([a-z]+))?/ ),
lang = parts[1],
locale = parts[2];
if ( languages[ lang + '-' + locale ] )
lang = lang + '-' + locale;
else if ( !languages[ lang ] )
lang = null;
CKEDITOR.lang.detect = lang ?
function() { return lang; } :
function( defaultLanguage ) { return defaultLanguage; };
return lang || defaultLanguage;
} | javascript | {
"resource": ""
} | |
q35222 | addFavicons | train | function addFavicons() {
var stream = new Transform({objectMode: true, highWaterMark: 2});
var hosts = {};
var downloads = [];
stream._transform = function (page, _, callback) {
stream.push(page);
var host = url.parse(page.url).host;
if (!hosts[host]) {
downloads.push(hosts[host] = download(url.resolve(page.url, '/favicon.ico')).then(function (result) {
if (result.statusCode === 200 &&
!(result.headers['content-type'] &&
result.headers['content-type'].indexOf('html') !== -1)) {
stream.push(result);
}
}, function () {
//ignore errors downloading favicons
}));
}
callback(null);
};
stream._flush = function (callback) {
Promise.all(downloads).done(function () {
callback();
}, function (err) {
stream.emit('error', err);
callback();
});
};
return stream;
} | javascript | {
"resource": ""
} |
q35223 | train | function( elementPath )
{
switch ( this.type )
{
case CKEDITOR.STYLE_BLOCK :
return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true );
case CKEDITOR.STYLE_OBJECT :
case CKEDITOR.STYLE_INLINE :
var elements = elementPath.elements;
for ( var i = 0, element ; i < elements.length ; i++ )
{
element = elements[ i ];
if ( this.type == CKEDITOR.STYLE_INLINE
&& ( element == elementPath.block || element == elementPath.blockLimit ) )
continue;
if( this.type == CKEDITOR.STYLE_OBJECT )
{
var name = element.getName();
if ( !( typeof this.element == 'string' ? name == this.element : name in this.element ) )
continue;
}
if ( this.checkElementRemovable( element, true ) )
return true;
}
}
return false;
} | javascript | {
"resource": ""
} | |
q35224 | train | function( elementPath )
{
switch ( this.type )
{
case CKEDITOR.STYLE_INLINE :
case CKEDITOR.STYLE_BLOCK :
break;
case CKEDITOR.STYLE_OBJECT :
return elementPath.lastElement.getAscendant( this.element, true );
}
return true;
} | javascript | {
"resource": ""
} | |
q35225 | train | function( label )
{
var styleDefinition = this._.definition,
html = [],
elementName = styleDefinition.element;
// Avoid <bdo> in the preview.
if ( elementName == 'bdo' )
elementName = 'span';
html = [ '<', elementName ];
// Assign all defined attributes.
var attribs = styleDefinition.attributes;
if ( attribs )
{
for ( var att in attribs )
{
html.push( ' ', att, '="', attribs[ att ], '"' );
}
}
// Assign the style attribute.
var cssStyle = CKEDITOR.style.getStyleText( styleDefinition );
if ( cssStyle )
html.push( ' style="', cssStyle, '"' );
html.push( '>', ( label || styleDefinition.name ), '</', elementName, '>' );
return html.join( '' );
} | javascript | {
"resource": ""
} | |
q35226 | removeFromInsideElement | train | function removeFromInsideElement( style, element )
{
var def = style._.definition,
attribs = def.attributes,
styles = def.styles,
overrides = getOverrides( style ),
innerElements = element.getElementsByTag( style.element );
for ( var i = innerElements.count(); --i >= 0 ; )
removeFromElement( style, innerElements.getItem( i ) );
// Now remove any other element with different name that is
// defined to be overriden.
for ( var overrideElement in overrides )
{
if ( overrideElement != style.element )
{
innerElements = element.getElementsByTag( overrideElement ) ;
for ( i = innerElements.count() - 1 ; i >= 0 ; i-- )
{
var innerElement = innerElements.getItem( i );
removeOverrides( innerElement, overrides[ overrideElement ] ) ;
}
}
}
} | javascript | {
"resource": ""
} |
q35227 | removeNoAttribsElement | train | function removeNoAttribsElement( element )
{
// If no more attributes remained in the element, remove it,
// leaving its children.
if ( !element.hasAttributes() )
{
if ( CKEDITOR.dtd.$block[ element.getName() ] )
{
var previous = element.getPrevious( nonWhitespaces ),
next = element.getNext( nonWhitespaces );
if ( previous && ( previous.type == CKEDITOR.NODE_TEXT || !previous.isBlockBoundary( { br : 1 } ) ) )
element.append( 'br', 1 );
if ( next && ( next.type == CKEDITOR.NODE_TEXT || !next.isBlockBoundary( { br : 1 } ) ) )
element.append( 'br' );
element.remove( true );
}
else
{
// Removing elements may open points where merging is possible,
// so let's cache the first and last nodes for later checking.
var firstChild = element.getFirst();
var lastChild = element.getLast();
element.remove( true );
if ( firstChild )
{
// Check the cached nodes for merging.
firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();
if ( lastChild && !firstChild.equals( lastChild )
&& lastChild.type == CKEDITOR.NODE_ELEMENT )
lastChild.mergeSiblings();
}
}
}
} | javascript | {
"resource": ""
} |
q35228 | getOverrides | train | function getOverrides( style )
{
if ( style._.overrides )
return style._.overrides;
var overrides = ( style._.overrides = {} ),
definition = style._.definition.overrides;
if ( definition )
{
// The override description can be a string, object or array.
// Internally, well handle arrays only, so transform it if needed.
if ( !CKEDITOR.tools.isArray( definition ) )
definition = [ definition ];
// Loop through all override definitions.
for ( var i = 0 ; i < definition.length ; i++ )
{
var override = definition[i];
var elementName;
var overrideEl;
var attrs;
// If can be a string with the element name.
if ( typeof override == 'string' )
elementName = override.toLowerCase();
// Or an object.
else
{
elementName = override.element ? override.element.toLowerCase() : style.element;
attrs = override.attributes;
}
// We can have more than one override definition for the same
// element name, so we attempt to simply append information to
// it if it already exists.
overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );
if ( attrs )
{
// The returning attributes list is an array, because we
// could have different override definitions for the same
// attribute name.
var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || new Array() );
for ( var attName in attrs )
{
// Each item in the attributes array is also an array,
// where [0] is the attribute name and [1] is the
// override value.
overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );
}
}
}
}
return overrides;
} | javascript | {
"resource": ""
} |
q35229 | normalizeProperty | train | function normalizeProperty( name, value, isStyle )
{
var temp = new CKEDITOR.dom.element( 'span' );
temp [ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );
return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );
} | javascript | {
"resource": ""
} |
q35230 | normalizeCssText | train | function normalizeCssText( unparsedCssText, nativeNormalize )
{
var styleText;
if ( nativeNormalize !== false )
{
// Injects the style in a temporary span object, so the browser parses it,
// retrieving its final format.
var temp = new CKEDITOR.dom.element( 'span' );
temp.setAttribute( 'style', unparsedCssText );
styleText = temp.getAttribute( 'style' ) || '';
}
else
styleText = unparsedCssText;
// Normalize font-family property, ignore quotes and being case insensitive. (#7322)
// http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property
styleText = styleText.replace( /(font-family:)(.*?)(?=;|$)/, function ( match, prop, val )
{
var names = val.split( ',' );
for ( var i = 0; i < names.length; i++ )
names[ i ] = CKEDITOR.tools.trim( names[ i ].replace( /["']/g, '' ) );
return prop + names.join( ',' );
});
// Shrinking white-spaces around colon and semi-colon (#4147).
// Compensate tail semi-colon.
return styleText.replace( /\s*([;:])\s*/, '$1' )
.replace( /([^\s;])$/, '$1;')
// Trimming spaces after comma(#4107),
// remove quotations(#6403),
// mostly for differences on "font-family".
.replace( /,\s+/g, ',' )
.replace( /\"/g,'' )
.toLowerCase();
} | javascript | {
"resource": ""
} |
q35231 | parseStyleText | train | function parseStyleText( styleText )
{
var retval = {};
styleText
.replace( /"/g, '"' )
.replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )
{
retval[ name ] = value;
} );
return retval;
} | javascript | {
"resource": ""
} |
q35232 | defaultApikey | train | function defaultApikey(apikey) {
if (typeof apikey !== 'undefined') {
if (typeof apikey !== 'string') {
throw new TypeError('`apikey` argument must be a string');
}
if (apikey.length !== 24) {
throw new TypeError('`apikey` argument must be 24 characters long');
}
return apikey;
}
throw new TypeError('Gandi client needs an apikey as a first argument');
} | javascript | {
"resource": ""
} |
q35233 | makeTempFile | train | function makeTempFile() {
const n = Math.floor(Math.random() * 100000)
const tempFile = path.join(os.tmpdir(), `node-exiftool_test_${n}.jpg`)
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(jpegFile)
const ws = fs.createWriteStream(tempFile)
rs.on('error', reject)
ws.on('error', reject)
ws.on('close', () => {
resolve(tempFile)
})
rs.pipe(ws)
})
} | javascript | {
"resource": ""
} |
q35234 | sortPaths | train | function sortPaths(items/* , [iteratee, ] dirSeparator */) {
assert(arguments.length >= 2, 'too few arguments');
assert(arguments.length <= 3, 'too many arguments');
var iteratee, dirSeparator;
if (arguments.length === 2) {
iteratee = identity;
dirSeparator = arguments[1];
}
else {
iteratee = arguments[1];
dirSeparator = arguments[2];
}
assert(isArray(items), 'items is not an array');
assert(isFunction(iteratee), 'iteratee is not a function');
assert(typeof dirSeparator === 'string', 'dirSeparator is not a String');
assert(dirSeparator.length === 1, 'dirSeparator must be a single character');
//encapsulate into DTOs
var itemDTOs = items.map(function (item) {
var path = iteratee(item);
assert(typeof path === 'string', 'item or iteratee(item) must be a String');
return {
item: item,
pathTokens: splitRetain(path, dirSeparator)
};
});
//sort DTOs
itemDTOs.sort(createItemDTOComparator(dirSeparator));
//decapsulate sorted DTOs and return
return itemDTOs.map(function (itemDTO) {
return itemDTO.item;
});
} | javascript | {
"resource": ""
} |
q35235 | setOptions | train | function setOptions(input) {
if (!isObject(input)) {
throw new Error('gtm.conf method expects a config object')
}
for (const key of ['debug', 'notify', 'parallel', 'strict']) {
const value = input[key]
if (typeof value === 'boolean') options[key] = value
else if (value != null) options[key] = strToBool(value)
}
for (const key of ['buildPrefix', 'watchPrefix']) {
const value = input[key]
if (typeof value === 'string') {
const trimmed = value.replace(/\s+/g, '')
if (trimmed !== '') options[key] = trimmed
}
}
if (isObject(input.groups)) {
for (const name of Object.keys(input.groups)) {
const value = input.groups[name]
if (typeof value === 'function' || Array.isArray(value)) {
options.groups[name] = value
} else if (!value) {
options.groups[name] = null // falsy values disable a group
}
}
}
} | javascript | {
"resource": ""
} |
q35236 | getElementForDirection | train | function getElementForDirection( node )
{
while ( node && !( node.getName() in allGuardElements || node.is( 'body' ) ) )
{
var parent = node.getParent();
if ( !parent )
break;
node = parent;
}
return node;
} | javascript | {
"resource": ""
} |
q35237 | contentHeight | train | function contentHeight( scrollable )
{
var overflowY = scrollable.getStyle( 'overflow-y' );
var doc = scrollable.getDocument();
// Create a temporary marker element.
var marker = CKEDITOR.dom.element.createFromHtml( '<span style="margin:0;padding:0;border:0;clear:both;width:1px;height:1px;display:block;">' + ( CKEDITOR.env.webkit ? ' ' : '' ) + '</span>', doc );
doc[ CKEDITOR.env.ie? 'getBody' : 'getDocumentElement']().append( marker );
var height = marker.getDocumentPosition( doc ).y + marker.$.offsetHeight;
marker.remove();
scrollable.setStyle( 'overflow-y', overflowY );
return height;
} | javascript | {
"resource": ""
} |
q35238 | ValueMapper | train | function ValueMapper(input, options) {
// Save input for later
this.input = input;
// Save placeholder middlewares
this.middlewares = [];
// Fallback options
options = options || {};
// Add each of the middlewares
var middlewares = options.middlewares || [];
middlewares.forEach(this.addMiddleware, this);
} | javascript | {
"resource": ""
} |
q35239 | train | function (key) {
// Assume the middleware is a function
var middleware = key;
// If the middleware is a string
if (typeof middleware === 'string') {
// Look it up and assert it was found
middleware = MIDDLEWARES[key];
assert(middleware, 'value-mapper middleware "' + key + '" could not be found."');
}
// Add the middleware to our stack
this.middlewares.push(middleware);
} | javascript | {
"resource": ""
} | |
q35240 | train | function (val) {
// Keep track of aliases used
var aliasesUsed = [],
aliasesNotFound = [],
that = this;
// Map the value through the middlewares
var middlewares = this.middlewares;
middlewares.forEach(function mapMiddlewareValue (fn) {
// Process the value through middleware
var valObj = fn.call(that, val);
// Save the results
val = valObj.value;
aliasesUsed.push.apply(aliasesUsed, valObj.aliasesUsed);
aliasesNotFound.push.apply(aliasesNotFound, valObj.aliasesNotFound);
});
// Return the value
return {
value: val,
aliasesUsed: aliasesUsed,
aliasesNotFound: aliasesNotFound
};
} | javascript | {
"resource": ""
} | |
q35241 | train | function (key) {
// Look up the normal value
var val = this.input[key];
// Save the key for reference
var _key = this.key;
this.key = key;
// Map our value through the middlewares
val = this.process(val);
// Restore the original key
this.key = _key;
// Return the value
return val;
} | javascript | {
"resource": ""
} | |
q35242 | render | train | function render(content) {
var deferred = q.defer();
var blockType = "normal";
var lines = content.split("\n");
var blocks = {};
for (var i=0; i<lines.length; i++) {
var line = lines[i];
if (line.substr(0,1) == "@") {
blockType = line.substr(1).trim();
if (blockType === "end") blockType = "normal";
continue;
}
if (blocks[blockType])
blocks[blockType] += line + "\n";
else
blocks[blockType] = line + "\n";
}
for (var key in blocks) {
if (blocks.hasOwnProperty(key)) {
try {
blocks[key] = metaMarked(blocks[key]);
} catch(err) {
return deferred.reject(new Error(err));
}
}
deferred.resolve(blocks);
}
return deferred.promise;
} | javascript | {
"resource": ""
} |
q35243 | splitInput | train | function splitInput(str) {
if (str.slice(0, 3) !== '---') return;
var matcher = /\n(\.{3}|-{3})/g;
var metaEnd = matcher.exec(str);
return metaEnd && [str.slice(0, metaEnd.index), str.slice(matcher.lastIndex)];
} | javascript | {
"resource": ""
} |
q35244 | train | function( range )
{
range.collapsed = (
range.startContainer &&
range.endContainer &&
range.startContainer.equals( range.endContainer ) &&
range.startOffset == range.endOffset );
} | javascript | {
"resource": ""
} | |
q35245 | train | function( mergeThen )
{
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
if ( !this.collapsed )
execContentsAction( this, 1, docFrag, mergeThen );
return docFrag;
} | javascript | {
"resource": ""
} | |
q35246 | train | function( normalized )
{
var startContainer = this.startContainer,
endContainer = this.endContainer;
var startOffset = this.startOffset,
endOffset = this.endOffset;
var collapsed = this.collapsed;
var child, previous;
// If there is no range then get out of here.
// It happens on initial load in Safari #962 and if the editor it's
// hidden also in Firefox
if ( !startContainer || !endContainer )
return { start : 0, end : 0 };
if ( normalized )
{
// Find out if the start is pointing to a text node that will
// be normalized.
if ( startContainer.type == CKEDITOR.NODE_ELEMENT )
{
child = startContainer.getChild( startOffset );
// In this case, move the start information to that text
// node.
if ( child && child.type == CKEDITOR.NODE_TEXT
&& startOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT )
{
startContainer = child;
startOffset = 0;
}
// Get the normalized offset.
if ( child && child.type == CKEDITOR.NODE_ELEMENT )
startOffset = child.getIndex( 1 );
}
// Normalize the start.
while ( startContainer.type == CKEDITOR.NODE_TEXT
&& ( previous = startContainer.getPrevious() )
&& previous.type == CKEDITOR.NODE_TEXT )
{
startContainer = previous;
startOffset += previous.getLength();
}
// Process the end only if not normalized.
if ( !collapsed )
{
// Find out if the start is pointing to a text node that
// will be normalized.
if ( endContainer.type == CKEDITOR.NODE_ELEMENT )
{
child = endContainer.getChild( endOffset );
// In this case, move the start information to that
// text node.
if ( child && child.type == CKEDITOR.NODE_TEXT
&& endOffset > 0 && child.getPrevious().type == CKEDITOR.NODE_TEXT )
{
endContainer = child;
endOffset = 0;
}
// Get the normalized offset.
if ( child && child.type == CKEDITOR.NODE_ELEMENT )
endOffset = child.getIndex( 1 );
}
// Normalize the end.
while ( endContainer.type == CKEDITOR.NODE_TEXT
&& ( previous = endContainer.getPrevious() )
&& previous.type == CKEDITOR.NODE_TEXT )
{
endContainer = previous;
endOffset += previous.getLength();
}
}
}
return {
start : startContainer.getAddress( normalized ),
end : collapsed ? null : endContainer.getAddress( normalized ),
startOffset : startOffset,
endOffset : endOffset,
normalized : normalized,
collapsed : collapsed,
is2 : true // It's a createBookmark2 bookmark.
};
} | javascript | {
"resource": ""
} | |
q35247 | train | function()
{
var container = this.startContainer;
var offset = this.startOffset;
if ( container.type != CKEDITOR.NODE_ELEMENT )
{
if ( !offset )
this.setStartBefore( container );
else if ( offset >= container.getLength() )
this.setStartAfter( container );
}
container = this.endContainer;
offset = this.endOffset;
if ( container.type != CKEDITOR.NODE_ELEMENT )
{
if ( !offset )
this.setEndBefore( container );
else if ( offset >= container.getLength() )
this.setEndAfter( container );
}
} | javascript | {
"resource": ""
} | |
q35248 | train | function()
{
var startNode = this.startContainer,
endNode = this.endContainer;
if ( startNode.is && startNode.is( 'span' )
&& startNode.data( 'cke-bookmark' ) )
this.setStartAt( startNode, CKEDITOR.POSITION_BEFORE_START );
if ( endNode && endNode.is && endNode.is( 'span' )
&& endNode.data( 'cke-bookmark' ) )
this.setEndAt( endNode, CKEDITOR.POSITION_AFTER_END );
} | javascript | {
"resource": ""
} | |
q35249 | train | function( element, checkType )
{
var checkStart = ( checkType == CKEDITOR.START );
// Create a copy of this range, so we can manipulate it for our checks.
var walkerRange = this.clone();
// Collapse the range at the proper size.
walkerRange.collapse( checkStart );
// Expand the range to element boundary.
walkerRange[ checkStart ? 'setStartAt' : 'setEndAt' ]
( element, checkStart ? CKEDITOR.POSITION_AFTER_START : CKEDITOR.POSITION_BEFORE_END );
// Create the walker, which will check if we have anything useful
// in the range.
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = elementBoundaryEval;
return walker[ checkStart ? 'checkBackward' : 'checkForward' ]();
} | javascript | {
"resource": ""
} | |
q35250 | train | function()
{
var startContainer = this.startContainer,
startOffset = this.startOffset;
// If the starting node is a text node, and non-empty before the offset,
// then we're surely not at the start of block.
if ( startOffset && startContainer.type == CKEDITOR.NODE_TEXT )
{
var textBefore = CKEDITOR.tools.ltrim( startContainer.substring( 0, startOffset ) );
if ( textBefore.length )
return false;
}
// Antecipate the trim() call here, so the walker will not make
// changes to the DOM, which would not get reflected into this
// range otherwise.
this.trim();
// We need to grab the block element holding the start boundary, so
// let's use an element path for it.
var path = new CKEDITOR.dom.elementPath( this.startContainer );
// Creates a range starting at the block start until the range start.
var walkerRange = this.clone();
walkerRange.collapse( true );
walkerRange.setStartAt( path.block || path.blockLimit, CKEDITOR.POSITION_AFTER_START );
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = getCheckStartEndBlockEvalFunction( true );
return walker.checkBackward();
} | javascript | {
"resource": ""
} | |
q35251 | authorizedHandler | train | function authorizedHandler(value) {
if (! value) return value;
delete value.public_id;
delete value.version;
delete value.signature;
delete value.resource_type;
return value;
} | javascript | {
"resource": ""
} |
q35252 | sendFile | train | function sendFile(params) {
const p = params;
checkParams(params);
fs.lstat(p.name, (error, stat) => {
if (error)
return sendError(error, params);
const isGzip = isGZIP(p.request) && p.gzip;
const time = stat.mtime.toUTCString();
const length = stat.size;
const range = getRange(p.request, length);
if (range)
assign(p, {
range,
status: RANGE
});
assign(p, {
time
});
if (!isGzip)
p.length = length;
setHeader(params);
const options = {
gzip : isGzip,
range,
};
files.pipe(p.name, p.response, options).catch((error) => {
sendError(error, params);
});
});
} | javascript | {
"resource": ""
} |
q35253 | sendError | train | function sendError(error, params) {
checkParams(params);
params.status = FILE_NOT_FOUND;
const data = error.message || String(error);
logError(error.stack);
send(data, params);
} | javascript | {
"resource": ""
} |
q35254 | redirect | train | function redirect(url, response) {
const header = {
'Location': url
};
assert(url, 'url could not be empty!');
assert(response, 'response could not be empty!');
fillHeader(header, response);
response.statusCode = MOVED_PERMANENTLY;
response.end();
} | javascript | {
"resource": ""
} |
q35255 | levenshtein | train | function levenshtein( source, target ) {
var s = source.length
var t = target.length
if( s === 0 ) return t
if( t === 0 ) return s
var i, k, matrix = []
for( i = 0; i <= t; i++ ) {
matrix[i] = [ i ]
}
for( k = 0; k <= s; k++ )
matrix[0][k] = k
for( i = 1; i <= t; i++ ) {
for( k = 1; k <= s; k++ ) {
( target.charAt( i - 1 ) === source.charAt( k - 1 ) )
? matrix[i][k] = matrix[ i - 1 ][ k - 1 ]
: matrix[i][k] = Math.min(
matrix[ i - 1 ][ k - 1 ] + 1,
Math.min(
matrix[i][ k - 1 ] + 1,
matrix[ i - 1 ][k] + 1
)
)
}
}
return matrix[t][s]
} | javascript | {
"resource": ""
} |
q35256 | train | function( name )
{
var external = this.externals[ name ];
return CKEDITOR.getUrl( ( external && external.dir ) || this.basePath + name + '/' );
} | javascript | {
"resource": ""
} | |
q35257 | train | function( name )
{
var external = this.externals[ name ];
return CKEDITOR.getUrl(
this.getPath( name ) +
( ( external && ( typeof external.file == 'string' ) ) ? external.file : this.fileName + '.js' ) );
} | javascript | {
"resource": ""
} | |
q35258 | train | function( names, path, fileName )
{
names = names.split( ',' );
for ( var i = 0 ; i < names.length ; i++ )
{
var name = names[ i ];
this.externals[ name ] =
{
dir : path,
file : fileName
};
}
} | javascript | {
"resource": ""
} | |
q35259 | postProcessList | train | function postProcessList( list )
{
var children = list.children,
child,
attrs,
count = list.children.length,
match,
mergeStyle,
styleTypeRegexp = /list-style-type:(.*?)(?:;|$)/,
stylesFilter = CKEDITOR.plugins.pastefromword.filters.stylesFilter;
attrs = list.attributes;
if ( styleTypeRegexp.exec( attrs.style ) )
return;
for ( var i = 0; i < count; i++ )
{
child = children[ i ];
if ( child.attributes.value && Number( child.attributes.value ) == i + 1 )
delete child.attributes.value;
match = styleTypeRegexp.exec( child.attributes.style );
if ( match )
{
if ( match[ 1 ] == mergeStyle || !mergeStyle )
mergeStyle = match[ 1 ];
else
{
mergeStyle = null;
break;
}
}
}
if ( mergeStyle )
{
for ( i = 0; i < count; i++ )
{
attrs = children[ i ].attributes;
attrs.style && ( attrs.style = stylesFilter( [ [ 'list-style-type'] ] )( attrs.style ) || '' );
}
list.addStyle( 'list-style-type', mergeStyle );
}
} | javascript | {
"resource": ""
} |
q35260 | fromRoman | train | function fromRoman( str )
{
str = str.toUpperCase();
var l = romans.length, retVal = 0;
for ( var i = 0; i < l; ++i )
{
for ( var j = romans[i], k = j[1].length; str.substr( 0, k ) == j[1]; str = str.substr( k ) )
retVal += j[ 0 ];
}
return retVal;
} | javascript | {
"resource": ""
} |
q35261 | fromAlphabet | train | function fromAlphabet( str )
{
str = str.toUpperCase();
var l = alpahbets.length, retVal = 1;
for ( var x = 1; str.length > 0; x *= l )
{
retVal += alpahbets.indexOf( str.charAt( str.length - 1 ) ) * x;
str = str.substr( 0, str.length - 1 );
}
return retVal;
} | javascript | {
"resource": ""
} |
q35262 | train | function ( styleDefiniton, variables )
{
return function( element )
{
var styleDef =
variables ?
new CKEDITOR.style( styleDefiniton, variables )._.definition
: styleDefiniton;
element.name = styleDef.element;
CKEDITOR.tools.extend( element.attributes, CKEDITOR.tools.clone( styleDef.attributes ) );
element.addStyle( CKEDITOR.style.getStyleText( styleDef ) );
};
} | javascript | {
"resource": ""
} | |
q35263 | train | function( styleDefinition, variableName )
{
var elementMigrateFilter = this.elementMigrateFilter;
return function( value, element )
{
// Build an stylish element first.
var styleElement = new CKEDITOR.htmlParser.element( null ),
variables = {};
variables[ variableName ] = value;
elementMigrateFilter( styleDefinition, variables )( styleElement );
// Place the new element inside the existing span.
styleElement.children = element.children;
element.children = [ styleElement ];
};
} | javascript | {
"resource": ""
} | |
q35264 | train | function( element )
{
if ( CKEDITOR.env.gecko )
{
// Grab only the style definition section.
var styleDefSection = element.onlyChild().value.match( /\/\* Style Definitions \*\/([\s\S]*?)\/\*/ ),
styleDefText = styleDefSection && styleDefSection[ 1 ],
rules = {}; // Storing the parsed result.
if ( styleDefText )
{
styleDefText
// Remove line-breaks.
.replace(/[\n\r]/g,'')
// Extract selectors and style properties.
.replace( /(.+?)\{(.+?)\}/g,
function( rule, selectors, styleBlock )
{
selectors = selectors.split( ',' );
var length = selectors.length, selector;
for ( var i = 0; i < length; i++ )
{
// Assume MS-Word mostly generate only simple
// selector( [Type selector][Class selector]).
CKEDITOR.tools.trim( selectors[ i ] )
.replace( /^(\w+)(\.[\w-]+)?$/g,
function( match, tagName, className )
{
tagName = tagName || '*';
className = className.substring( 1, className.length );
// Reject MS-Word Normal styles.
if ( className.match( /MsoNormal/ ) )
return;
if ( !rules[ tagName ] )
rules[ tagName ] = {};
if ( className )
rules[ tagName ][ className ] = styleBlock;
else
rules[ tagName ] = styleBlock;
} );
}
});
filters.applyStyleFilter = function( element )
{
var name = rules[ '*' ] ? '*' : element.name,
className = element.attributes && element.attributes[ 'class' ],
style;
if ( name in rules )
{
style = rules[ name ];
if ( typeof style == 'object' )
style = style[ className ];
// Maintain style rules priorities.
style && element.addStyle( style, true );
}
};
}
}
return false;
} | javascript | {
"resource": ""
} | |
q35265 | initStream | train | function initStream(options) {
if (!_.isObject(options)) {
options = {};
}
return through.obj(function(chunk, enc, cb) {
var compilerOptions = chunk[FIELD_NAME] || {};
compilerOptions = _.merge(compilerOptions, options);
if (options.progress === true) {
compilerOptions.progress = progressCallback;
}
chunk[FIELD_NAME] = compilerOptions;
cb(null, chunk);
});
} | javascript | {
"resource": ""
} |
q35266 | BaseTypeHandler | train | function BaseTypeHandler(ksTypeName, handlers) {
this.ksTypeName = ksTypeName;
if ("function" === typeof handlers) {
this.handlers = {default: handlers};
}
else {
this.handlers = _.extend({}, handlers);
}
} | javascript | {
"resource": ""
} |
q35267 | onExit | train | function onExit() {
if (!onExit.done) {
if (options.strict !== true) showLoadingErrors()
if (options.debug === true) showDebugInfo()
}
onExit.done = true
} | javascript | {
"resource": ""
} |
q35268 | showDebugInfo | train | function showDebugInfo() {
customLog(`gulp-task-maker options:\n${util.inspect(options)}`)
for (const data of scripts) {
const info = {
callback: data.callback,
configs: data.normalizedConfigs,
errors: data.errors
}
customLog(
`gulp-task-maker script '${data.name}':\n${util.inspect(info, {
depth: 6
})}`
)
}
} | javascript | {
"resource": ""
} |
q35269 | handleError | train | function handleError(err, store) {
if (err && !err.plugin) {
err.plugin = 'gulp-task-maker'
}
if (Array.isArray(store)) {
store.push(err)
} else {
showError(err)
}
} | javascript | {
"resource": ""
} |
q35270 | train | function( editor )
{
var hr = editor.document.createElement( 'hr' ),
range = new CKEDITOR.dom.range( editor.document );
editor.insertElement( hr );
// If there's nothing or a non-editable block followed by, establish a new paragraph
// to make sure cursor is not trapped.
range.moveToPosition( hr, CKEDITOR.POSITION_AFTER_END );
var next = hr.getNext();
if ( !next || next.type == CKEDITOR.NODE_ELEMENT && !next.isEditable() )
range.fixBlock( true, editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
range.select();
} | javascript | {
"resource": ""
} | |
q35271 | findSquaredDistanceBetweenSegments | train | function findSquaredDistanceBetweenSegments(segmentA, segmentB) {
findClosestPointsFromSegmentToSegment(_segmentDistance_tmpVecA, _segmentDistance_tmpVecB,
segmentA, segmentB);
return vec3.squaredDistance(_segmentDistance_tmpVecA, _segmentDistance_tmpVecB);
} | javascript | {
"resource": ""
} |
q35272 | findSquaredDistanceFromSegmentToPoint | train | function findSquaredDistanceFromSegmentToPoint(segment, point) {
findClosestPointOnSegmentToPoint(_segmentDistance_tmpVecA, segment, point);
return vec3.squaredDistance(_segmentDistance_tmpVecA, point);
} | javascript | {
"resource": ""
} |
q35273 | findPoiBetweenSegmentAndPlaneRegion | train | function findPoiBetweenSegmentAndPlaneRegion(poi, segment, planeVertex1, planeVertex2, planeVertex3,
planeVertex4) {
return findPoiBetweenSegmentAndTriangle(poi, segment, planeVertex1, planeVertex2, planeVertex3) ||
findPoiBetweenSegmentAndTriangle(poi, segment, planeVertex1, planeVertex3, planeVertex4);
} | javascript | {
"resource": ""
} |
q35274 | findPoiBetweenSegmentAndTriangle | train | function findPoiBetweenSegmentAndTriangle(poi, segment, triangleVertex1, triangleVertex2,
triangleVertex3) {
//
// Find the point of intersection between the segment and the triangle's plane.
//
// First triangle edge.
vec3.subtract(_tmpVec1, triangleVertex2, triangleVertex1);
// Second triangle edge.
vec3.subtract(_tmpVec2, triangleVertex3, triangleVertex1);
// Triangle normal.
vec3.cross(_tmpVec3, _tmpVec1, _tmpVec2);
// Triangle to segment.
vec3.subtract(_tmpVec4, segment.start, triangleVertex1);
const normalToSegmentProj = vec3.dot(_tmpVec3, segment.dir);
if (normalToSegmentProj < EPSILON && normalToSegmentProj > -EPSILON) {
// The line segment is parallel to the triangle.
return false;
}
const normalToDiffProj = -vec3.dot(_tmpVec3, _tmpVec4);
const segmentNormalizedDistance = normalToDiffProj / normalToSegmentProj;
if (segmentNormalizedDistance < 0 || segmentNormalizedDistance > 1) {
// The line segment ends before intersecting the plane.
return false;
}
vec3.scaleAndAdd(poi, segment.start, segment.dir, segmentNormalizedDistance);
//
// Determine whether the point of intersection lies within the triangle.
//
const edge1DotEdge1 = vec3.dot(_tmpVec1, _tmpVec1);
const edge1DotEdge2 = vec3.dot(_tmpVec1, _tmpVec2);
const edge2DotEdge2 = vec3.dot(_tmpVec2, _tmpVec2);
// Triangle to point of intersection.
vec3.subtract(_tmpVec3, poi, triangleVertex1);
const diffDotEdge1 = vec3.dot(_tmpVec3, _tmpVec1);
const diffDotEdge2 = vec3.dot(_tmpVec3, _tmpVec2);
const denominator = edge1DotEdge2 * edge1DotEdge2 - edge1DotEdge1 * edge2DotEdge2;
// Check the triangle's parametric coordinates.
const s = (edge1DotEdge2 * diffDotEdge2 - edge2DotEdge2 * diffDotEdge1) / denominator;
if (s < 0 || s > 1) {
return false;
}
const t = (edge1DotEdge2 * diffDotEdge1 - edge1DotEdge1 * diffDotEdge2) / denominator;
if (t < 0 || s + t > 1) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q35275 | findClosestPointsFromSegmentToSegment | train | function findClosestPointsFromSegmentToSegment(closestA, closestB, segmentA, segmentB) {
const {distA, distB} = findClosestPointsFromLineToLine(
segmentA.start, segmentA.dir, segmentB.start, segmentB.dir);
const isDistAInBounds = distA >= 0 && distA <= 1;
const isDistBInBounds = distB >= 0 && distB <= 1;
if (isDistAInBounds) {
if (isDistBInBounds) {
// The distances along both line segments are within bounds.
vec3.scaleAndAdd(closestA, segmentA.start, segmentA.dir, distA);
vec3.scaleAndAdd(closestB, segmentB.start, segmentB.dir, distB);
} else {
// Only the distance along the first line segment is within bounds.
if (distB < 0) {
vec3.copy(closestB, segmentB.start);
} else {
vec3.copy(closestB, segmentB.end);
}
findClosestPointOnSegmentToPoint(closestA, segmentA, closestB);
}
} else {
if (isDistBInBounds) {
// Only the distance along the second line segment is within bounds.
if (distA < 0) {
vec3.copy(closestA, segmentA.start);
} else {
vec3.copy(closestA, segmentA.end);
}
findClosestPointOnSegmentToPoint(closestB, segmentB, closestA);
} else {
// Neither of the distances along either line segment are within bounds.
if (distA < 0) {
vec3.copy(closestA, segmentA.start);
} else {
vec3.copy(closestA, segmentA.end);
}
if (distB < 0) {
vec3.copy(closestB, segmentB.start);
} else {
vec3.copy(closestB, segmentB.end);
}
const altClosestA = vec3.create();
const altClosestB = vec3.create();
findClosestPointOnSegmentToPoint(altClosestA, segmentA, closestB);
findClosestPointOnSegmentToPoint(altClosestB, segmentB, closestA);
if (vec3.squaredDistance(altClosestA, closestB) <
vec3.squaredDistance(altClosestB, closestA)) {
vec3.copy(closestA, altClosestA);
} else {
vec3.copy(closestB, altClosestB);
}
}
}
} | javascript | {
"resource": ""
} |
q35276 | findClosestPointOnSegmentToPoint | train | function findClosestPointOnSegmentToPoint(closestPoint, segment, point) {
const dirSquaredLength = vec3.squaredLength(segment.dir);
if (!dirSquaredLength) {
// The point is at the segment start.
vec3.copy(closestPoint, segment.start);
} else {
// Calculate the projection of the point onto the line extending through the segment.
vec3.subtract(_tmpVec1, point, segment.start);
const t = vec3.dot(_tmpVec1, segment.dir) / dirSquaredLength;
if (t < 0) {
// The point projects beyond the segment start.
vec3.copy(closestPoint, segment.start);
} else if (t > 1) {
// The point projects beyond the segment end.
vec3.copy(closestPoint, segment.end);
} else {
// The point projects between the start and end of the segment.
vec3.scaleAndAdd(closestPoint, segment.start, segment.dir, t);
}
}
} | javascript | {
"resource": ""
} |
q35277 | findClosestPointsFromLineToLine | train | function findClosestPointsFromLineToLine(startA, dirA, startB, dirB) {
vec3.subtract(_tmpVec1, startA, startB);
const dirBDotDirAToB = vec3.dot(dirB, _tmpVec1);
const dirADotDirAToB = vec3.dot(dirA, _tmpVec1);
const sqrLenDirB = vec3.squaredLength(dirB);
const sqrLenDirA = vec3.squaredLength(dirA);
const dirADotDirB = vec3.dot(dirA, dirB);
const denominator = sqrLenDirA * sqrLenDirB - dirADotDirB * dirADotDirB;
const distA = denominator < EPSILON
? 0
: (dirADotDirB * dirBDotDirAToB - sqrLenDirB * dirADotDirAToB) / denominator;
const distB = (dirBDotDirAToB + dirADotDirB * distA) / sqrLenDirB;
return {
distA: distA,
distB: distB
};
} | javascript | {
"resource": ""
} |
q35278 | handleCollisionsForJob | train | function handleCollisionsForJob(job, elapsedTime, physicsParams) {
const collidable = job.collidable;
// Clear any previous collision info.
collidable.previousCollisions = collidable.collisions;
collidable.collisions = [];
// Find all colliding collidables.
const collidingCollidables = findIntersectingCollidablesForCollidable(collidable);
// Store the time of collision for each collision.
const collisions = _recordCollisions(collidable, collidingCollidables, elapsedTime);
// Calculate the points of contact for each collision.
_calculatePointsOfContact(collisions);
// Collision resolution.
_resolveCollisions(collisions, physicsParams);
} | javascript | {
"resource": ""
} |
q35279 | checkThatNoObjectsCollide | train | function checkThatNoObjectsCollide() {
// Broad-phase collision detection (pairs whose bounding volumes intersect).
let collisions = collidableStore.getPossibleCollisionsForAllCollidables();
// Narrow-phase collision detection (pairs that actually intersect).
collisions = _detectPreciseCollisionsFromCollisions(collisions);
collisions.forEach(collision => {
console.warn('Objects still intersect after collision resolution', collision);
});
} | javascript | {
"resource": ""
} |
q35280 | _recordCollisions | train | function _recordCollisions(collidable, collidingCollidables, elapsedTime) {
return collidingCollidables.map(other => {
const collision = {
collidableA: collidable,
collidableB: other,
time: elapsedTime
};
// Record the fact that these objects collided (the ModelController may want to handle this).
collision.collidableA.collisions.push(collision);
collision.collidableB.collisions.push(collision);
return collision;
});
} | javascript | {
"resource": ""
} |
q35281 | _detectPreciseCollisionsFromCollisions | train | function _detectPreciseCollisionsFromCollisions(collisions) {
return collisions.filter(collision => {
// TODO:
// - Use temporal bisection with discrete sub-time steps to find time of collision (use
// x-vs-y-specific intersection detection methods).
// - Make sure the collision object is set up with the "previousState" from the sub-step
// before collision and the time from the sub-step after collision (determined from the
// previous temporal bisection search...)
return detectIntersection(collision.collidableA, collision.collidableB);
});
} | javascript | {
"resource": ""
} |
q35282 | _resolveCollisions | train | function _resolveCollisions(collisions, physicsParams) {
collisions.forEach(collision => {
// If neither physics job needs the standard collision restitution, then don't do it.
if (_notifyPhysicsJobsOfCollision(collision)) {
if (collision.collidableA.physicsJob && collision.collidableB.physicsJob) {
// Neither of the collidables is stationary.
_resolveCollision(collision, physicsParams);
} else {
// One of the two collidables is stationary.
_resolveCollisionWithStationaryObject(collision, physicsParams);
}
}
});
} | javascript | {
"resource": ""
} |
q35283 | _resolveCollision | train | function _resolveCollision(collision, physicsParams) {
const collidableA = collision.collidableA;
const collidableB = collision.collidableB;
const previousStateA = collidableA.physicsJob.previousState;
const previousStateB = collidableB.physicsJob.previousState;
const nextStateA = collidableA.physicsJob.currentState;
const nextStateB = collidableB.physicsJob.currentState;
const centerA = collidableA.centerOfMass;
const centerB = collidableB.centerOfMass;
const contactPoint = collision.contactPoint;
const contactPointOffsetA = tmpVec3;
vec3.subtract(contactPointOffsetA, contactPoint, centerA);
const contactPointOffsetB = tmpVec4;
vec3.subtract(contactPointOffsetB, contactPoint, centerB);
//
// Calculate the relative velocity of the bodies at the point of contact.
//
// We use the velocity from the previous state, since it is the velocity that led to the
// collision.
//
const velocityA = tmpVec1;
vec3.cross(tmpVec1, previousStateA.angularVelocity, contactPointOffsetA);
vec3.add(velocityA, previousStateA.velocity, tmpVec1);
const velocityB = tmpVec2;
vec3.cross(tmpVec2, previousStateB.angularVelocity, contactPointOffsetB);
vec3.add(velocityB, previousStateB.velocity, tmpVec2);
const relativeVelocity = vec3.create();
vec3.subtract(relativeVelocity, velocityB, velocityA);
if (vec3.dot(relativeVelocity, collision.contactNormal) >= 0) {
// If the relative velocity is not pointing against the normal, then the normal was calculated
// incorrectly (this is likely due to the time step being too large and the fact that our
// contact calculations don't consider velocity). So update the contact normal to be in the
// direction of the relative velocity.
// TODO: Check that this works as expected.
// console.warn('Non-collision because objects are moving away from each other.');
vec3.copy(collision.contactNormal, relativeVelocity);
vec3.normalize(collision.contactNormal, collision.contactNormal);
vec3.negate(collision.contactNormal, collision.contactNormal);
}
_applyImpulseFromCollision(collision, relativeVelocity, contactPointOffsetA,
contactPointOffsetB, physicsParams);
// NOTE: This state reversion is only applied to collidableA. This assumes that only A is moving
// during this iteration of the collision pipeline.
// Revert to the position and orientation from immediately before the collision.
vec3.copy(nextStateA.position, previousStateA.position);
quat.copy(nextStateA.orientation, previousStateA.orientation);
// Also revert the collidables' position and orientation.
collidableA.position = previousStateA.position;
collidableA.orientation = previousStateA.orientation;
nextStateA.updateDependentFields();
nextStateB.updateDependentFields();
} | javascript | {
"resource": ""
} |
q35284 | _resolveCollisionWithStationaryObject | train | function _resolveCollisionWithStationaryObject(collision, physicsParams) {
const contactNormal = collision.contactNormal;
let physicsCollidable;
if (collision.collidableA.physicsJob) {
physicsCollidable = collision.collidableA;
} else {
physicsCollidable = collision.collidableB;
vec3.negate(contactNormal, contactNormal);
}
const previousState = physicsCollidable.physicsJob.previousState;
const nextState = physicsCollidable.physicsJob.currentState;
const center = physicsCollidable.centerOfMass;
const contactPoint = collision.contactPoint;
const contactPointOffset = tmpVec3;
vec3.subtract(contactPointOffset, contactPoint, center);
// Calculate the relative velocity of the bodies at the point of contact. We use the velocity from
// the previous state, since it is the velocity that led to the collision.
const velocity = vec3.create();
vec3.cross(tmpVec1, previousState.angularVelocity, contactPointOffset);
vec3.add(velocity, previousState.velocity, tmpVec1);
if (vec3.dot(velocity, contactNormal) <= 0) {
// If the relative velocity is not pointing against the normal, then the normal was calculated
// incorrectly (this is likely due to the time step being too large and the fact that our
// contact calculations don't consider velocity). So update the contact normal to be in the
// direction of the relative velocity.
// TODO: Check that this works as expected.
console.warn('Non-collision because object is moving away from stationary object.');
vec3.copy(collision.contactNormal, velocity);
vec3.normalize(collision.contactNormal, collision.contactNormal);
vec3.negate(collision.contactNormal, collision.contactNormal);
}
_applyImpulseFromCollisionWithStationaryObject(physicsCollidable, collision, velocity,
contactPointOffset, physicsParams);
// Revert to the position and orientation from immediately before the collision.
vec3.copy(nextState.position, previousState.position);
quat.copy(nextState.orientation, previousState.orientation);
// Also revert the collidable's position and orientation.
physicsCollidable.position = previousState.position;
physicsCollidable.orientation = previousState.orientation;
nextState.updateDependentFields();
} | javascript | {
"resource": ""
} |
q35285 | proxyStream | train | function proxyStream(err, stats) {
return through.obj(function(chunk, enc, cb) {
processStats.call(this, chunk, stats);
if (_.isError(err)) {
this.emit('error', wrapError(err));
}
cb(null, chunk);
});
} | javascript | {
"resource": ""
} |
q35286 | run | train | function run(env) {
console.log(); // empty line
var verbfile = env.configPath;
if (versionFlag && tasks.length === 0) {
verbLog('CLI version', pkg.version);
if (env.modulePackage && typeof env.modulePackage.version !== 'undefined') {
verbLog('Local version', env.modulePackage.version);
}
}
// `node_modules/verb`
if (!env.modulePath || !fs.existsSync(env.modulePath)) {
/* deps: verb */
env.modulePath = resolve.sync('verb');
}
// chdir before requiring `verbfile.js` to allow users to chdir as needed
if (process.cwd() !== env.cwd) {
process.chdir(env.cwd);
verbLog('working directory changed to', tildify(env.cwd));
}
// require verb
var verbInst = require(env.modulePath);
verbInst.extend('argv', argv);
verbInst.emit('loaded');
if (!argv._.length && argv.no) {
exit(0);
}
// `verbfile.js`
if ((hasVerbmd && !hasVerbfile) || !verbfile) {
verbfile = resolve.sync('verb-default');
env.configBase = path.dirname(env.configBase);
require(verbfile)(verbInst);
} else {
// this is what actually loads up the verbfile
require(verbfile);
}
verbLog('using verbfile', tildify(verbfile));
logEvents(verbInst);
process.nextTick(function () {
if (simpleTasksFlag) {
return logTasksSimple(env, verbInst);
}
if (tasksFlag) {
return logTasks(env, verbInst);
}
verbInst.run(toRun, function (err) {
if (err) console.error(err);
});
});
} | javascript | {
"resource": ""
} |
q35287 | callbackParser | train | function callbackParser(err, out) {
if (err) {
error += err + '\n\n';
} else {
results[counter] = out;
}
counter++;
if (counter === urlLength) {
let result = {sources: [], feeds: []};
let i = 0;
_.each(results, feed => {
feed.metadata.lastBuildDate = moment(feed.metadata.lastBuildDate).format('x');
feed.metadata.update = moment(feed.metadata.update).format('x');
result.sources.push({type: feed.type, metadata: feed.metadata});
_.each(feed.items, function (item) {
item.source = i;
result.feeds.push(item);
});
i++;
});
// Sort value
switch (allowSortValue[sortByDate]) {
case allowSortValue.asc:
result.feeds.sort((a, b) => (a.date > b.date) ? 1 : ((b.date > a.date) ? -1 : 0));
break;
case allowSortValue.desc:
result.feeds.sort((a, b) => (a.date < b.date) ? 1 : ((b.date < a.date) ? -1 : 0));
break;
default:
break;
}
if (error !== '') {
finishCallback(error);
} else {
finishCallback(null, {feedRSSAtom: result});
}
}
} | javascript | {
"resource": ""
} |
q35288 | resizeHandler | train | function resizeHandler()
{
var viewPaneSize = mainWindow.getViewPaneSize();
shim && shim.setStyles( { width : viewPaneSize.width + 'px', height : viewPaneSize.height + 'px' } );
editor.resize( viewPaneSize.width, viewPaneSize.height, null, true );
} | javascript | {
"resource": ""
} |
q35289 | p1so | train | function p1so (topic1, topic2) {
pub(topic1, null, {persist: true});
var spy = sub(topic2);
return spy;
} | javascript | {
"resource": ""
} |
q35290 | subPubArg | train | function subPubArg (topic, data, i) {
var spy = sub(topic);
pub(topic, data);
var args = spy.calls.first().args;
return typeof i === 'undefined' ? args : args[i];
} | javascript | {
"resource": ""
} |
q35291 | train | function (options) {
var processQueue = [];
$.each(options.processQueue, function () {
var settings = {},
action = this.action,
prefix = this.prefix === true ? action : this.prefix;
$.each(this, function (key, value) {
if ($.type(value) === 'string' &&
value.charAt(0) === '@') {
settings[key] = options[
value.slice(1) || (prefix ? prefix +
key.charAt(0).toUpperCase() + key.slice(1) : key)
];
} else {
settings[key] = value;
}
});
processQueue.push(settings);
});
options.processQueue = processQueue;
} | javascript | {
"resource": ""
} | |
q35292 | train | function( editor )
{
try
{
var selection = editor.getSelection();
if ( selection.getType() == CKEDITOR.SELECTION_ELEMENT )
{
var selectedElement = selection.getSelectedElement();
if ( selectedElement.is( 'a' ) )
return selectedElement;
}
var range = selection.getRanges( true )[ 0 ];
range.shrink( CKEDITOR.SHRINK_TEXT );
var root = range.getCommonAncestor();
return root.getAscendant( 'a', true );
}
catch( e ) { return null; }
} | javascript | {
"resource": ""
} | |
q35293 | obbVsSphere | train | function obbVsSphere(contactPoint, contactNormal, obb, sphere) {
findClosestPointFromObbToPoint(contactPoint, obb, sphere.centerOfVolume);
vec3.subtract(contactNormal, sphere.centerOfVolume, contactPoint);
vec3.normalize(contactNormal, contactNormal);
} | javascript | {
"resource": ""
} |
q35294 | ResourcePool | train | function ResourcePool (options) {
this.max = options.max || 1;
this.maxUses = options.maxUses || 1;
this.create = options.create || function () {};
this.destroy = options.destroy || function () {};
this.active = 0;
this.resources = new Array(this.max);
this.resourceActive = new Array(this.max);
this.resourceUses = new Array(this.max);
} | javascript | {
"resource": ""
} |
q35295 | Fittings | train | function Fittings(bigpipe) {
if (!this.name) throw new Error('The fittings.name property is required.');
this.ultron = new Ultron(bigpipe);
this.bigpipe = bigpipe;
this.setup();
} | javascript | {
"resource": ""
} |
q35296 | makeitso | train | function makeitso(where) {
if ('string' === typeof where) {
where = {
expose: path.basename(where).replace(new RegExp(path.extname(where).replace('.', '\\.') +'$'), ''),
path: where
};
}
return where;
} | javascript | {
"resource": ""
} |
q35297 | Attachment | train | function Attachment(options) {
this.fileName = options.fileName;
this.contents = options.contents;
this.filePath = options.filePath;
this.streamSource = options.streamSource;
this.contentType = options.contentType;
this.cid = options.cid;
} | javascript | {
"resource": ""
} |
q35298 | trimHash | train | function trimHash (uri) {
var indexOfHash = uri.indexOf('#');
return (indexOfHash != -1) ? uri.substring(0, indexOfHash) : uri;
} | javascript | {
"resource": ""
} |
q35299 | in_array | train | function in_array( needle, haystack )
{
var found = 0,
key;
for ( key in haystack )
{
if ( haystack[ key ] == needle )
{
found = 1;
break;
}
}
return found;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.