_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q8000
|
train
|
function ( arg ) {
if ( arg === true ) {
observer.silent = arg;
}
else if ( arg === false ) {
observer.silent = arg;
array.each( observer.queue, function ( i ) {
observer.fire( i.obj, i.event );
});
observer.queue = [];
}
return arg;
}
|
javascript
|
{
"resource": ""
}
|
|
q8001
|
train
|
function ( obj ) {
return obj ? observer.clisteners[observer.id( obj )] : array.keys( observer.clisteners ).length;
}
|
javascript
|
{
"resource": ""
}
|
|
q8002
|
train
|
function ( obj, event, st ) {
observer.alisteners[obj][event][st] = array.cast( observer.listeners[obj][event][st] );
}
|
javascript
|
{
"resource": ""
}
|
|
q8003
|
train
|
function ( obj, all ) {
all = ( all === true );
var result;
if ( all ) {
result = string.explode( obj, " " ).map( function ( i ) {
return i.charAt( 0 ).toUpperCase() + i.slice( 1 );
}).join(" ");
}
else {
result = obj.charAt( 0 ).toUpperCase() + obj.slice( 1 );
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q8004
|
train
|
function ( obj, camel ) {
var result = string.trim( obj ).replace( /\s+/g, "-" );
if ( camel === true ) {
result = result.replace( /([A-Z])/g, "-$1" ).toLowerCase();
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q8005
|
train
|
function ( obj ) {
return obj.replace( /oe?s$/, "o" ).replace( /ies$/, "y" ).replace( /ses$/, "se" ).replace( /s$/, "" );
}
|
javascript
|
{
"resource": ""
}
|
|
q8006
|
train
|
function ( obj ) {
var s = string.trim( obj ).replace( /\.|_|-|\@|\[|\]|\(|\)|\#|\$|\%|\^|\&|\*|\s+/g, " " ).toLowerCase().split( regex.space_hyphen ),
r = [];
array.each( s, function ( i, idx ) {
r.push( idx === 0 ? i : string.capitalize( i ) );
});
return r.join( "" );
}
|
javascript
|
{
"resource": ""
}
|
|
q8007
|
train
|
function ( obj ) {
obj = string.trim( obj );
return obj.charAt( 0 ).toLowerCase() + obj.slice( 1 );
}
|
javascript
|
{
"resource": ""
}
|
|
q8008
|
train
|
function ( obj, caps ) {
if ( caps !== true ) {
return string.explode( obj, "-" ).join( " " );
}
else {
return string.explode( obj, "-" ).map( function ( i ) {
return string.capitalize( i );
}).join( " " );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8009
|
train
|
function ( arg ) {
var result;
if ( !arg ) {
return;
}
arg = string.trim( arg );
if ( arg.indexOf( "," ) === -1 ) {
result = utility.dom( arg );
}
else {
result = [];
array.each( string.explode( arg ), function ( query ) {
var obj = utility.dom( query );
if ( obj instanceof Array ) {
result = result.concat( obj );
}
else if ( obj ) {
result.push( obj );
}
});
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q8010
|
train
|
function ( obj, origin ) {
var o = obj,
s = origin;
utility.iterate( s, function ( v, k ) {
var getter, setter;
if ( !( v instanceof RegExp ) && typeof v === "function" ) {
o[k] = v.bind( o[k] );
}
else if ( !(v instanceof RegExp ) && !(v instanceof Array ) && v instanceof Object ) {
if ( o[k] === undefined ) {
o[k] = {};
}
utility.alias( o[k], s[k] );
}
else {
getter = function () {
return s[k];
};
setter = function ( arg ) {
s[k] = arg;
};
utility.property( o, k, {enumerable: true, get: getter, set: setter, value: s[k]} );
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8011
|
train
|
function ( id ) {
if ( id === undefined || string.isEmpty( id ) ) {
throw new Error( label.error.invalidArguments );
}
// deferred
if ( utility.timer[id] !== undefined ) {
clearTimeout( utility.timer[id] );
delete utility.timer[id];
}
// repeating
if ( utility.repeating[id] !== undefined ) {
clearTimeout( utility.repeating[id] );
delete utility.repeating[id];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8012
|
train
|
function ( obj, shallow ) {
var clone;
if ( shallow === true ) {
return json.decode( json.encode( obj ) );
}
else if ( !obj || regex.primitive.test( typeof obj ) || ( obj instanceof RegExp ) ) {
return obj;
}
else if ( obj instanceof Array ) {
return obj.slice();
}
else if ( !server && !client.ie && obj instanceof Document ) {
return xml.decode( xml.encode( obj ) );
}
else if ( typeof obj.__proto__ !== "undefined" ) {
return utility.extend( obj.__proto__, obj );
}
else if ( obj instanceof Object ) {
// If JSON encoding fails due to recursion, the original Object is returned because it's assumed this is for decoration
clone = json.encode( obj, true );
if ( clone !== undefined ) {
clone = json.decode( clone );
// Decorating Functions that would be lost with JSON encoding/decoding
utility.iterate( obj, function ( v, k ) {
if ( typeof v === "function" ) {
clone[k] = v;
}
});
}
else {
clone = obj;
}
return clone;
}
else {
return obj;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8013
|
train
|
function ( value ) {
var tmp;
if ( value === null || value === undefined ) {
return undefined;
}
else if ( value === "true" ) {
return true;
}
else if ( value === "false" ) {
return false;
}
else if ( value === "null" ) {
return null;
}
else if ( value === "undefined" ) {
return undefined;
}
else if ( value === "" ) {
return value;
}
else if ( !isNaN( tmp = Number( value ) ) ) {
return tmp;
}
else if ( regex.json_wrap.test( value ) ) {
return json.decode( value, true ) || value;
}
else {
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8014
|
train
|
function ( content, media ) {
var ss, css;
ss = element.create( "style", {type: "text/css", media: media || "print, screen"}, utility.$( "head" )[0] );
if ( ss.styleSheet ) {
ss.styleSheet.cssText = content;
}
else {
css = document.createTextNode( content );
ss.appendChild( css );
}
return ss;
}
|
javascript
|
{
"resource": ""
}
|
|
q8015
|
train
|
function ( fn, ms, scope ) {
ms = ms || 1000;
scope = scope || global;
return function debounced () {
setTimeout( function () {
fn.apply( scope, arguments );
}, ms);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8016
|
train
|
function ( args, value, obj ) {
args = args.split( "." );
var p = obj,
nth = args.length;
if ( obj === undefined ) {
obj = this;
}
if ( value === undefined ) {
value = null;
}
array.each( args, function ( i, idx ) {
var num = idx + 1 < nth && !isNaN( number.parse( args[idx + 1], 10 ) ),
val = value;
if ( !isNaN( number.parse( i, 10 ) ) ) {
i = number.parse( i, 10 );
}
// Creating or casting
if ( p[i] === undefined ) {
p[i] = num ? [] : {};
}
else if ( p[i] instanceof Object && num ) {
p[i] = array.cast( p[i] );
}
else if ( p[i] instanceof Object ) {
// Do nothing
}
else if ( p[i] instanceof Array && !num ) {
p[i] = array.toObject( p[i] );
}
else {
p[i] = {};
}
// Setting reference or value
idx + 1 === nth ? p[i] = val : p = p[i];
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8017
|
train
|
function ( fn, ms, id, repeat ) {
var op;
ms = ms || 0;
repeat = ( repeat === true );
if ( id !== undefined ) {
utility.clearTimers( id );
}
else {
id = utility.uuid( true );
}
op = function () {
utility.clearTimers( id );
fn();
};
utility[repeat ? "repeating" : "timer"][id] = setTimeout( op, ms );
return id;
}
|
javascript
|
{
"resource": ""
}
|
|
q8018
|
train
|
function ( arg ) {
var result;
if ( !regex.selector_complex.test( arg ) ) {
if ( regex.hash.test( arg ) ) {
result = document.getElementById( arg.replace( regex.hash, "" ) ) || undefined;
}
else if ( regex.klass.test( arg ) ) {
result = array.cast( document.getElementsByClassName( arg.replace( regex.klass, "" ) ) );
}
else if ( regex.word.test( arg ) ) {
result = array.cast( document.getElementsByTagName( arg ) );
}
else {
result = array.cast( document.querySelectorAll( arg ) );
}
}
else {
result = array.cast( document.querySelectorAll( arg ) );
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q8019
|
train
|
function ( e, args, scope, warning ) {
warning = ( warning === true );
var o = {
"arguments" : args !== undefined ? array.cast( args ) : [],
message : e.message || e,
number : e.number !== undefined ? ( e.number & 0xFFFF ) : undefined,
scope : scope,
stack : e.stack || undefined,
timestamp : new Date().toUTCString(),
type : e.type || "TypeError"
};
utility.log( ( o.stack || o.message || o ), !warning ? "error" : "warn" );
utility.error.log.push( o );
observer.fire( abaaso, "error", o );
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q8020
|
train
|
function ( obj, dom ) {
dom = ( dom === true );
var id;
if ( obj !== undefined && ( ( obj.id !== undefined && obj.id !== "" ) || ( obj instanceof Array ) || ( obj instanceof String || typeof obj === "string" ) ) ) {
return obj;
}
if ( dom ) {
do {
id = utility.domId( utility.uuid( true) );
}
while ( utility.$( "#" + id ) !== undefined );
}
else {
id = utility.domId( utility.uuid( true) );
}
if ( typeof obj === "object" ) {
obj.id = id;
return obj;
}
else {
return id;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8021
|
train
|
function ( color ) {
var digits, red, green, blue, result, i, nth;
if ( color.charAt( 0 ) === "#" ) {
result = color;
}
else {
digits = string.explode( color.replace( /.*\(|\)/g, "" ) );
red = number.parse( digits[0] || 0 );
green = number.parse( digits[1] || 0 );
blue = number.parse( digits[2] || 0 );
result = ( blue | ( green << 8 ) | ( red << 16 ) ).toString( 16 );
if ( result.length < 6 ) {
nth = number.diff( result.length, 6 );
i = -1;
while ( ++i < nth ) {
result = "0" + result;
}
}
result = "#" + result;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q8022
|
train
|
function ( obj ) {
var l = abaaso.loading;
if ( l.url === null || obj === undefined ) {
throw new Error( label.error.invalidArguments );
}
// Setting loading image
if ( l.image === undefined ) {
l.image = new Image();
l.image.src = l.url;
}
// Clearing target element
element.clear( obj );
// Creating loading image in target element
element.create( "img", {alt: label.common.loading, src: l.image.src}, element.create( "div", {"class": "loading"}, obj ) );
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8023
|
train
|
function ( arg, target ) {
var ts, msg;
if ( typeof console !== "undefined" ) {
ts = typeof arg !== "object";
msg = ts ? "[" + new Date().toLocaleTimeString() + "] " + arg : arg;
console[target || "log"]( msg );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8024
|
train
|
function ( obj, arg ) {
utility.iterate( arg, function ( v, k ) {
if ( ( obj[k] instanceof Array ) && ( v instanceof Array ) ) {
array.merge( obj[k], v );
}
else if ( ( obj[k] instanceof Object ) && ( v instanceof Object ) ) {
utility.iterate( v, function ( x, y ) {
obj[k][y] = utility.clone( x );
});
}
else {
obj[k] = utility.clone( v );
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8025
|
train
|
function ( arg, obj ) {
if ( $[arg] !== undefined || !obj instanceof Object ) {
throw new Error( label.error.invalidArguments );
}
$[arg] = obj;
return $[arg];
}
|
javascript
|
{
"resource": ""
}
|
|
q8026
|
train
|
function ( obj ) {
return typeof obj === "object" ? obj : ( obj.charAt && obj.charAt( 0 ) === "#" ? utility.$( obj ) : obj );
}
|
javascript
|
{
"resource": ""
}
|
|
q8027
|
train
|
function ( uri ) {
var obj = {},
parsed = {};
if ( uri === undefined ) {
uri = !server ? location.href : "";
}
if ( !server ) {
obj = document.createElement( "a" );
obj.href = uri;
}
else {
obj = url.parse( uri );
}
if ( server ) {
utility.iterate( obj, function ( v, k ) {
if ( v === null ) {
obj[k] = undefined;
}
});
}
parsed = {
auth : server ? null : regex.auth.exec( uri ),
protocol : obj.protocol || "http:",
hostname : obj.hostname || "localhost",
port : obj.port ? number.parse( obj.port, 10 ) : "",
pathname : obj.pathname,
search : obj.search || "",
hash : obj.hash || "",
host : obj.host || "localhost"
};
// 'cause IE is ... IE; required for data.batch()
if ( client.ie ) {
if ( parsed.protocol === ":" ) {
parsed.protocol = location.protocol;
}
if ( string.isEmpty( parsed.hostname ) ) {
parsed.hostname = location.hostname;
}
if ( string.isEmpty( parsed.host ) ) {
parsed.host = location.host;
}
if ( parsed.pathname.charAt( 0 ) !== "/" ) {
parsed.pathname = "/" + parsed.pathname;
}
}
parsed.auth = obj.auth || ( parsed.auth === null ? "" : parsed.auth[1] );
parsed.href = obj.href || ( parsed.protocol + "//" + ( string.isEmpty( parsed.auth ) ? "" : parsed.auth + "@" ) + parsed.host + parsed.pathname + parsed.search + parsed.hash );
parsed.path = obj.path || parsed.pathname + parsed.search;
parsed.query = utility.queryString( null, parsed.search );
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
|
q8028
|
train
|
function () {
if ( ( server || ( !client.ie || client.version > 8 ) ) && typeof Object.defineProperty === "function" ) {
return function ( obj, prop, descriptor ) {
if ( !( descriptor instanceof Object ) ) {
throw new Error( label.error.invalidArguments );
}
if ( descriptor.value !== undefined && descriptor.get !== undefined ) {
delete descriptor.value;
}
Object.defineProperty( obj, prop, descriptor );
};
}
else {
return function ( obj, prop, descriptor ) {
if ( !( descriptor instanceof Object ) ) {
throw new Error( label.error.invalidArguments );
}
obj[prop] = descriptor.value;
return obj;
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8029
|
train
|
function ( obj, type ) {
var target = obj.prototype || obj;
utility.iterate( prototypes[type], function ( v, k ) {
if ( !target[k] ) {
utility.property( target, k, {value: v, configurable: true, writable: true} );
}
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8030
|
train
|
function ( arg, qstring ) {
var obj = {},
result = qstring !== undefined ? ( qstring.indexOf( "?" ) > -1 ? qstring.replace( /.*\?/, "" ) : null) : ( server || string.isEmpty( location.search ) ? null : location.search.replace( "?", "" ) );
if ( result !== null && !string.isEmpty( result ) ) {
result = result.split( "&" );
array.each( result, function (prop ) {
var item = prop.split( "=" );
if ( string.isEmpty( item[0] ) ) {
return;
}
if ( item[1] === undefined ) {
item[1] = "";
}
else {
item[1] = utility.coerce( decodeURIComponent( item[1] ) );
}
if ( obj[item[0]] === undefined ) {
obj[item[0]] = item[1];
}
else if ( !(obj[item[0]] instanceof Array) ) {
obj[item[0]] = [obj[item[0]]];
obj[item[0]].push( item[1] );
}
else {
obj[item[0]].push( item[1] );
}
});
}
if ( arg !== null && arg !== undefined ) {
obj = obj[arg];
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8031
|
train
|
function ( arg ) {
if ( arg === undefined ) {
arg = this || utility.$;
}
arg = arg.toString().match( regex.reflect )[1];
return string.explode( arg );
}
|
javascript
|
{
"resource": ""
}
|
|
q8032
|
train
|
function ( fn, ms, id, now ) {
ms = ms || 10;
id = id || utility.uuid( true );
now = ( now !== false );
// Could be valid to return false from initial execution
if ( now && fn() === false ) {
return;
}
// Creating repeating execution
utility.defer( function () {
var recursive = function ( fn, ms, id ) {
var recursive = this;
if ( fn() !== false ) {
utility.repeating[id] = setTimeout( function () {
recursive.call( recursive, fn, ms, id );
}, ms );
}
else {
delete utility.repeating[id];
}
};
recursive.call( recursive, fn, ms, id );
}, ms, id, true );
return id;
}
|
javascript
|
{
"resource": ""
}
|
|
q8033
|
train
|
function ( arg, target ) {
var frag;
if ( typeof arg !== "object" || (!(regex.object_undefined.test( typeof target ) ) && ( target = target.charAt( 0 ) === "#" ? utility.$( target ) : utility.$( target )[0] ) === undefined ) ) {
throw new Error( label.error.invalidArguments );
}
if ( target === undefined ) {
target = utility.$( "body" )[0];
}
frag = document.createDocumentFragment();
if ( arg instanceof Array ) {
array.each( arg, function ( i ) {
element.html( element.create( array.cast( i, true )[0], frag ), array.cast(i)[0] );
});
}
else {
utility.iterate( arg, function ( v, k ) {
if ( typeof v === "string" ) {
element.html( element.create( k, undefined, frag ), v );
}
else if ( ( v instanceof Array ) || ( v instanceof Object ) ) {
utility.tpl( v, element.create( k, undefined, frag ) );
}
});
}
target.appendChild( frag );
return array.last( target.childNodes );
}
|
javascript
|
{
"resource": ""
}
|
|
q8034
|
train
|
function ( safe ) {
var s = function () { return ( ( ( 1 + Math.random() ) * 0x10000 ) | 0 ).toString( 16 ).substring( 1 ); },
r = [8, 9, "a", "b"],
o;
o = ( s() + s() + "-" + s() + "-4" + s().substr( 0, 3 ) + "-" + r[Math.floor( Math.random() * 4 )] + s().substr( 0, 3 ) + "-" + s() + s() + s() );
if ( safe === true ) {
o = o.replace( /-/g, "" );
}
return o;
}
|
javascript
|
{
"resource": ""
}
|
|
q8035
|
train
|
function ( obj, arg ) {
array.each( arg.replace( /\]$/, "" ).replace( /\]/g, "." ).replace( /\.\./g, "." ).split( /\.|\[/ ), function ( i ) {
obj = obj[i];
});
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q8036
|
train
|
function () {
var i = 0,
defer = deferred(),
args = array.cast( arguments ),
nth;
// Did we receive an Array? if so it overrides any other arguments
if ( args[0] instanceof Array ) {
args = args[0];
}
// How many instances to observe?
nth = args.length;
// None, end on next tick
if ( nth === 0 ) {
defer.resolve( null );
}
// Setup and wait
else {
array.each( args, function ( p ) {
p.then( function () {
if ( ++i === nth && !defer.isResolved()) {
if ( args.length > 1 ) {
defer.resolve( args.map( function ( obj ) {
return obj.value || obj.promise.value;
}));
}
else {
defer.resolve( args[0].value || args[0].promise.value );
}
}
}, function () {
if ( !defer.isResolved() ) {
if ( args.length > 1 ) {
defer.reject( args.map( function ( obj ) {
return obj.value || obj.promise.value;
}));
}
else {
defer.reject( args[0].value || args[0].promise.value );
}
}
});
});
}
return defer;
}
|
javascript
|
{
"resource": ""
}
|
|
q8037
|
train
|
function ( arg, wrap ) {
try {
if ( arg === undefined ) {
throw new Error( label.error.invalidArguments );
}
wrap = ( wrap !== false );
var x = wrap ? "<xml>" : "",
top = ( arguments[2] !== false ),
node;
/**
* Encodes a value as a node
*
* @method node
* @private
* @param {String} name Node name
* @param {Value} value Node value
* @return {String} Node
*/
node = function ( name, value ) {
var output = "<n>v</n>";
output = output.replace( "v", ( regex.cdata.test( value ) ? "<![CDATA[" + value + "]]>" : value ) );
return output.replace(/<(\/)?n>/g, "<$1" + name + ">");
};
if ( arg !== null && arg.xml !== undefined ) {
arg = arg.xml;
}
if ( arg instanceof Document ) {
arg = ( new XMLSerializer() ).serializeToString( arg );
}
if ( regex.boolean_number_string.test( typeof arg ) ) {
x += node( "item", arg );
}
else if ( typeof arg === "object" ) {
utility.iterate( arg, function ( v, k ) {
x += xml.encode( v, ( typeof v === "object" ), false ).replace( /item|xml/g, isNaN( k ) ? k : "item" );
});
}
x += wrap ? "</xml>" : "";
if ( top ) {
x = "<?xml version=\"1.0\" encoding=\"UTF8\"?>" + x;
}
return x;
}
catch ( e ) {
utility.error( e, arguments, this );
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8038
|
train
|
function(str, options) {
// get settings
var settings;
if (_.isUndefined(options) && defaultSettings !== null) {
settings = defaultSettings;
} else if (!_.isUndefined(options)) {
settings = util.parseOptions(options, defaultOptions);
} else {
settings = util.parseOptions(defaultOptions);
defaultSettings = settings;
}
// return processed string
return util.replaceMatches(str, settings);
}
|
javascript
|
{
"resource": ""
}
|
|
q8039
|
FakeDate
|
train
|
function FakeDate(a, b, c, d, e, f, g) {
var argsArray = [].splice.call(arguments, 0);
var date =
argsArray.length === 0
? new OriginalDate(Date.now())
: makeOriginalDateFromArgs.apply(undefined, argsArray);
if (!(this instanceof FakeDate)) {
return date.toString();
}
this._date = date;
}
|
javascript
|
{
"resource": ""
}
|
q8040
|
patch
|
train
|
function patch(node, tag) {
var data = node.data || (node.data = {})
data.partOfSpeech = tag
}
|
javascript
|
{
"resource": ""
}
|
q8041
|
dataToType
|
train
|
function dataToType(data, name, options) {
options = options || {};
var knownID = /(^|\s|_)(zip|phone|id)(_|\s|$)/i;
// If data is not a simple type, then just use text
if (_.isArray(data[0]) || _.isObject(data[0])) {
return Sequelize.TEXT;
}
// Otherise go through each value and see what is found
data = _.map(data, function(d) {
d = standardize(d);
return {
value: d,
length: (d && d.toString) ? d.toString().length : null,
kind: pickle(d, options)
};
});
// Filter out any empty values
data = _.filter(data, "length");
var counted = _.countBy(data, "kind");
var top = _.sortBy(_.map(counted, function(d, di) {
return { kind: di, count: d };
}), "count").reverse()[0];
var maxLength = _.maxBy(data, "length");
maxLength = maxLength ? maxLength.length : maxLength;
var kind;
// If none, then just assume string
if (_.size(data) === 0) {
return Sequelize.STRING;
}
// If there is only one kind, stick with that
else if (_.size(counted) === 1) {
kind = top.kind;
}
// If there is an integer and a float, use float
else if (counted.INTGER && counted.FLOAT) {
kind = "FLOAT";
}
else {
kind = top.kind;
}
// Check for long strings
if (kind === "STRING" && maxLength * 2 < 512) {
return new Sequelize.STRING(Math.floor(maxLength * 2));
}
// Otherwise add length
else if (kind === "STRING" && maxLength * 2 >= 512) {
return Sequelize.TEXT;
}
// Known not numbers
else if ((kind === "INTEGER" || kind === "FLOAT") && knownID.test(name)) {
return new Sequelize.STRING(Math.floor(maxLength * 2));
}
// Check for long integers
else if (kind === "INTEGER" && maxLength > 8) {
return Sequelize.BIGINT;
}
else {
return Sequelize[kind];
}
}
|
javascript
|
{
"resource": ""
}
|
q8042
|
standardize
|
train
|
function standardize(value) {
var isString = _.isString(value);
value = utils.standardizeInput(value);
return (isString && value === null) ? "" : value;
}
|
javascript
|
{
"resource": ""
}
|
q8043
|
pickle
|
train
|
function pickle(value, options) {
options = options || {};
// Tests
var floatTest = /^(-|)[\d,]+.\d+$/g;
var intTest = /^\d+$/g;
var booleanTest = /^(true|false)$/g;
var dateTest = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/g;
var datetimeTest = /^\d{1,2}\/\d{1,2}\/\d{2,4}\s+\d{1,2}:\d{1,2}(:\d{1,2}|)(\s+|)(am|pm|)$/gi;
// Test values
if ((options.datetimeFormat && moment(value, options.datetimeFormat, true).isValid()) || datetimeTest.test(value)) {
return "DATE";
}
if ((options.dateFormat && moment(value, options.dateFormat, true).isValid()) || dateTest.test(value)) {
return "DATEONLY";
}
if (_.isInteger(value) || intTest.test(value)) {
return "INTEGER";
}
if ((_.isFinite(value) && !_.isInteger(value)) || floatTest.test(value)) {
return "FLOAT";
}
if (_.isBoolean(value) || booleanTest.test(value)) {
return "BOOLEAN";
}
return "STRING";
}
|
javascript
|
{
"resource": ""
}
|
q8044
|
train
|
function(line) {
line = line.toString();
var colCount = _.size(transactionFields);
var possibleRow = row + line;
var possibleFields = possibleRow.slice(1, possibleRow.length - 1).split("\",\"");
// Unfortunately there are some fields that have new line characters in them
// and there could be exta commas
if (line.slice(-1) !== "\"" || possibleFields.length < colCount) {
row = row + line;
return false;
}
// Otherwise just use what we have
else {
line = row + line;
row = "";
}
// Parse and match with headers
var fields = line.slice(1, line.length - 1).split("\",\"");
var parsed = {};
_.each(_.keys(transactionFields), function(h, hi) {
parsed[h] = fields[hi];
});
// Use auto parser to coerce the types
parsed = this.autoParser(parsed, this.options.models, {
dateFormat: this.options.dateFormat,
datetimeFormat: this.options.datetimeFormat
});
//checkFieldLength(parsed, "other_receipt_code");
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
|
q8045
|
checkFieldLength
|
train
|
function checkFieldLength(parsed, field, length) {
length = length || transactionFields[field].options.length;
if (parsed.transactions[field] && parsed.transactions[field].toString().length > length) {
console.log(parsed.transactions);
console.log(field, parsed.transactions[field]);
}
}
|
javascript
|
{
"resource": ""
}
|
q8046
|
improveFunc
|
train
|
function improveFunc(doclet) {
doclet.signature = doclet.name + '(';
_.each(doclet.params, function(p, i) {
if (!(p && p.type && p.type.names)) {
logger.debug('Bad parameter', p, doclet.longname);
return;
}
p.signature = ':param ' +
p.type && p.type.names && p.type.names.join('|');
p.signature += ' ' + p.name;
if (p.optional) {
doclet.signature += '[';
}
if (i > 0) {
doclet.signature += ', ';
}
doclet.signature += p.name;
if (p.optional) {
doclet.signature += ']';
}
return p.name;
});
doclet.signature += ')';
_.each(doclet.returns, function(r) {
if (!(r && r.type && r.type.names)) {
logger.debug('Bad return', r, doclet.longname);
return;
}
r.signature = ':return ' +
r.type && r.type.names && r.type.names.join('|');
});
}
|
javascript
|
{
"resource": ""
}
|
q8047
|
generate
|
train
|
function generate(target, generator) {
return function(cb) {
logger.debug('generate', target);
generator(context, handleErrorCallback(function(err, data) {
if (err) {
logger.error('cannot generate ' + target);
logger.debug(err);
return;
}
write(target, data, cb);
}));
};
}
|
javascript
|
{
"resource": ""
}
|
q8048
|
registerLink
|
train
|
function registerLink(doclet) {
var url = helper.createLink(doclet);
helper.registerLink(doclet.longname, url);
doclet.rstLink = url.substr(0, url.length - helper.fileExtension.length);
// Parent link
if (!doclet.memberof) {
return;
}
var parent;
parent = helper.find(context.data, {longname: doclet.memberof});
if (parent && parent.length > 0) {
doclet.parentRstLink = parent[0].rstLink;
}
// Reference code
doclet.rstReference = doclet.parentRstLink + '.' + doclet.name;
}
|
javascript
|
{
"resource": ""
}
|
q8049
|
write
|
train
|
function write(relPath, data, cb) {
var target = path.join(context.destination, relPath);
mkdirp(path.dirname(target), handleErrorCallback(function() {
fs.writeFileSync(target, data);
handleErrorCallback(cb)(null, target);
logger.debug('file written: %s', target);
}));
}
|
javascript
|
{
"resource": ""
}
|
q8050
|
handleErrorCallback
|
train
|
function handleErrorCallback(cb) {
return function(err) {
if (err) {
logger.error(err);
return cb(err);
}
return cb.apply(this, arguments);
};
}
|
javascript
|
{
"resource": ""
}
|
q8051
|
autoParse
|
train
|
function autoParse(data, models, options) {
options = options || {};
var parsed = {};
// Go through each data point
_.each(data, function(value, field) {
var d = findField(field, models);
// Find field in
if (d) {
parsed[d.modelName] = parsed[d.modelName] || {};
parsed[d.modelName][d.field.name] = parse(value, d.field, options);
}
});
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q8052
|
parse
|
train
|
function parse(value, field, options) {
options = options || {};
var parsed = utils.standardizeInput(value);
// Integer
if (field.type.key === "BOOLEAN") {
parsed = utils.toBoolean(parsed);
}
else if (field.type.key === "INTEGER") {
parsed = utils.toInteger(parsed);
}
else if (field.type.key === "FLOAT") {
parsed = utils.toFloat(parsed);
}
else if (field.type.key === "DATEONLY") {
parsed = utils.toDate(parsed, options.dateFormat);
}
else if (field.type.key === "DATE") {
parsed = utils.toDateTime(parsed, options.datetimeFormat);
}
else if (field.type.key === "STRING") {
parsed = utils.toString(parsed);
}
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q8053
|
findField
|
train
|
function findField(field, models) {
var found = false;
_.each(models, function(model) {
// Go through fields
_.each(model.fields, function(f) {
if (f.input === field) {
found = {
modelName: model.modelName,
field: f
};
}
});
});
return found;
}
|
javascript
|
{
"resource": ""
}
|
q8054
|
train
|
function (element, quantity, callback) {
if (this.$.basket) {
this.fixBasketCurrency();
var basketItem = this.$.basket.addElement(element, quantity);
element = basketItem.$.element;
var originId = this.$.originId;
if (originId) {
basketItem.set('origin', new Entity({
id: originId
}));
}
this.extendElementWithLinks(element);
}
callback && callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q8055
|
train
|
function (basketItem, element, quantity, cb) {
this.extendElementWithLinks(element);
basketItem.set({
element: element,
quantity: quantity
});
basketItem.save(null, cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q8056
|
docletChildren
|
train
|
function docletChildren(context, doclet, kinds) {
if (!kinds) {
kinds = mainDocletKinds;
}
var results = {};
_.each(kinds, function(k) {
var q = {
kind: k,
memberof: doclet ? doclet.longname : {isUndefined: true}
};
results[k] = helper.find(context.data, q);
});
logger.debug((doclet ? doclet.longname : '<global>'),
'doclet children',
'kinds:', kinds,
'results:', results);
return results;
}
|
javascript
|
{
"resource": ""
}
|
q8057
|
example
|
train
|
function example() {
return function(data, render) {
var output = '.. code-block:: javascript\n';
var lines = render(data).split('\n');
logger.debug('line-0', data);
if (lines.length && lines[0].match(/^<caption>.*<\/caption>$/)) {
output += ' :caption: ' + lines.shift().slice(9, -10) + '\n';
}
output += '\n';
for (var i = 0; i < lines.length; i++) {
output += ' ' + lines[i] + '\n';
}
return render(output);
};
}
|
javascript
|
{
"resource": ""
}
|
q8058
|
train
|
function(data, restrictions, callback) {
var image;
if (restrictions instanceof Function) {
callback = restrictions;
restrictions = null;
}
if (data instanceof BlobImage || data instanceof iFrameUpload) {
image = data;
} else if (_.isString(data)) {
image = new RemoteImage({
src: data
});
} else {
image = new FileSystemImage({
file: data
});
}
var uploadDesign = new UploadDesign({
image: image
});
this._uploadDesign(uploadDesign, restrictions, callback);
return uploadDesign;
}
|
javascript
|
{
"resource": ""
}
|
|
q8059
|
train
|
function(on, options) {
options = options || {};
this.on = _.isUndefined(on) ? true : !!on;
this.useBullet = _.isUndefined(options.useBullet) ? true : !!options.useBullet;
// Use stderr since this is all just nice info to have and not data
// http://www.jstorimer.com/blogs/workingwithcode/7766119-when-to-use-stderr-instead-of-stdout
this.output = options.output || process.stderr;
// Other properties
this.bullet = bullet;
this.cc = cc;
this.chalk = chalk;
this.progressOptionsComplete = cc.bgo + " " + cc.bgc;
this.progressOptionsIncomplete = cc.bwo + " " + cc.bwc;
this.progressBarFormat = (this.useBullet ? bullet : "") + "[:bar] :percent | :elapseds elapsed | ~:etas left";
this.spinnerFormat = (this.useBullet ? bullet : "") + "%s";
}
|
javascript
|
{
"resource": ""
}
|
|
q8060
|
train
|
function(settings, pluginInfo, options) {
// resolve plugin and plugin options
var plugin;
if (_.has(pluginInfo, 'plugin')) {
plugin = pluginInfo.plugin;
} else if (_.has(pluginInfo, 'module')) {
// make sure we don't load the same module twice
if (_.contains(settings.loadedModules, pluginInfo.module)) {
return settings;
}
// try to load module
try {
plugin = require(pluginInfo.module);
} catch (err) {
throw new GrawlixPluginError({
msg: "cannot find module '" + pluginInfo.module + "'",
plugin: pluginInfo,
trace: new Error()
});
}
settings.loadedModules.push(pluginInfo.module);
} else {
plugin = pluginInfo;
}
var pluginOpts = _.has(pluginInfo, 'options') ? pluginInfo.options : {};
// instantiate plugin if necessary
if (_.isFunction(plugin)) {
plugin = plugin(pluginOpts, options);
}
// validate plugin
if (!(plugin instanceof GrawlixPlugin)) {
throw new GrawlixPluginError({
msg: 'invalid plugin',
plugin: pluginInfo
});
} else if (plugin.name === null || _.isEmpty(plugin.name)) {
throw new GrawlixPluginError({
msg: 'invalid plugin - name property not provided',
plugin: pluginInfo
});
} else if (_.contains(settings.loadedPlugins, plugin.name)) {
// don't load the same plugin twice
return settings;
}
// initialize plugin
plugin.init(pluginOpts);
// load filters
if (!_.isUndefined(plugin.filters) && _.isArray(plugin.filters)) {
try {
loadFilters(settings, plugin.filters, options.allowed);
} catch (err) {
err.plugin = pluginInfo;
throw err;
}
}
// load styles
if (!_.isUndefined(plugin.styles) && _.isArray(plugin.styles)) {
try {
loadStyles(settings, plugin.styles);
} catch (err) {
err.plugin = pluginInfo;
throw err;
}
}
// add name to loaded plugins
settings.loadedPlugins.push(plugin.name);
// return
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q8061
|
train
|
function(settings, filters, allowed) {
if (filters.length > 0) {
_.each(filters, function(obj) {
if (!_.has(obj, 'word')) {
return;
}
if (!_.has(obj, 'pattern')) {
// configure existing filter options
var filter = _.findWhere(settings.filters, { word: obj.word });
if (!_.isUndefined(filter)) {
filter.configure(obj);
}
} else if (!_.contains(allowed, obj.word)) {
// if filter word isn't whitelisted, add as new GrawlixFilter
settings.filters.push( toGrawlixFilter(obj) );
}
});
}
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q8062
|
train
|
function(settings, styles) {
if (_.isArray(styles) && styles.length > 0) {
_.each(styles, function(obj) {
if (!_.has(obj, 'name')) {
return;
}
var style = _.findWhere(settings.styles, { name: obj.name });
if (!_.isUndefined(style)) {
style.configure(obj);
} else {
settings.styles.push( toGrawlixStyle(obj) );
}
});
}
return settings;
}
|
javascript
|
{
"resource": ""
}
|
|
q8063
|
train
|
function(str, filter, settings) {
// get filter style if provided
var style;
if (filter.hasStyle() && settings.style.isOverrideAllowed) {
style = _.findWhere(settings.styles, { name: filter.style });
}
if (_.isUndefined(style)) {
// if filter style not found, or no filter style set, use main style
style = settings.style;
}
// get replacement grawlix
var repl;
if (!settings.isRandom && style.hasFixed(filter.word)) {
// if in fixed replacement mode and style has a defined fixed replacement
// string for the filter's word
repl = style.getFixed(filter.word);
} else {
// if single-character style
repl = generateGrawlix(str, filter, style);
}
// apply filter template if necessary
if (filter.hasTemplate()) {
repl = filter.template(repl);
}
// replace the match
return str.replace(filter.regex, repl);
}
|
javascript
|
{
"resource": ""
}
|
|
q8064
|
train
|
function(str, filter, style) {
// determine length
var len;
if (filter.isExpandable) {
len = filter.getMatchLen(str);
} else {
len = filter.word.length;
}
// generate grawlix
if (!style.canRandomize()) {
return style.getFillGrawlix(len);
}
return style.getRandomGrawlix(len);
}
|
javascript
|
{
"resource": ""
}
|
|
q8065
|
indexOf
|
train
|
function indexOf(list, element, comparator) {
for (var i=0,item; item=list[i]; i++) {
if (equals(item, element, comparator)) {
return i;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q8066
|
Tree
|
train
|
function Tree(options) {
this.root = new Node(this, options);
this.unique = options && options.unique || false;
this.compare = options && options.compare || compare;
this.equals = options && options.equals || equals;
this.keyType = options && options.keyType || undefined;
this.id = options && options.id || undefined;
}
|
javascript
|
{
"resource": ""
}
|
q8067
|
Node
|
train
|
function Node(tree, options) {
this.tree = tree;
if (options && options.parent) {this.parent = options.parent;}
if (options && options.hasOwnProperty('key')) { this.key = options.key; }
this.data = options && options.hasOwnProperty('value') ? [options.value] : [];
}
|
javascript
|
{
"resource": ""
}
|
q8068
|
getLowerBoundMatcher
|
train
|
function getLowerBoundMatcher(compare, query) {
// No lower bound
if (!query.hasOwnProperty('$gt') && !query.hasOwnProperty('$gte')) {
return function(){return true;};
}
if (query.hasOwnProperty('$gt') && query.hasOwnProperty('$gte')) {
if (compare(query.$gte, query.$gt) === 0) {
return function (key) { return compare(key, query.$gt) > 0; };
}
if (compare(query.$gte, query.$gt) > 0) {
return function (key) { return compare(key, query.$gte) >= 0; };
} else {
return function (key) { return compare(key, query.$gt) > 0; };
}
}
if (query.hasOwnProperty('$gt')) {
return function (key) { return compare(key, query.$gt) > 0; };
} else {
return function (key) { return compare(key, query.$gte) >= 0; };
}
}
|
javascript
|
{
"resource": ""
}
|
q8069
|
getUpperBoundMatcher
|
train
|
function getUpperBoundMatcher(compare, query) {
// No lower bound
if (!query.hasOwnProperty('$lt') && !query.hasOwnProperty('$lte')) {
return function () { return true; };
}
if (query.hasOwnProperty('$lt') && query.hasOwnProperty('$lte')) {
if (compare(query.$lte, query.$lt) === 0) {
return function (key) { return compare(key, query.$lt) < 0; };
}
if (compare(query.$lte, query.$lt) < 0) {
return function (key) { return compare(key, query.$lte) <= 0; };
} else {
return function (key) { return compare(key, query.$lt) < 0; };
}
}
if (query.hasOwnProperty('$lt')) {
return function (key) { return compare(key, query.$lt) < 0; };
} else {
return function (key) { return compare(key, query.$lte) <= 0; };
}
}
|
javascript
|
{
"resource": ""
}
|
q8070
|
betweenBounds
|
train
|
function betweenBounds(node, query, lbm, ubm) {
var res = [];
if (!node.hasOwnProperty('key')) { return res; } // Empty tree
lbm = lbm || getLowerBoundMatcher(node.tree.compare, query);
ubm = ubm || getUpperBoundMatcher(node.tree.compare, query);
if (lbm(node.key) && node.left) { res.push.apply(res, betweenBounds(node.left, query, lbm, ubm)); }
if (lbm(node.key) && ubm(node.key)) { res.push.apply(res, node.data); }
if (ubm(node.key) && node.right) { res.push.apply(res, betweenBounds(node.right, query, lbm, ubm)); }
return res;
}
|
javascript
|
{
"resource": ""
}
|
q8071
|
balanceFactor
|
train
|
function balanceFactor(node) {
return (node.left ? node.left.height : 0) - (node.right ? node.right.height : 0);
}
|
javascript
|
{
"resource": ""
}
|
q8072
|
rightTooSmall
|
train
|
function rightTooSmall(node) {
if (balanceFactor(node) <= 1) { return node; } // Right is not too small, don't change
if (balanceFactor(node.left) < 0) {leftRotation(node.left);}
return rightRotation(node);
}
|
javascript
|
{
"resource": ""
}
|
q8073
|
leftTooSmall
|
train
|
function leftTooSmall(node) {
if (balanceFactor(node) >= -1) { return node; } // Left is not too small, don't change
if (balanceFactor(node.right) > 0) {rightRotation(node.right);}
return leftRotation(node);
}
|
javascript
|
{
"resource": ""
}
|
q8074
|
train
|
function(data) {
if (thisTables.options.stdin) {
thisTables.guessBuffers.push(data);
}
bar.tick(data.length);
}
|
javascript
|
{
"resource": ""
}
|
|
q8075
|
unionizeList
|
train
|
function unionizeList(array, start, count, union) {
var internalObservees = [] // list of observees and their property path
if(union !== undefined) {
var afterEnd = start+count
for(var n=start; n<afterEnd; n++) {
internalObservees.push({obj: array[n], index: n})
if(union === true)
array[n] = array[n].subject
}
}
return internalObservees
}
|
javascript
|
{
"resource": ""
}
|
q8076
|
unionizeListEvents
|
train
|
function unionizeListEvents(that, internalObservees, propertyList, collapse) {
for(var n=0; n<internalObservees.length; n++) {
unionizeEvents(that, internalObservees[n].obj, propertyList.concat(internalObservees[n].index+''), collapse)
}
}
|
javascript
|
{
"resource": ""
}
|
q8077
|
chainQueryRun
|
train
|
function chainQueryRun (safeCon, arg, currentObj) {
objAdder(safeCon, currentObj);
var stream;
try {
stream = safeCon.query.apply(safeCon, arg);
} catch(e) {
return currentObj.rollback(e);
}
autoErrorRollback(currentObj);
onewayEventConnect(stream, currentObj);
if (currentObj._autoCommit) {
autoCommitReady(safeCon, currentObj);
}
stream.on('error', function(e){
safeCon._errorState = true;
});
currentObj.on('end', function(){
safeCon._count -= 1;
});
safeCon._count += 1;
currentObj.stream = stream;
currentObj.emit('nextChain', safeCon);
}
|
javascript
|
{
"resource": ""
}
|
q8078
|
train
|
function(prezContents, cb) {
var slideChunksPreTpl = prezContents.toString().split(slideBreakAt);
_.forEach(slideChunksPreTpl, function(chunk) {
opts.slides.push({
preHtml: chunk,
indented: opts.slides.length && isIndented(chunk)
});
});
cb(null, opts);
}
|
javascript
|
{
"resource": ""
}
|
|
q8079
|
train
|
function (e) {
if (this.$.enabled) {
this.removeClass('drag-over');
if (e && e.$) {
e = e.$;
if (e.dataTransfer && e.dataTransfer.files.length) {
for (var i = 0; i < e.dataTransfer.files.length; i++) {
this._addAndUploadFile(e.dataTransfer.files[i]);
}
}
}
}
e.preventDefault();
e.stopPropagation();
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q8080
|
train
|
function (file, callback) {
var self = this,
reader = new FileReader();
var uploadDesign = this.$.imageUploadService.upload(file, function (err) {
if (!err) {
self.trigger("uploadComplete", {
uploadDesign: uploadDesign
});
} else {
self.trigger("uploadError", {
error: err,
uploadDesign: uploadDesign
});
}
callback && callback(err, uploadDesign);
});
reader.onload = function(evt) {
var img = new Image();
img.onload = function() {
uploadDesign.set({
previewImage: evt.target.result,
localImage: evt.target.result
});
};
img.src = evt.target.result;
};
reader.readAsDataURL(file);
return uploadDesign;
}
|
javascript
|
{
"resource": ""
}
|
|
q8081
|
on_record
|
train
|
function on_record(record) {
var parser = this
//LOG.info('Record %s: %s', RECORD_NAMES[record.header.type], record.header.recordId)
record.bodies = parser.bodies
parser.bodies = []
record.body_utf8 = function() {
return this.bodies
.map(function(data) { return data.toString() })
.join('')
}
var req_id = record.header.recordId
if(req_id == 0)
return LOG.info('Ignoring management record: %j', record)
var request = requests_in_flight[req_id]
if(!request)
return LOG.error('Record for unknown request: %s\n%s', req_id, util.inspect(request))
if(record.header.type == FCGI.constants.record.FCGI_STDERR)
return LOG.error('Error: %s', record.body_utf8().trim())
else if(record.header.type == FCGI.constants.record.FCGI_STDOUT) {
request.stdout = request.stdout.concat(record.bodies)
return send_stdout(request)
}
else if(record.header.type == FCGI.constants.record.FCGI_END) {
request.res.end()
LOG.info('%s %s %d', request.req.method, request.req.url, request.status)
delete requests_in_flight[req_id]
if(request.keepalive == FCGI.constants.keepalive.ON)
process_request() // If there are more in the queue, get to them now.
else
socket.end()
}
else {
LOG.info('Unknown record: %j', record)
Object.keys(FCGI.constants.record).forEach(function(type) {
if(record.header.type == FCGI.constants.record[type])
LOG.info('Unknown record type: %s', type)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q8082
|
train
|
function (object, label, callback) {
var labelObject = this.$.dataSource.createEntity(ObjectLabel);
labelObject.set({
object: object,
objectType: this.$.dataSource.createEntity(ObjectType, this.getObjectTypeIdForElement(object)),
label: label
});
labelObject.save(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q8083
|
middlewareFunction
|
train
|
function middlewareFunction (req,res,next){
return ipToLocation(req.ip)
.then(function (location) {
req.location = location;
next();
})
.catch(function (error) {
req.locationError = error;
next();
})
}
|
javascript
|
{
"resource": ""
}
|
q8084
|
home
|
train
|
function home(context, cb) {
var viewModel = _.extend(
{
package: helper.find(context.data, {kind: 'package'})[0]
}, util.docletChildren(context, null, util.mainDocletKinds),
util.docletChildren(context, null, util.subDocletKinds),
util.rstMixin,
_.pick(context, ['readme'])
);
logger.debug('home namespaces', viewModel.namespaces);
util.view('home.rst', viewModel, cb);
}
|
javascript
|
{
"resource": ""
}
|
q8085
|
resolve
|
train
|
function resolve(parent, id) {
if (/^\.\.?\//.test(id) && parent) { // is a relative id
id = parent.replace(/[^\/]+$/, id); // prepend parent's dirname
}
var terms = [];
id.split('/').forEach(function(term) {
if ('..' === term) { terms.pop(); } // remove previous, don't add ..
else if ('.' !== term) { terms.push(term); } // add term
// else if ('.' === term) // ignore .
});
return terms.join('/');
}
|
javascript
|
{
"resource": ""
}
|
q8086
|
translate
|
train
|
function translate(id, filename, buffer, options, next) {
var ext = (filename.match(extexp) || [])[1] || '',
encoding = options.encoding || exports.defaults.encoding,
trans = options.translate, js, nowrap;
// make a list of what not to wrap
nowrap = options.nowrap || exports.defaults.nowrap;
nowrap = [ 'define', 'define.min', 'define.shim' ].concat(nowrap);
// should this code get wrapped with a define?
nowrap = nowrap.some(function(no) {
return no.test ? no.test(id) : (no === id);
});
// convert commonjs to amd
function wrap(err, js) {
if (err) { return next(err); }
var deps = exports.dependencies(id, js), params = [], undef = '';
// make sure require, exports, and module are properly passed into the factory
if (/\brequire\b/.test(js)) { params.push('require'); }
if (/\bexports\b/.test(js)) { params.push('exports'); }
if (/\bmodule\b/.test(js)) { params.push('module'); }
// make sure code follows the `exports` path instead of `define` path once wrapped
if (/\bdefine\.amd\b/.test(js)) { undef = 'var define;'; }
if (deps.length) {
deps = ',' + JSON.stringify(params.concat(deps));
} else if (params.length) {
params = [ 'require', 'exports', 'module' ];
}
js = 'define(' + JSON.stringify(id) + deps + ',function(' + params + ')' +
'{' + js + '\n' + undef + '}' + // rely on hoisting for define
');\n';
next(null, js);
}
// find the translate function
trans = trans && (trans[filename] || trans[id] || trans[ext]);
if (trans) { // user configured translation
return trans(
{ id:id, filename:filename, buffer:buffer },
options, (nowrap ? next : wrap)
);
}
js = buffer.toString(encoding);
// handle javascript files
if ('js' === ext) {
return (nowrap ? next : wrap)(null, js);
}
// handle non-javascript files
if ('json' !== ext) { js = JSON.stringify(js); } // export file as json string
if (nowrap) { return next(null, 'return ' + js); }
return next(null, 'define(' + JSON.stringify(id) + ',' + js + ');\n');
}
|
javascript
|
{
"resource": ""
}
|
q8087
|
wrap
|
train
|
function wrap(err, js) {
if (err) { return next(err); }
var deps = exports.dependencies(id, js), params = [], undef = '';
// make sure require, exports, and module are properly passed into the factory
if (/\brequire\b/.test(js)) { params.push('require'); }
if (/\bexports\b/.test(js)) { params.push('exports'); }
if (/\bmodule\b/.test(js)) { params.push('module'); }
// make sure code follows the `exports` path instead of `define` path once wrapped
if (/\bdefine\.amd\b/.test(js)) { undef = 'var define;'; }
if (deps.length) {
deps = ',' + JSON.stringify(params.concat(deps));
} else if (params.length) {
params = [ 'require', 'exports', 'module' ];
}
js = 'define(' + JSON.stringify(id) + deps + ',function(' + params + ')' +
'{' + js + '\n' + undef + '}' + // rely on hoisting for define
');\n';
next(null, js);
}
|
javascript
|
{
"resource": ""
}
|
q8088
|
getFilename
|
train
|
function getFilename(id, options, next) {
var Path = require('path'),
root = options.root || exports.defaults.root,
map = options.map || {},
forbid = (options.forbid || []).map(function(forbid) {
return forbid.test ? forbid : Path.resolve(root, forbid);
}),
filename;
function test(forbid) {
return forbid.test ? forbid.test(filename) :
(filename.slice(0, forbid.length) === forbid); // filename starts with forbid
}
// mapped modules can be in forbidden places. (define and define.shim should be mapped)
map.define = map.define || Path.resolve(__dirname, 'define');
map['define.min'] = map['define.min'] || Path.resolve(__dirname, 'define.min');
map['define.shim'] = map['define.shim'] || Path.resolve(__dirname, 'define.shim');
// get a filename from the id
filename = map[id] || id; // look for the file in the id map
if ('function' === typeof filename) { filename = filename(id, options); } // if function use result
filename = Path.resolve(root, filename); // relative to root
if (!map[id]) {
// anything below options.root is forbidden
if ('..' === Path.relative(root, filename).slice(0, 2) || forbid.some(test)) {
return next(new Error('Forbidden'), '');
}
}
fs.stat(filename, function(err, stats) {
if (err) { // not found without .js, try with
return fs.exists(filename + '.js', function(exists) {
return next(null, filename + (exists ? '.js' : ''));
});
}
if (stats.isDirectory()) { // directories look for /index.js
return fs.exists(filename + '/index.js', function(exists) {
return next(null, filename + (exists ? '/index.js' : ''));
});
}
return next(null, filename);
});
}
|
javascript
|
{
"resource": ""
}
|
q8089
|
moduleToCode
|
train
|
function moduleToCode(id, r) {
exports.module(id, options, done);
function done(err, result) {
if (err) {
next(err);
next = function(){}; // make sure you only call next(err) once
return;
}
if (result && (!modified || result.modified > modified)) {
modified = result.modified; // update latest last modified date
}
results[r] = result && result.code || '';
if (++doneCount >= ids.length) { alldone(); } // done with all of them
}
}
|
javascript
|
{
"resource": ""
}
|
q8090
|
alldone
|
train
|
function alldone() {
// combine and compress modules
var module = {
code: results.join(''),
modified: modified
};
// no compressing? done.
if (!compress) { return next(null, module); }
compress(module, function(err, js) {
module.code = js.code || js;
next(err, err ? null : module);
});
}
|
javascript
|
{
"resource": ""
}
|
q8091
|
exec_console
|
train
|
function exec_console(func, log, format) {
if (format === 'json') {
func(JSON.stringify(log));
} else {
func(
' ' + log.type + '\n',
'CREATED: ' + log.created + '\t ' + '\n',
'MESSAGE: ' + log.message + '\t ' + log.trace + '\n',
!!log.data ? 'DATA:' + log.data + '\n' : '',
'\n'
);
}
}
|
javascript
|
{
"resource": ""
}
|
q8092
|
withCallback
|
train
|
function withCallback(source, destination, methods) {
return promisifyAll(source, destination, methods, thenify.withCallback)
}
|
javascript
|
{
"resource": ""
}
|
q8093
|
map
|
train
|
function map(arr, fn) {
for (var arr2 = [], a = 0, aa = arr.length; a < aa; ++a) { arr2[a] = fn(arr[a]); }
return arr2;
}
|
javascript
|
{
"resource": ""
}
|
q8094
|
fireWaits
|
train
|
function fireWaits(module) {
map(waits[module.id], function(fn) { fn(module); });
waits[module.id] = [];
}
|
javascript
|
{
"resource": ""
}
|
q8095
|
define
|
train
|
function define(id, deps, exp) {
if (!exp) { exp = deps; deps = [ 'require', 'exports', 'module' ]; }
var module = getModule(undefined, id);
module.children = map(deps, function(dep) { return getModule(module, dep); });
module.loaded = true;
factories[id] = exp;
fireWaits(module);
}
|
javascript
|
{
"resource": ""
}
|
q8096
|
makeRequire
|
train
|
function makeRequire(module) {
var mrequire = function(id, fn) { return require(module, id, fn); };
mrequire.resolve = function(id) { return getModule(module, id).uri; };
mrequire.toUrl = function(id) {
return getModule(module, id.replace(/\.[^.\\\/]+$/, ''))
.uri.replace(/\.js$/i, id.match(/\.[^.\\\/]+$/));
};
mrequire.cache = modules;
mrequire.main = main;
mrequire.map = mapUrlToIds; // allow mapping multiple module ids to a url
return mrequire;
}
|
javascript
|
{
"resource": ""
}
|
q8097
|
getModule
|
train
|
function getModule(parent, id) {
if ('require' === id || 'exports' === id || 'module' === id) {
return { id:id, loaded:true, exports:parent[id] || parent, children:[] };
}
id = resolve(parent, id).replace(/\.js$/i, '');
if (modules[id]) { return modules[id]; }
var uri = canonicalize(urls[id] ? urls[id] : path.replace(/[^\/]*$/, id + '.js')),
module = (modules[id] = { id:id, filename:uri, uri:uri, loaded:false, children:[] });
module.require = makeRequire(module);
waits[id] = [];
return module;
}
|
javascript
|
{
"resource": ""
}
|
q8098
|
require
|
train
|
function require(parent, id, fn) {
if (fn) { return ensure(parent, id, fn); }
var module = getModule(parent, id);
if (!module.loaded) { throw new Error(id + ' not found'); }
if (!('exports' in module)) {
module.parent = parent; // first module to actually require this one is parent
// if define was passed a non-function, just assign it to exports
if ('function' !== typeof factories[id = module.id]) { module.exports = factories[id]; }
else {
module.exports = {};
fn = map(module.children.slice(0, factories[id].length), // don't require prematurely on wrapped commonjs
function(child) { return require(module, child.id); });
if ((fn = factories[id].apply(global, fn))) { module.exports = fn; } // if something was returned, export it instead
}
}
return module.exports;
}
|
javascript
|
{
"resource": ""
}
|
q8099
|
ensure
|
train
|
function ensure(parent, ids, fn) {
ids = [].concat(ids);
var visited = {}, wait = 0;
function done() {
if (fn) { fn.apply(global, map(ids, function(id) { return require(parent, id); })); }
fn = undefined;
}
function visit(module) {
if (module.id in visited) { return; }
if ((visited[module.id] = module.loaded)) { return map(module.children, visit); }
++wait;
waits[module.id].push(function() {
map(module.children, visit);
if (--wait <= 0) { setTimeout(done, 0); }
});
var script;
map(doc.querySelectorAll('script'), function(node) {
if (canonicalize(node.src) === module.uri) { script = node; }
});
if (!script) {
script = doc.createElement('script');
script.onload = script.onerror = script.onreadystatechange = function() {
if ('loading' === script.readyState) { return; }
script.onload = script.onerror = script.onreadystatechange = null;
fireWaits(module);
};
script.defer = true;
script.src = module.uri;
doc.querySelector('head').appendChild(script);
}
}
map(ids, function(id) { visit(getModule(parent, id)); });
if (wait <= 0) { setTimeout(done, 0); } // always async
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.