_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q37200 | _rel_save_button_start | train | function _rel_save_button_start(){
//
//ll('looks like edge (in cb): ' + eeid);
var qstr ='input:radio[name=' + radio_name + ']:checked';
var rval = jQuery(qstr).val();
// ll('rval: ' + rval);
// // TODO: Should I report this too? Smells a
// // bit like the missing properties with
// // setParameter/s(),
// // Change label.
// //conn.setLabel(rval); // does not work!?
// conn.removeOverlay("label");
// conn.addOverlay(["Label", {'label': rval,
// 'location': 0.5,
// 'cssClass': "aLabel",
// 'id': 'label' } ]);
// Kick off callback.
manager.add_fact(ecore.get_id(), source_id,
target_id, rval);
// Close modal.
mdl.destroy();
} | javascript | {
"resource": ""
} |
q37201 | isChild | train | function isChild(child, parent) {
while (child = child.parentNode) {
if (child == parent) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q37202 | isHidden | train | function isHidden(element) {
var parent_styles,
overflow_x,
overflow_y,
overflow,
parent = element.parentNode,
styles;
if (!parent) {
return true;
}
// Always return false for the document element
if (isDocumentElement(parent)) {
return false;
}
// Get the computed styles of the element
styles = getStyle(element);
// Return true if the element is invisible
if ( styles.opacity === '0'
|| styles.display === 'none'
|| styles.visibility === 'hidden') {
return true;
}
return isHidden(parent);
} | javascript | {
"resource": ""
} |
q37203 | isDocumentElement | train | function isDocumentElement(element) {
if ( element == document.body
|| element.nodeType === 9
|| (element.nodeType == 1 && element.nodeName == 'HTML')) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q37204 | collides | train | function collides(element_one, element_two) {
var result,
rect1,
rect2;
if (element_one.nodeName) {
rect1 = element_one.getBoundingClientRect();
} else {
rect1 = element_one;
}
if (element_two.nodeName) {
rect2 = element_two.getBoundingClientRect();
} else {
rect2 = element_two;
}
result = !(
rect1.top > rect2.bottom ||
rect1.right < rect2.left ||
rect1.bottom < rect2.top ||
rect1.left > rect2.right
);
return result;
} | javascript | {
"resource": ""
} |
q37205 | elementAtRectPoints | train | function elementAtRectPoints(element, rect) {
var sample;
// Get the first sample
sample = document.elementFromPoint(rect.left, ~~rect.top);
if (sample == element || isChild(element, sample)) {
return true;
}
// Get the second sample
sample = document.elementFromPoint(rect.left, ~~rect.bottom);
if (sample == element || isChild(element, sample)) {
return true;
}
// Get the third sample
sample = document.elementFromPoint(rect.right, ~~rect.bottom);
if (sample == element || isChild(element, sample)) {
return true;
}
// Get the fourth sample
sample = document.elementFromPoint(rect.right, ~~rect.top);
if (sample == element || isChild(element, sample)) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q37206 | _isVisible | train | function _isVisible(start_element, padding) {
var real_rect,
sample,
result,
rect;
// Check if the start element is in the document
if (!elementInDocument(start_element)) {
return false;
}
// Check if the element is explicitly hidden
if (isHidden(start_element)) {
return false;
}
if (padding == null) {
padding = 2;
}
// Make sure the start element is somewhere on the screen
real_rect = start_element.getBoundingClientRect();
rect = {
bottom : real_rect.bottom + padding,
right : real_rect.right + padding,
left : real_rect.left - padding,
top : real_rect.top - padding
};
// Totally underneath the viewport
if (rect.top > document.documentElement.clientHeight) {
return false;
}
// Totally above the viewport
if (rect.bottom < 0) {
return false;
}
// Totally left of the viewport
if (rect.right < 0) {
return false;
}
// Totally right of the viewport
if (rect.left > document.documentElement.clientWidth) {
return false;
}
result = isElementVisible(start_element);
if (result) {
// If no padding is given, we can also check for occlusions
if (!padding) {
return elementAtRectPoints(start_element, rect);
}
return true;
} else {
return false;
}
function isElementVisible(element) {
var context = getViewContext(element),
ctx_rect;
if (!context) {
return false;
}
// Get the context rectangle
ctx_rect = context.getBoundingClientRect();
// The current element and the start element
// both have to collide with the current context rectangle
// (if the current element equals the start_element we only need
// to check the modified rect to the ctx_rect)
if ( (element == start_element || collides(element, ctx_rect))
&& collides(rect, ctx_rect)) {
// If the context element is the document element,
// no further checks are needed
if (isDocumentElement(context)) {
return true;
}
// Recursively see if the current context is visible
return isElementVisible(context);
}
return false;
}
} | javascript | {
"resource": ""
} |
q37207 | defineApp | train | function defineApp(app) {
app.use('/foo', function appFoo(req, res) {
if (req.xhr) {
var body = {
foo: 'bar'
};
responseSender.sendJSON(res, body);
} else {
responseSender.sendPage(res, 'Foo', '<h1>Bar!</h1>', 200);
}
});
app.use('/fail', function appFail(req, res) {
/* jshint unused: false, quotmark: false */
throw new Error("Don't worry, the error handler will take care of this");
});
app.use('/fail-async', function appFailAsync(req, res) {
/* jshint unused: false, quotmark: false */
setTimeout(function() {
throw new Error("I may be async, but the error handler will still catch me!");
}, 100);
});
app.use('/', express.static(__dirname));
} | javascript | {
"resource": ""
} |
q37208 | train | function( cb ) {
// If we are running in node.js replace the THREE.js XHRLoader
// with an offline version.
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}"); // browser exclude
if (!isBrowser()) {
// Expose 'THREE' for non-compatible scripts
global.THREE = THREE;
// Override XHR Loader
global.THREE.XHRLoader = require('./lib/FileXHRLoader');
}
// Trigger callback
if (cb) cb();
} | javascript | {
"resource": ""
} | |
q37209 | hoc | train | function hoc(Component) {
return class HOC extends React.Component {
/**
* Create a new instance of the HOC with state defaults.
*
* @param {Object} props Props passed from other HOCs.
*/
constructor(props) {
super(props);
this.state = {isLoading: false};
}
/**
* Set the current isLoading state.
*
* @param {Boolean} isLoading Whether the component is currently loading.
*/
setIsLoading(isLoading) {
this.setState({isLoading});
}
/**
* Execute a function that sets the current loading state while it is executing.
*
* @param {Function} func Function to execute. Expect a callback as its first parameter, which,
* when called, resets the current loading state.
*/
loading(func) {
this.setIsLoading(true);
func(this.setIsLoading.bind(this, false));
}
/**
* Render the wrapped component, passing along props from this HOC's internal state.
*
* @returns {XML} The wrapped component with additional props.
*/
render() {
return (
<Component
ref={(elem) => {
this.component = elem;
}}
loading={this.loading.bind(this)}
{...this.props}
{...this.state}
/>
);
}
};
} | javascript | {
"resource": ""
} |
q37210 | repeat | train | function repeat(str, amount) {
var s = ''
, i;
for(i = 0;i < amount;i++) {
s += str;
}
return s;
} | javascript | {
"resource": ""
} |
q37211 | train | function(string, start, end) {
var crc = 0
var x = 0;
var y = 0;
crc = crc ^ (-1);
for(var i = start, iTop = end; i < iTop;i++) {
y = (crc ^ string[i]) & 0xFF;
x = table[y];
crc = (crc >>> 8) ^ x;
}
return crc ^ (-1);
} | javascript | {
"resource": ""
} | |
q37212 | train | function(functionCache, hash, functionString, object) {
// Contains the value we are going to set
var value = null;
// Check for cache hit, eval if missing and return cached function
if(functionCache[hash] == null) {
eval("value = " + functionString);
functionCache[hash] = value;
}
// Set the object
return functionCache[hash].bind(object);
} | javascript | {
"resource": ""
} | |
q37213 | train | function() {
// Get the start search index
var i = index;
// Locate the end of the c string
while(buffer[i] !== 0x00 && i < buffer.length) {
i++
}
// If are at the end of the buffer there is a problem with the document
if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString")
// Grab utf8 encoded string
var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i);
// Update index position
index = i + 1;
// Return string
return string;
} | javascript | {
"resource": ""
} | |
q37214 | enableEnvConfig | train | function enableEnvConfig (grunt, opts) {
var options = opts || {};
var cacheConfig = options.cache;
var getRaw = grunt.config.getRaw;
grunt.config.getRaw = function getRawWrapper (prop) {
if (prop) {
prop = grunt.config.getPropString(prop);
var required = propRequire(prop, /^\$require\.([a-z0-9_$]+(?:\.[a-z0-9_$]+)*)$/i);
if (required) {
return required;
} else {
return preprocessForEach(prop.replace(/([^\\])\./g, '$1\u000E').split('\u000E'), function preprocessEach (obj) {
// when not match the `$require` pattern, behave as `grunt.config.getRaw`
if (typeof obj === 'string' || obj instanceof String) {
var required = propRequire(obj, /^<%=\s*\$require\.([a-z0-9_$]+(?:\.[a-z0-9_$]+)*)\s*%>$/i);
// recursively template requiring is not supported
obj = required ? required : obj;
}
return obj;
});
}
}
return getRaw.apply(this, arguments);
};
function preprocessForEach (props, fn) {
var parent = grunt.config.data
, obj
, eachProp;
while ((eachProp = props.shift()) !== undefined && eachProp.length) {
obj = parent[eachProp];
if (eachProp in parent) {
obj = fn.call(this, obj, parent);
if (cacheConfig) {
parent[eachProp] = obj;
}
parent = obj;
}
if (typeof obj !== 'object') {
break;
}
}
return obj;
}
grunt.template.env = function (env) {
if (typeof env !== 'string' && !(env instanceof String)) throw new TypeError('template.env expects string formated property');
var obj = process.env;
env.replace(/([^\\])\./g, '$1\u000E').split('\u000E').forEach(function (prop) {
obj = obj[prop];
});
return obj;
};
grunt.template.through = function (obj) {
if (typeof obj === 'object') {
return JSON.stringify(obj);
}
return obj;
};
function propRequire (prop, regExpr) {
var matched = prop.match(regExpr);
if (matched) {
var path = grunt.config.get(matched[1]);
grunt.verbose.writeln('$require:' + path);
return require(path);
}
}
} | javascript | {
"resource": ""
} |
q37215 | one_space | train | function one_space(left, right) {
left = left || token;
right = right || next_token;
if (right.id !== '(end)' && !option.white &&
(token.line !== right.line ||
token.thru + 1 !== right.from)) {
warn('expected_space_a_b', right, artifact(token), artifact(right));
}
} | javascript | {
"resource": ""
} |
q37216 | symbol | train | function symbol(s, p) {
var x = syntax[s];
if (!x || typeof x !== 'object') {
syntax[s] = x = {
id: s,
lbp: p || 0,
string: s
};
}
return x;
} | javascript | {
"resource": ""
} |
q37217 | onEntityDraw | train | function onEntityDraw(entity, context) {
context.save();
if (selectionService.isSelected(entity)) {
context.strokeStyle = '#f33';
} else {
context.strokeStyle = '#666';
}
context.strokeRect(
entity.pos.x, entity.pos.y, entity.size.x, entity.size.y);
context.restore();
} | javascript | {
"resource": ""
} |
q37218 | verify | train | function verify(rawMsg, rawSig, rawPub) {
const msg = nacl.util.decodeUTF8(rawMsg);
const sig = nacl.util.decodeBase64(rawSig);
const pub = base58.decode(rawPub);
const m = new Uint8Array(crypto_sign_BYTES + msg.length);
const sm = new Uint8Array(crypto_sign_BYTES + msg.length);
let i;
for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
// Call to verification lib...
return naclBinding.verify(m, sm, pub);
} | javascript | {
"resource": ""
} |
q37219 | require | train | function require(name) {
var module = require.modules[name];
if (!module) throw new Error('failed to require "' + name + '"');
if (!('exports' in module) && typeof module.definition === 'function') {
module.client = module.component = true;
module.definition.call(this, module.exports = {}, module);
delete module.definition;
}
return module.exports;
} | javascript | {
"resource": ""
} |
q37220 | Request | train | function Request(path, client, delim) {
if (!(this instanceof Request)) return new Request(path, client);
// init client
this.client = client;
if (!this.client) throw new Error('hyper-path requires a client to be passed as the second argument');
this.delim = delim || '.';
this.parse(path);
this._listeners = {};
this._scope = {};
this._warnings = {};
} | javascript | {
"resource": ""
} |
q37221 | firstDefined | train | function firstDefined() {
for (var i = 0, l = arguments.length, v; i < l; i++) {
v = arguments[i];
if (typeof v !== 'undefined') return v;
}
return v;
} | javascript | {
"resource": ""
} |
q37222 | process | train | async function process({inputStream, skip, lineHandler, quiet, throttle}) {
skip = skip || 0;
throttle = throttle || Number.MAX_VALUE;
return await new P((resolve, reject) => {
let cursor = 0;
let concurrency = 0;
const errors = [];
const reader = readline.createInterface({input: inputStream});
reader.on('line', async line => {
if (cursor++ < skip || (!quiet && errors.length)) {
return;
}
const lineNo = cursor;
if (++concurrency > throttle) {
reader.pause();
}
try {
await lineHandler(line, cursor);
} catch (e) {
if (!quiet) {
e.line = lineNo;
errors.push(e);
reader.close();
}
} finally {
skip++;
if (--concurrency < throttle) {
reader.resume();
}
}
}).on('close', async () => {
while (skip < cursor)
await P.delay(100);
if (errors.length) {
const e = _.minBy(errors, 'line');
e.errors = errors;
reject(e);
} else {
resolve(skip);
}
});
});
} | javascript | {
"resource": ""
} |
q37223 | itemIsValid | train | function itemIsValid(item) {
if (!('isValid' in item)) {
return true;
}
if (_.isFunction(item.isValid)) {
return item.isValid();
}
return false;
} | javascript | {
"resource": ""
} |
q37224 | mine | train | function mine(js) {
var names = [];
var state = 0;
var ident;
var quote;
var name;
var isIdent = /[a-z0-9_.]/i;
var isWhitespace = /[ \r\n\t]/;
function $start(char) {
if (char === "/") {
return $slash;
}
if (char === "'" || char === '"') {
quote = char;
return $string;
}
if (isIdent.test(char)) {
ident = char;
return $ident;
}
return $start;
}
function $ident(char) {
if (isIdent.test(char)) {
ident += char;
return $ident;
}
if (char === "(" && ident === "require") {
ident = undefined;
return $call;
}
return $start(char);
}
function $call(char) {
if (isWhitespace.test(char)) return $call;
if (char === "'" || char === '"') {
quote = char;
name = "";
return $name;
}
return $start(char);
}
function $name(char) {
if (char === quote) {
return $close;
}
name += char;
return $name;
}
function $close(char) {
if (isWhitespace.test(char)) return $close;
if (char === ")" || char === ',') {
names.push(name);
}
name = undefined;
return $start(char);
}
function $string(char) {
if (char === "\\") {
return $escape;
}
if (char === quote) {
return $start;
}
return $string;
}
function $escape(char) {
return $string;
}
function $slash(char) {
if (char === "/") return $lineComment;
if (char === "*") return $multilineComment;
return $start(char);
}
function $lineComment(char) {
if (char === "\r" || char === "\n") return $start;
return $lineComment;
}
function $multilineComment(char) {
if (char === "*") return $multilineEnding;
return $multilineComment;
}
function $multilineEnding(char) {
if (char === "/") return $start;
if (char === "*") return $multilineEnding;
return $multilineComment;
}
var state = $start;
for (var i = 0, l = js.length; i < l; i++) {
state = state(js[i]);
}
return names;
} | javascript | {
"resource": ""
} |
q37225 | allocate | train | function allocate(height, length) {
var node = new Array(length);
node.height = height;
if (height > 0) {
node.sizes = new Array(length);
}
return node;
} | javascript | {
"resource": ""
} |
q37226 | saveSlot | train | function saveSlot(aList, bList, index, slot) {
setEither(aList, bList, index, slot);
var isInFirst = (index === 0 || index === aList.sizes.length);
var len = isInFirst ? 0 : getEither(aList.sizes, bList.sizes, index - 1);
setEither(aList.sizes, bList.sizes, index, len + length(slot));
} | javascript | {
"resource": ""
} |
q37227 | start | train | function start() {
var donePromise = mediator.promise(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.START, CONSTANTS.DONE_PREFIX));
var errorPromise = mediator.promise(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.START, CONSTANTS.ERROR_PREFIX));
mediator.publish(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.START));
return getTopicPromises(donePromise, errorPromise);
} | javascript | {
"resource": ""
} |
q37228 | stop | train | function stop() {
var donePromise = mediator.promise(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.STOP, CONSTANTS.DONE_PREFIX));
var errorPromise = mediator.promise(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.STOP, CONSTANTS.ERROR_PREFIX));
mediator.publish(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.STOP));
return getTopicPromises(donePromise, errorPromise);
} | javascript | {
"resource": ""
} |
q37229 | forceSync | train | function forceSync() {
var donePromise = mediator.promise(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.FORCE_SYNC, CONSTANTS.DONE_PREFIX));
var errorPromise = mediator.promise(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.FORCE_SYNC, CONSTANTS.ERROR_PREFIX));
mediator.publish(resultSyncSubscribers.getTopic(CONSTANTS.TOPICS.FORCE_SYNC));
return getTopicPromises(donePromise, errorPromise);
} | javascript | {
"resource": ""
} |
q37230 | train | function() {
this.colon = false;
HelpDocument.apply(this, arguments);
this.format = fmt.MARKDOWN_FORMAT;
this.vanilla = true;
this.useCustom = true;
// disable columns
this.use = false;
var format = '* `%s`: %s';
var overrides = {
synopsis: '```synopsis\n%s\n```'
}
this.markdown = {};
var conf = this.conf.markdown || {}, i, key;
var formats = conf.formats || {};
for(i = 0;i < this.sections.length;i++) {
key = this.sections[i];
this.markdown[key] = formats[key] || overrides[key] || format;
}
} | javascript | {
"resource": ""
} | |
q37231 | average | train | function average(array) {
var length = array.length;
if (length === 0) {
throw new RangeError("Error");
}
var index = -1;
var result = 0;
while (++index < length) {
result += array[index];
}
return result / length;
} | javascript | {
"resource": ""
} |
q37232 | checkCompilationType | train | function checkCompilationType( config ) {
if ( config.tfw.compile.type === 'firefoxos' ) {
config.tfw.compile.type = 'web';
} else {
config.tfw.compile.type = 'desktop';
}
} | javascript | {
"resource": ""
} |
q37233 | handleStatusChange | train | function handleStatusChange(response) {
if (response.authResponse) {
logResponse(response);
window.location.hash = '#menu';
updateUserInfo(response);
} else {
window.location.hash = '#login';
}
} | javascript | {
"resource": ""
} |
q37234 | displayMealList | train | function displayMealList() {
// Meal list
logResponse("[displayMealList] displaying meal list.");
var tmpl = $("#meal_list_tmpl").html();
var output = Mustache.to_html(tmpl, meals);
$("#meal-list").html(output).listview('refresh');
} | javascript | {
"resource": ""
} |
q37235 | appendChildren | train | function appendChildren(children, el) {
ensureArray(children)
.forEach(append.bind(el));
return el;
} | javascript | {
"resource": ""
} |
q37236 | train | function(scope) {
console.log(
'Before start to process input files:',
scope.files.map(function(file) {
var rulesCount = file.parsed.rules.length;
rulesCount += ' rule' + (rulesCount > 1 ? 's' : '');
return '\n' + rulesCount + ' in ' + file.config.input;
}).join(',')
);
} | javascript | {
"resource": ""
} | |
q37237 | train | function(scope, config) {
var isAngry = config.mood === 'angry',
isColorExist;
console.log(
'\nProcessing command: ' + scope.command.name
);
if (scope.decl.prop === 'content') {
scope.decl.value = isAngry ?
'"BAD BAD NOT GOOD"' :
'"GOOD GOOD NOT BAD"';
}
isColorExist = scope.rule.decls.some(function(decl) {
if (decl.prop === 'color') {
decl.value = isAngry ? 'red' : 'pink';
return true;
}
if ( ! isAngry && decl.prop === 'font-size') {
decl.value = '48px';
}
});
if ( ! isColorExist) {
scope.rule.append({
prop : 'color',
value : isAngry ? 'red' : 'pink'
});
}
(scope.angrifiedCount || (scope.angrifiedCount = 0));
scope.angrifiedCount++;
} | javascript | {
"resource": ""
} | |
q37238 | dquote | train | function dquote(s) {
var sq = (s.indexOf('\'') >= 0);
var dq = (s.indexOf('"') >= 0);
if (sq && dq) {
s = s.replace(/"/g, '\\"');
dq = false;
}
if (dq) {
s = '\'' + s + '\'';
}
else {
s = '"' + s + '"';
}
return s;
} | javascript | {
"resource": ""
} |
q37239 | train | function (i) {
workers[i] = cluster.fork();
console.log('Creating Worker: ', workers[i].process.pid);
workers[i].on('message', m => {
switch (m.type) {
case 'STARTED':
!startedWorkers && startWatches();
break;
}
});
// Optional: Restart worker on exit
workers[i].on('exit', function (code, signal) {
console.log('Respawning worker', i);
spawn(i);
});
} | javascript | {
"resource": ""
} | |
q37240 | parseNames | train | function parseNames(filePath, prefix, defaultAppName) {
var appName = this.getAppName(filePath, defaultAppName);
var names = {
appShortName: appName,
appName: this.getAppModuleName(prefix, appName),
isPartial: !!filePath.match(/^.*\.partial\.js/)
};
names.isPage = !names.isPartial;
// name of the page used for setting the css style (ex. my.home.page.js would be my.home)
// the class name on the maincontent in HTML would be something like gh-my-home
var lastSlash = filePath.lastIndexOf(delim);
names.uiPartName = filePath.substring(lastSlash + 1)
.replace('.page.js', '')
.replace('.partial.js', '');
// view url is what is used as unique key in template cache for generated HTML
names.viewUrl = 'templates/' + names.uiPartName;
// get the directive and controller name (ex. directive ghAnswerList and controller AnswerListCtrl
var moduleNamePascal = this.pancakes.utils.getPascalCase(filePath)
.replace('Page', '')
.replace('Partial', '');
names.directiveName = prefix + moduleNamePascal;
names.controllerName = moduleNamePascal + 'Ctrl';
return names;
} | javascript | {
"resource": ""
} |
q37241 | getHtml | train | function getHtml(uipart, options) {
options = options || {};
var me = this;
// if any subviews, add them as dependencies
var model = {
isMobile: options.isMobile,
appName: options.appName,
pageCssId: options.appName + 'PageCssId'
};
var deps = _.extend({
subviews: {},
model: model,
pageContent: options.pageContent || ' ',
sideviewContent: options.sideviewContent || ' '
}, this.getJangularDeps());
_.each(uipart.subviews, function (subview, subviewName) {
deps.subviews[subviewName] = me.pancakes.cook(subview, { dependencies: deps });
});
// cook the view; the result will be jeff objects
var view = this.pancakes.cook(uipart.view, { dependencies: deps });
// we can now generate HTML off the jyt objects (using jyt render so angular NOT interpreted)
var html = jangular.jytRender(view);
html = html.replace(/\'/g, '\\\''); // need to protect all single quotes
return html;
} | javascript | {
"resource": ""
} |
q37242 | ensureRowsDeleted | train | function ensureRowsDeleted(rows) {
async.whilst(
() => rows.length,
(cb) => {
rows[0].del(() => {
sheet.getRows(query_options, (err, _rows) => {
rows = _rows;
cb();
});
});
},
next);
} | javascript | {
"resource": ""
} |
q37243 | train | function () {
var self = this;
// Already destroyed.
if (!self.inQueue)
return;
if (self.heartbeat) {
self.heartbeat.stop();
self.heartbeat = null;
}
if (self.socket) {
self.socket.close();
self.socket._meteorSession = null;
}
// Drop the merge box data immediately.
self.collectionViews = {};
self.inQueue = null;
Package.facts && Package.facts.Facts.incrementServerFact(
"livedata", "sessions", -1);
Meteor.defer(function () {
// stop callbacks can yield, so we defer this on destroy.
// sub._isDeactivated() detects that we set inQueue to null and
// treats it as semi-deactivated (it will ignore incoming callbacks, etc).
self._deactivateAllSubscriptions();
// Defer calling the close callbacks, so that the caller closing
// the session isn't waiting for all the callbacks to complete.
_.each(self._closeCallbacks, function (callback) {
callback();
});
});
} | javascript | {
"resource": ""
} | |
q37244 | train | function () {
var self = this;
// For the reported client address for a connection to be correct,
// the developer must set the HTTP_FORWARDED_COUNT environment
// variable to an integer representing the number of hops they
// expect in the `x-forwarded-for` header. E.g., set to "1" if the
// server is behind one proxy.
//
// This could be computed once at startup instead of every time.
var httpForwardedCount = parseInt(process.env['HTTP_FORWARDED_COUNT']) || 0;
if (httpForwardedCount === 0)
return self.socket.remoteAddress;
var forwardedFor = self.socket.headers["x-forwarded-for"];
if (! _.isString(forwardedFor))
return null;
forwardedFor = forwardedFor.trim().split(/\s*,\s*/);
// Typically the first value in the `x-forwarded-for` header is
// the original IP address of the client connecting to the first
// proxy. However, the end user can easily spoof the header, in
// which case the first value(s) will be the fake IP address from
// the user pretending to be a proxy reporting the original IP
// address value. By counting HTTP_FORWARDED_COUNT back from the
// end of the list, we ensure that we get the IP address being
// reported by *our* first proxy.
if (httpForwardedCount < 0 || httpForwardedCount > forwardedFor.length)
return null;
return forwardedFor[forwardedFor.length - httpForwardedCount];
} | javascript | {
"resource": ""
} | |
q37245 | train | function (name, handler, options) {
var self = this;
options = options || {};
if (name && name in self.publish_handlers) {
Meteor._debug("Ignoring duplicate publish named '" + name + "'");
return;
}
if (Package.autopublish && !options.is_auto) {
// They have autopublish on, yet they're trying to manually
// picking stuff to publish. They probably should turn off
// autopublish. (This check isn't perfect -- if you create a
// publish before you turn on autopublish, it won't catch
// it. But this will definitely handle the simple case where
// you've added the autopublish package to your app, and are
// calling publish from your app code.)
if (!self.warned_about_autopublish) {
self.warned_about_autopublish = true;
Meteor._debug(
"** You've set up some data subscriptions with Meteor.publish(), but\n" +
"** you still have autopublish turned on. Because autopublish is still\n" +
"** on, your Meteor.publish() calls won't have much effect. All data\n" +
"** will still be sent to all clients.\n" +
"**\n" +
"** Turn off autopublish by removing the autopublish package:\n" +
"**\n" +
"** $ meteor remove autopublish\n" +
"**\n" +
"** .. and make sure you have Meteor.publish() and Meteor.subscribe() calls\n" +
"** for each collection that you want clients to see.\n");
}
}
if (name)
self.publish_handlers[name] = handler;
else {
self.universal_publish_handlers.push(handler);
// Spin up the new publisher on any existing session too. Run each
// session's subscription in a new Fiber, so that there's no change for
// self.sessions to change while we're running this loop.
_.each(self.sessions, function (session) {
if (!session._dontStartNewUniversalSubs) {
Fiber(function() {
session._startSubscription(handler);
}).run();
}
});
}
} | javascript | {
"resource": ""
} | |
q37246 | train | function (exception, context) {
if (!exception || exception instanceof Meteor.Error)
return exception;
// Did the error contain more details that could have been useful if caught in
// server code (or if thrown from non-client-originated code), but also
// provided a "sanitized" version with more context than 500 Internal server
// error? Use that.
if (exception.sanitizedError) {
if (exception.sanitizedError instanceof Meteor.Error)
return exception.sanitizedError;
Meteor._debug("Exception " + context + " provides a sanitizedError that " +
"is not a Meteor.Error; ignoring");
}
// tests can set the 'expected' flag on an exception so it won't go to the
// server log
if (!exception.expected)
Meteor._debug("Exception " + context, exception.stack);
return new Meteor.Error(500, "Internal server error");
} | javascript | {
"resource": ""
} | |
q37247 | GitBeat | train | function GitBeat(options) {
var self = this;
var url;
options = options || {};
if (typeof options === 'string') {
url = options;
options = {};
}
this.cwd = path.resolve(options.cwd || '');
this.logger = options.logger || noop;
url = url || options.url;
this.isCloned = false;
if (url) {
this.logger('initial clone', url, !!options.done);
this.clone(url, options.done || noop);
}
} | javascript | {
"resource": ""
} |
q37248 | train | function () {
this._super.onenter ();
this.element.action = "javascript:void(0)";
this._scrollbar ( gui.Client.scrollBarSize );
this._flexboxerize (
this.dom.q ( "label" ),
this.dom.q ( "input" )
);
} | javascript | {
"resource": ""
} | |
q37249 | train | function ( label, input ) {
var avail = this.box.width - label.offsetWidth;
var space = gui.Client.isGecko ? 6 : 4;
input.style.width = avail - space + "px";
} | javascript | {
"resource": ""
} | |
q37250 | train | function(clazz, metaData) {
// Apply clazz interface
if (!clazz.__isClazz) {
_.extend(clazz, this.clazz_interface);
}
// Apply interface common for clazz and its prototype
if (!clazz.__interfaces) {
clazz.__interfaces = [];
clazz.prototype.__interfaces = [];
_.extend(clazz, this.common_interface);
_.extend(clazz.prototype, this.common_interface);
}
// Calls sub processors
clazz.__metaProcessors = metaData.meta_processors || {};
var parent = metaData.parent;
if (parent) {
if (!clazz.__isSubclazzOf(parent)) {
throw new Error('Clazz "' + clazz.__name +
'" must be sub clazz of "' + parent.__isClazz ? parent.__name : parent + '"!');
}
}
var processors = clazz.__getMetaProcessors();
_.each(processors, function(processor) {
processor.process(clazz, metaData);
});
// Sets clazz defaults
if (_.isFunction(clazz.__setDefaults)) {
clazz.__setDefaults();
}
} | javascript | {
"resource": ""
} | |
q37251 | train | function() {
var processors = this._processors;
_.each(processors, function(processor, name) {
if (_.isString(processor)) {
processors[name] = meta(processor);
}
});
return processors;
} | javascript | {
"resource": ""
} | |
q37252 | train | function(processors) {
var that = this;
_.each(processors, function(processor, name) {
if (name in that._processors) {
throw new Error('Processor "' + name + '" already exists!');
}
that._processors[name] = processor;
});
return this;
} | javascript | {
"resource": ""
} | |
q37253 | train | function(parent) {
var clazzParent = this;
while (clazzParent) {
if (clazzParent === parent || clazzParent.__name === parent) {
return true;
}
clazzParent = clazzParent.__parent;
}
return false;
} | javascript | {
"resource": ""
} | |
q37254 | train | function(property) {
if (this.hasOwnProperty(property) && !_.isUndefined(this[property])) {
return this[property];
}
if (this.__proto && this.__proto.hasOwnProperty(property) && !_.isUndefined(this.__proto[property])) {
return this.__proto[property];
}
var parent = this.__parent;
while (parent) {
if (parent.hasOwnProperty(property) && !_.isUndefined(parent[property])) {
return parent[property];
}
parent = parent.__parent;
}
} | javascript | {
"resource": ""
} | |
q37255 | train | function(property, level /* fields */) {
var propertyContainers = [];
if (this.hasOwnProperty(property)) {
propertyContainers.push(this[property]);
}
if (this.__proto && this.__proto.hasOwnProperty(property)) {
propertyContainers.push(this.__proto[property]);
}
var parent = this.__parent;
while (parent) {
if (parent.hasOwnProperty(property)) {
propertyContainers.push(parent[property]);
}
parent = parent.__parent;
}
var fields = _.toArray(arguments).slice(2);
var propertyValues = {};
for (var i = 0, ii = propertyContainers.length; i < ii; ++i) {
this.__collectValues(propertyValues, propertyContainers[i], level || 1, fields);
}
return propertyValues;
} | javascript | {
"resource": ""
} | |
q37256 | self | train | function self(collector, container, level, fields, reverse) {
fields = [].concat(fields || []);
_.each(container, function(value, name) {
if (fields[0] && (name !== fields[0])) {
return;
}
if (level > 1 && _.isSimpleObject(value)) {
if (!(name in collector)) {
collector[name] = {};
}
self(collector[name], value, level-1, fields.slice(1));
} else if (reverse || (!(name in collector))) {
collector[name] = value;
}
});
return collector;
} | javascript | {
"resource": ""
} |
q37257 | train | function(FLEX_HOME, done) {
var playersDir = path.join(FLEX_HOME, 'frameworks', 'libs', 'player');
if (fs.existsSync(playersDir) && fs.statSync(playersDir).isDirectory()) {
var tmpDirRoot = os.tmpdir ? os.tmpdir() : os.tmpDir();
var tmpOldPlayersDir = path.join(tmpDirRoot, 'node-playerglobal');
var prepOldPlayerStorage = function(done) {
function cb(err) {
done(err ? new Error('Failed to prepare the storage location for the old "playerglobal.swc" library collection.\nError: ' + err) : null);
}
if (fs.existsSync(tmpOldPlayersDir)) {
async.series(
[
function(done) {
rimraf(tmpOldPlayersDir, done);
},
function(done) {
mkdirp(tmpOldPlayersDir, done);
}
],
cb
);
}
else {
mkdirp(tmpOldPlayersDir, cb);
}
};
var saveOldPlayers = function(done) {
ncp(playersDir, tmpOldPlayersDir, function(err) {
done(err ? new Error('Failed to maintain the old "playerglobal.swc" library collection.\nError: ' + err) : null);
});
};
var installNewPlayers = function(done) {
ncp(downloadDir, playersDir, function(err) {
done(err ? new Error('Failed to install the new "playerglobal.swc" library collection.\nError: ' + err) : null);
});
};
var restoreNonConflictingOldPlayers = function(done) {
ncp(tmpOldPlayersDir, playersDir, { clobber: false }, function(err) {
if (err) {
console.warn('WARNING: Failed to restore any non-conflicting files from the old "playerglobal.swc" library collection.\nError: ' + err);
}
done();
});
};
async.series(
[
prepOldPlayerStorage,
saveOldPlayers,
installNewPlayers,
restoreNonConflictingOldPlayers
],
done
);
}
else {
done(new TypeError('The FLEX_HOME provided does not contain the expected directory structure'));
}
} | javascript | {
"resource": ""
} | |
q37258 | train | function () {
this._super.onready ();
this.element.tabIndex = 0;
this._doctitle ( location.hash );
this.event.add ( "hashchange", window );
} | javascript | {
"resource": ""
} | |
q37259 | when | train | function when(promises) {
promises = arrayify(promises);
var whenPromise = new PromiseFactory();
var pending = promises.length;
var results = [];
var resolve = function (i) {
return function (val) {
results[i] = val;
pending--;
if (pending === 0) {
whenPromise.resolve(results);
}
};
};
promises.forEach(function (p, i) {
if (!p || !p.then) return;
p.then(resolve(i), whenPromise.reject);
});
return whenPromise.promise();
} | javascript | {
"resource": ""
} |
q37260 | PromiseFactory | train | function PromiseFactory() {
var deferred = whenjs.defer();
//var timeout = setTimeout(function () { console.log(t, 'Promise timed out')}, 3000);
this.reject = function (err) {
deferred.reject(err);
};
this.resolve = function (val) {
// clearTimeout(timeout);
deferred.resolve(val);
};
this.promise = function () {
return deferred.promise;
};
} | javascript | {
"resource": ""
} |
q37261 | asPromise | train | function asPromise (val) {
if (val && typeof val.then === 'function') {
return val;
}
var deferred = new PromiseFactory();
deferred.resolve(val);
return deferred.promise();
} | javascript | {
"resource": ""
} |
q37262 | failures | train | function failures (items) {
var fs = [], i, v;
for (i = 0; i < items.length; i += 1) {
v = items[i];
if (!v.passed_) {
fs.push(v);
}
}
return fs;
} | javascript | {
"resource": ""
} |
q37263 | train | function() {
return this.__all__.reduce(function(all, mixin) {
return mixin instanceof Mixin.__class__ ?
all.concat(mixin.__flatten__()) :
all.concat([mixin]);
}, []);
} | javascript | {
"resource": ""
} | |
q37264 | train | function(reopen, name) {
return function() {
// the `reopen` function that was passed in to this function will continue
// the process of reopening to the function that this is monkey-patching.
// it is not a recursive call.
// the `recursiveReopen` function, on the other hand, is the reopen
// function that's actually defined on the class object and will allow us
// to restart the reopen process from the beginning for each individual
// mixin that we find.
var recursiveReopen = Class.__metaclass__.prototype[name];
var args = _.toArray(arguments);
var properties = args.shift();
if (properties instanceof Mixin.__class__) {
properties.__flatten__().forEach(function(mixin) {
recursiveReopen.call(this, mixin);
}, this);
properties = {};
}
args.unshift(properties);
return reopen.apply(this, args);
};
} | javascript | {
"resource": ""
} | |
q37265 | parseModule | train | function parseModule(fileInfo) {
var moduleName = file2modulename(fileInfo.relativePath);
var sourceFile = new SourceFile(moduleName, fileInfo.content);
var comments = [];
var moduleTree;
var parser = new Parser(sourceFile);
// Configure the parser
parser.handleComment = function(range) {
comments.push({ range: range });
};
traceurOptions.setFromObject(service.traceurOptions);
try {
// Parse the file as a module, attaching the comments
moduleTree = parser.parseModule();
attachComments(moduleTree, comments);
} catch(ex) {
// HACK: sometime traceur crashes for various reasons including
// Not Yet Implemented (NYI)!
log.error(ex.stack);
moduleTree = {};
}
log.debug(moduleName);
moduleTree.moduleName = moduleName;
// We return the module AST but also a collection of all the comments
// since it can be helpful to iterate through them without having to
// traverse the AST again
return {
moduleTree: moduleTree,
comments: comments
};
} | javascript | {
"resource": ""
} |
q37266 | train | function (name, contents, hash) {
this.actionQueue.push(this.webdriverClient.setCookie.bind(this.webdriverClient, {name: name, value: contents}));
this.actionQueue.push(this._setCookieCb.bind(this, name, contents, hash));
return this;
} | javascript | {
"resource": ""
} | |
q37267 | train | function (name, cookie, hash) {
this.actionQueue.push(this.webdriverClient.getCookie.bind(this.webdriverClient, name));
this.actionQueue.push(this._cookieCb.bind(this, name, hash));
return this;
} | javascript | {
"resource": ""
} | |
q37268 | send | train | function send(pool, id, event, message) {
const socket = pool.sockets.connected[id];
if (socket) {
return socket.emit(event, message);
} else {
console.log(`Cannot send ${event} to disconnected socket ${id}`);
}
} | javascript | {
"resource": ""
} |
q37269 | newChannel | train | function newChannel() {
let chan = new Channel();
let result = chan.send.bind(chan);
result._inst = chan;
return result;
} | javascript | {
"resource": ""
} |
q37270 | variance | train | function variance(array) {
var length = array.length;
if (length === 0) {
throw new RangeError('Error');
}
var index = -1;
var mean = 0;
while (++index < length) {
mean += array[index] / length;
}
var result = 0;
for (var i = 0; i < length; i++) {
result += Math.pow(array[i] - mean, 2);
}
return 1 / length * result;
} | javascript | {
"resource": ""
} |
q37271 | Swig | train | function Swig() {
var opts = (app.config.engines && app.config.engines.swig) || {};
this.options = protos.extend({
cache: false
}, opts);
swig.setDefaults(this.options); // Set options for swig
this.module = swig;
this.multiPart = true;
this.extensions = ['swig', 'swig.html'];
} | javascript | {
"resource": ""
} |
q37272 | train | function(name) {
if (debuggers[name]) {
return debuggers[name];
}
var dbg = function(fmt) {
// if this debugger is not enabled, do nothing.
// Check it every time so we can enable or disable a debugger at runtime.
// It won't be slow.
if (!enableStatus[this._name]) {
return;
}
fmt = coerce.apply(this, arguments);
var curr = +new Date(); // IE8 don't have `Date.now()`
var ms = curr - (this._timestamp || curr);
this._timestamp = curr;
if (isChrome) {
fmt = '%c' + name + '%c ' + fmt + ' %c+' + humanize(ms);
w.global.console.log(fmt, this._style, this._msgStyle, this._style);
} else {
fmt = name + ' ' + fmt + ' +' + humanize(ms);
if (w.global.console && w.global.console.log) {
w.global.console.log(fmt);
}
// Any one want to alert debug message? I think it's annoying.
}
};
dbg._name = name;
dbg._msgStyle = styles[0];
dbg._style = style();
enableStatus[name] = debug.enabled(name);
debuggers[name] = dbg.bind(dbg);
return debuggers[name];
} | javascript | {
"resource": ""
} | |
q37273 | train | function(fmt) {
if (fmt instanceof Error) {
return fmt.stack || fmt.message;
} else {
return w.format.apply(this, arguments);
}
} | javascript | {
"resource": ""
} | |
q37274 | train | function(ms) {
var sec = 1000;
var min = 60 * 1000;
var hour = 60 * min;
if (ms >= hour) {
return (ms / hour).toFixed(1) + 'h';
}
if (ms >= min) {
return (ms / min).toFixed(1) + 'm';
}
if (ms >= sec) {
return (ms / sec | 0) + 's';
}
return ms + 'ms';
} | javascript | {
"resource": ""
} | |
q37275 | wxappEntry | train | function wxappEntry() {
const regex = /src\/pages\/([^\/]+)\/[^\.]+.js/;
return {
entry: () => {
let pages = {}
let core = []
glob.sync(`./src/pages/**/*.js`).forEach(x => {
const name = x.match(regex)[1]
const key = `pages/${name}/${name}`
pages[key] = x
})
return Object.assign({}, pages, {
app: [
//'webpack-dev-server/client',
//'webpack/hot/only-dev-server',
'./src/app.js'
]
})
}
}
} | javascript | {
"resource": ""
} |
q37276 | setup | train | function setup() {
// check if config directory is given
if( _config_path !== -1 ) {
// get path
var config_path = path.resolve( process.argv[ _config_path + 1 ] );
// check if directory exists and is a valid directory
fs.stat( config_path, function( err, stats ) {
if( err && err.code === "ENOENT" ) {
process.stdout.write( "The given directory doesn't exists.\n".red );
} else if( err ) {
// unknown error
process.stdout.write( (err.message + "\n").red );
} else if( !stats.isDirectory() ) {
process.stdout.write( "The given config directory is not an actual directory.\n".red );
} else {
readConfigDir( config_path );
}
} );
return;
}
// ask for config directory
ask( "Where are your config files? ", function( c_path ) {
readConfigDir( c_path );
} );
} | javascript | {
"resource": ""
} |
q37277 | handleConfigEntry | train | function handleConfigEntry ( defaults, values, parent_name, cb ) {
var entries = Object.keys( defaults ),
c = 0;
var cont = function () { // entry handling function
if( c < entries.length ) {
var key = entries[ c ],
entry = defaults[ key ];
if ( typeof entry === "string" || typeof entry === "number" || typeof entry === "boolean" || entry == undefined ) {
ask( ( parent_name ? parent_name + "." + key.blue : key.blue ) + " (" + entry.toString().yellow + "): ", function ( newValue ) {
if ( newValue === "" ) {
newValue = defaults[ key ];
}
values[ key ] = newValue;
c++;
cont(); // continue
} );
} else if ( entry instanceof Array ) { // support for arrays
var array = values[ key ] = [],
_proto = defaults[ key ][ 0 ];
if ( _proto ) {
var array_handler = function ( num ) {
num = parseInt( num );
if( num ) { // this makes sure num > 0
var cc = -1;
var array_item_handler = function () {
cc++;
if( cc < num ) {
array.push( {} );
var i = array[ array.length - 1 ];
handleConfigEntry( _proto, i, ( parent_name ? parent_name + "." + key : key ) + "." + cc, array_item_handler );
} else {
c++;
cont(); // done with the array
}
};
array_item_handler(); // begin with the array
} else {
ask( "Number of entries for " + ( parent_name ? parent_name + "." + key.blue : key.blue ) + " ? ", array_handler );
}
};
ask( "Number of entries for " + ( parent_name ? parent_name + "." + key.blue : key.blue ) + " ? ", array_handler );
} else {
c++;
cont();
}
} else {
values[ key ] = {};
// recurse down the object
handleConfigEntry( defaults[ key ], values[ key ], ( parent_name ? parent_name + "." + key : key ), function () {
c++;
cont();
} );
}
} else {
if ( cb ) {
cb(); // done :)
}
}
};
// begin
cont();
} | javascript | {
"resource": ""
} |
q37278 | train | function (paths, obj, defaultValue = null) {
if (!Array.isArray(paths)) {
throw new Error("paths must be an array of strings");
}
let res = defaultValue;
paths.some(path => {
const result = this.getFlattened(path, obj, defaultValue);
if (result !== defaultValue) {
res = result;
return true;
}
return false;
});
return res;
} | javascript | {
"resource": ""
} | |
q37279 | train | function (obj) {
"use strict";
if (Object.getPrototypeOf(obj) !== Object.prototype) {
throw Error("obj must be an Object");
}
return Object.keys(obj)[0] || null;
} | javascript | {
"resource": ""
} | |
q37280 | train | function (key, styles) {
key = camelToKebab(key)
let stylesText = ''
for (const k in styles) {
if (styles.hasOwnProperty(k)) {
stylesText += camelToKebab(k) + ':' + styles[k] + ';'
}
}
const styleText = `@${key}{${stylesText}}`
appendCss(styleText, 'dom-added-rules')
} | javascript | {
"resource": ""
} | |
q37281 | preHandleSrc | train | function preHandleSrc (cssSrc) {
/*
* fix like: .a{ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e6529dda', endColorstr='#e6529dda', GradientType=0)\9;}
* which has two semicolon( : ) will cause parse error.
*/
cssSrc = cssSrc.replace(/progid(\s)?:(\s)?/g, '#tidy1#');
/*
* fix absolute url path like:
* .a { background: url("http://www.qq.com/one.png");}
*
*/
cssSrc = cssSrc.replace(/:\/\//g, '#tidy2#');
/*
* fix base64 url like:
* .a { background: url("data:image/png;base64,iVBOMVEX///////////////+g0jAqu8zdII=");}
*
*/
cssSrc = cssSrc.replace(/data[\s\S]+?\)/g, function(match){
match = match.replace(/:/g, '#tidy3#');
match = match.replace(/;/g, '#tidy4#');
match = match.replace(/\//g, '#tidy5#');
return match;
});
/*
* fix multiple line comment include single comment //
* eg: / * sth // another * /
*/
cssSrc = cssSrc.replace(/\/\*[\s\S]+?\*\//g, function(match){
// handle single comment //
match = match.replace(/\/\//g, '#tidy6#');
return match;
});
/*
* fix single comment like: // something
* It can't works in IE, and will cause parse error
* update: handle single line for compressive case
*/
cssSrc = cssSrc.replace(/(^|[^:|'|"|\(])\/\/.+?(?=\n|\r|$)/g, function(match){
// Handle compressive file
if (match.indexOf('{') === -1 || match.indexOf('}') === -1) {
var targetMatch;
//handle first line
if (match.charAt(0) !== '/' ) {
// remove first string and / and \
targetMatch = match.substr(1).replace(/\\|\//g, '');
return match.charAt(0) + '/*' + targetMatch + '*/';
} else {
targetMatch = match.replace(/\\|\//g, '');
return '/*' + targetMatch + '*/';
}
} else {
throw new Error('There maybe some single comment // in this file.');
}
});
return cssSrc;
} | javascript | {
"resource": ""
} |
q37282 | train | function (code, language, bare) {
var result;
if (typeof hljs !== 'undefined') {
if (language) {
try {
result = hljs.highlight(language, code, true);
}
catch (e) {
Ember.warn(
'[marked] Failing to highlight some code with language `' + language +
'`, trying auto-detecting language (error: ' + e + ').'
);
result = hljs.highlightAuto(code);
}
}
else {
result = hljs.highlightAuto(code);
}
result.value = '<pre><code>' + result.value + '</code></pre>';
if (bare) {
return result;
}
else {
return result.value;
}
}
else {
result = '<pre><code>' + (code || '').replace(/<>&/g, entitiesReplacer) + '</code></pre>';
if (bare) {
return {value: result, language: null};
}
else {
return result;
}
}
} | javascript | {
"resource": ""
} | |
q37283 | _parseErrors | train | function _parseErrors() {
let errors = [].slice.call(arguments);
let parsed = [];
errors.forEach(err => {
let message = (err instanceof Error) ? err.stack : err.toString();
parsed.push(message);
});
return parsed;
} | javascript | {
"resource": ""
} |
q37284 | _log | train | function _log(message) {
if (cluster.isMaster) {
// write directly to the log file
console.log(_format(message));
}
else {
// send to master
cluster.worker.process.send({
type: "logging",
data: {
message: message,
workerID: cluster.worker.id,
pid: cluster.worker.process.pid
}
});
}
} | javascript | {
"resource": ""
} |
q37285 | BaseView | train | function BaseView (properties, application) {
// note that if application is not defined, this.application will
// default to the default, global application.
this.application = application;
this._onParent = _.bind(this._onParent, this);
SubindableObject.call(this, properties);
/**
* The main application that instantiated this view
* @property application
* @type {Application}
*/
this.initialize();
// ref back to this context for templates
this["this"] = this;
} | javascript | {
"resource": ""
} |
q37286 | train | function (data) {
this.on("change:parent", this._onParent);
// copy the data to this object. Note this shaves a TON
// of time off initializing any view, especially list items if we
// use this method over @setProperties data
if (false) {
for(var key in data) {
this[key] = data[key];
}
}
// necessary to properly dispose this view so it can be recycled
if (this.parent) this._onParent(this.parent);
} | javascript | {
"resource": ""
} | |
q37287 | train | function () {
var path = [], cp = this;
while (cp) {
path.unshift(cp.name || cp.constructor.name);
cp = cp.parent;
}
return path.join(".");
} | javascript | {
"resource": ""
} | |
q37288 | train | function () {
// if rendered, then just return the fragment
if (this._rendered) {
return this.section.render();
}
this._rendered = true;
if (this._cleanupJanitor) {
this._cleanupJanitor.dispose();
}
if (!this.section) {
this._createSection();
}
this.willRender();
this.emit("render");
var fragment = this.section.render();
this.didRender();
this._updateVisibility();
return fragment;
} | javascript | {
"resource": ""
} | |
q37289 | train | function (search) {
if (!this.section) this.render();
var el = noselector(this.section.getChildNodes());
if (arguments.length) {
return el.find(search).andSelf().filter(search);
}
return el;
} | javascript | {
"resource": ""
} | |
q37290 | merge | train | function merge( elem, callback ) {
var old = find( destChildren, elem.name ),
nl;
// merge with old element
if ( old ) {
if ( typeof callback == 'function' ) {
return callback( old );
}
_.merge( old.attribs, elem.attribs );
if ( elem.children ) {
combine( old, elem );
}
// append new element
} else {
if ( dest.children ) {
utils.appendChild( dest, elem );
} else {
utils.prepend( destChildren[ 0 ], elem );
// fix for domutils issue
elem.parent = destChildren[ 0 ].parent;
destChildren.unshift( elem );
destChildren.splice( destChildren.indexOf( elem ) + 1, 0, nl );
}
}
} | javascript | {
"resource": ""
} |
q37291 | mergeDoctype | train | function mergeDoctype( elem ) {
merge( elem, function( old ) {
utils.replaceElement( old, elem );
destChildren[ destChildren.indexOf( old ) ] = elem;
} );
} | javascript | {
"resource": ""
} |
q37292 | signup | train | async function signup (username, password, options = {}) {
let { email = null, profile = {}, roles = [] } = options
let user = await User.create({ username, email })
user.sign = await UserSign.create({ user, password })
user.profile = await UserProfile.create({ user, profile })
user.roles = await UserRole.createBulk(roles.map((code) => ({ user, code })))
await user.save()
return user
} | javascript | {
"resource": ""
} |
q37293 | signin | train | async function signin (username, password, options = {}) {
let { agent } = options
let user = await User.only({ username })
let sign = user && await UserSign.only({ user })
let valid = sign && await sign.testPassword(password)
if (!valid) {
throw new Error('Signin failed!')
}
await user.sync()
session.signed = user
return user
} | javascript | {
"resource": ""
} |
q37294 | FunctionCompiler | train | function FunctionCompiler() {
var _this;
_classCallCheck(this, FunctionCompiler);
_this = _possibleConstructorReturn(this, _getPrototypeOf(FunctionCompiler).call(this));
/**
* Compile sequence.
* @type {Array<function>}
*/
_this._sequence = [_this._uncomment, _this._validate, _this._extract, _this._direct, _this._compile, _this._definehead, _this._injecthead, _this._macromize];
/**
* Options from Grunt.
* @type {Map}
*/
_this._options = null;
/**
* Hm.
*/
_this._macros = null;
/**
* Mapping script tag attributes.
* This may be put to future use.
* @type {Map<string,string>}
*/
_this._directives = null;
/**
* Processing intstructions.
* @type {Array<Instruction>}
*/
_this._instructions = null;
/**
* Compiled arguments list.
* @type {Array<string>}
*/
_this._params = null;
/**
* Tracking imported functions.
* @type {Map<string,string>}
*/
_this._functions = {};
/**
* Did compilation fail just yet?
* @type {boolean}
*/
_this._failed = false;
return _this;
} | javascript | {
"resource": ""
} |
q37295 | ScriptCompiler | train | function ScriptCompiler() {
var _this4;
_classCallCheck(this, ScriptCompiler);
_this4 = _possibleConstructorReturn(this, _getPrototypeOf(ScriptCompiler).call(this));
_this4.inputs = {};
return _this4;
} | javascript | {
"resource": ""
} |
q37296 | strip | train | function strip(script) {
script = this._stripout(script, '<!--', '-->');
script = this._stripout(script, '/*', '*/');
script = this._stripout(script, '^//', '\n');
return script;
} | javascript | {
"resource": ""
} |
q37297 | Runner | train | function Runner() {
_classCallCheck(this, Runner);
this.firstline = false;
this.lastline = false;
this.firstchar = false;
this.lastchar = false;
this._line = null;
this._index = -1;
} | javascript | {
"resource": ""
} |
q37298 | Output | train | function Output() {
var body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
_classCallCheck(this, Output);
this.body = body;
this.temp = null;
} | javascript | {
"resource": ""
} |
q37299 | getState | train | function getState(element) {
assertType(element, Node, false, 'Invalid element specified');
let state = element.state || element.getAttribute(Directive.STATE);
if (!state || state === '')
return null;
else
return state;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.