_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q48100
preprocessorcery
train
function preprocessorcery(infile, info, callback) { applicable(infile, info, (err, preprocessors) => { if (err) return callback(err); const q = queue(1); preprocessors.forEach((preprocessor) => { const outfile = newfile(infile); q.defer((next) => { preprocessor(infile, outfile, (err) => { if (err) return next(err); infile = outfile; next(); }); }); }); q.await((err) => { if (err) return callback(err); // infile has been changed to the output file by this point callback(null, infile); }); }); }
javascript
{ "resource": "" }
q48101
copy
train
function copy(finished) { fs.createReadStream(infile) .once('error', callback) .pipe(fs.createWriteStream(outfile)) .once('error', callback) .on('finish', finished); }
javascript
{ "resource": "" }
q48102
cleanUpNodeJSDoc
train
function cleanUpNodeJSDoc( node, JSDocCommentValue = getJSDocCommentValue(node), ) { t.removeComments(node); t.addComment(node, 'leading', createJSDocCommentValue(JSDocCommentValue)); }
javascript
{ "resource": "" }
q48103
renderHtmlAst
train
function renderHtmlAst(node, { components }) { if (node.type === 'root') { // NOTE: wrap children with React.Fragment, to avoid div wrapper from `hast-to-hyperscript` node = { type: 'element', tagName: Fragment, properties: {}, children: node.children, }; } function h(name, props, children) { return React.createElement( getReactElement(name, components), props, getReactChildren(name, children), ); } return toH(h, node); }
javascript
{ "resource": "" }
q48104
train
function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return request; }
javascript
{ "resource": "" }
q48105
train
function(method, data, callback) { xhr.open(method, url, true, user, password); if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*"); if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); }); if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType); if (responseType != null) xhr.responseType = responseType; if (timeout > 0) xhr.timeout = timeout; if (callback == null && typeof data === "function") callback = data, data = null; if (callback != null && callback.length === 1) callback = fixCallback(callback); if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); }); event.call("beforesend", request, xhr); xhr.send(data == null ? null : data); return request; }
javascript
{ "resource": "" }
q48106
load_ipython_extension
train
function load_ipython_extension() { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(181), __webpack_require__(178), __webpack_require__(179), __webpack_require__(180), __webpack_require__(560), __webpack_require__(182), __webpack_require__(216), __webpack_require__(349), __webpack_require__(504)], __WEBPACK_AMD_DEFINE_RESULT__ = (function (Extension, Jupyter, events, utils, codecell, d3_selection, trial, history, nowutils) { console.log("<<<LOAD noworkflow 2>>>"); var notebook = Jupyter.notebook; Extension.register_renderer(notebook, trial, history, nowutils, d3_selection); Extension.render_cells(notebook); }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); }
javascript
{ "resource": "" }
q48107
diagonal
train
function diagonal(s, d) { if (s.dy == undefined) { s.dy = 0; } if (d.dy == undefined) { d.dy = 0; } let path = `M ${s.x} ${(s.y + s.dy)} C ${(s.x + d.x) / 2} ${(s.y + s.dy)}, ${(s.x + d.x) / 2} ${(d.y + d.dy)}, ${d.x} ${(d.y + d.dy)}`; return path; }
javascript
{ "resource": "" }
q48108
register_renderer
train
function register_renderer(notebook, trial, history, utils, d3_selection) { /* Get an instance of output_area from a CodeCell instance */ var _notebook$get_cells$r = notebook.get_cells().reduce(function (result, cell) { return cell.output_area ? cell : result; }, {}), output_area = _notebook$get_cells$r.output_area; /* History mime */ var append_history = function append_history(data, metadata, element) { var div = document.createElement('div'); element.append(div); var graph = new history.HistoryGraph('history-' + utils.makeid(), div, { width: data.width, height: data.height, hintMessage: "" }); graph.load(data); return div; }; /* Trial mime */ var append_trial = function append_trial(data, metadata, element) { var div = document.createElement('div'); element.append(div); var graph = new trial.TrialGraph('trial-' + utils.makeid(), div, { width: data.width, height: data.height }); graph.load(data, data.trial1, data.trial2); return div; }; /** * Register the mime type and append_history function with output_area */ output_area.register_mime_type('application/noworkflow.history+json', append_history, { safe: true, index: 0 }); output_area.register_mime_type('application/noworkflow.trial+json', append_trial, { safe: true, index: 0 }); }
javascript
{ "resource": "" }
q48109
linkCss
train
function linkCss(component) { const destination = path.join(demo, component); process.chdir(destination); const dist = path.join(packages, component, 'dist'); const source = path.relative(destination, dist); fs.readdirSync(source).forEach(file => { fs.symlinkSync(path.join(source, file), file); }); console.log(chalk.green('success'), 'Linked demo CSS'); }
javascript
{ "resource": "" }
q48110
updateDemo
train
function updateDemo(component) { const source = path.join(packages, component, 'demo'); const destination = path.join(demo, component); ncp(source, destination, error => { if (error) { console.log(chalk.red('error'), error); } else { rimraf(source, () => { console.log(chalk.green('success'), 'Updated component demo'); execSync(`yarn build --scope @zendeskgarden/css-${component}`); linkCss(component); execSync(`yarn start --open=${component}`); }); } }); }
javascript
{ "resource": "" }
q48111
addComponent
train
function addComponent(name) { const source = path.join(packages, '.template'); const destination = path.join(packages, name); if (fs.existsSync(destination)) { console.log(chalk.red('error'), 'Component package exists'); } else { ncp(source, destination, error => { if (error) { console.log(chalk.red('error'), error); } else { const items = walk(destination, { nodir: true }); items.forEach(item => { const string = fs.readFileSync(item.path, 'utf8'); const template = Handlebars.compile(string); const data = template({ component: name }); fs.writeFileSync(item.path, data, 'utf8'); }); console.log(chalk.green('success'), 'Added new component'); execSync('yarn postinstall'); updateDemo(name); } }); } }
javascript
{ "resource": "" }
q48112
toProperties
train
function toProperties(variables) { const categories = Object.keys(variables); const valueOf = (category, value) => { let retVal; if (category === 'color') { retVal = `rgb(${value.r}, ${value.g}, ${value.b})`; } else if (category === 'font-family') { retVal = value .map(font => { return font.indexOf(' ') === -1 ? font : `'${font}'`; }) .join(', '); } else { retVal = value; } return retVal; }; return categories.reduce((retVal, category) => { const keys = Object.keys(variables[category]); keys.forEach(key => { const value = valueOf(category, variables[category][key]); const _key = key.length > 0 ? `${category}-${key}` : `${category}`; retVal.push(`--zd-${_key}: ${value};`); }); return retVal; }, []); }
javascript
{ "resource": "" }
q48113
train
function (/*Date*/date, /*String*/interval, /*int*/amount) { var res = addTransform(interval, date, amount || 0); amount = res[0]; var property = res[1]; var sum = new Date(+date); var fixOvershoot = res[2]; if (property) { sum["set" + property](sum["get" + property]() + amount); } if (fixOvershoot && (sum.getDate() < date.getDate())) { sum.setDate(0); } return sum; // Date }
javascript
{ "resource": "" }
q48114
train
function (/*Date*/date1, /*Date?*/date2, /*String*/interval, utc) { date2 = date2 || new Date(); interval = interval || "day"; return differenceTransform(interval, date1, date2, utc); }
javascript
{ "resource": "" }
q48115
train
function (leftContext, rightContext) { var leftMatch = leftContext.match, fh = leftMatch.factHash, alias = this.__alias, rightFact = rightContext.fact; fh[alias] = rightFact.object; var ret = this.constraint.assert(fh); fh[alias] = null; return ret; }
javascript
{ "resource": "" }
q48116
getSeverity
train
function getSeverity(config, ruleId) { const rules = config && config.rules const ruleOptions = rules && rules[ruleId] const severity = Array.isArray(ruleOptions) ? ruleOptions[0] : ruleOptions switch (severity) { case 2: case "error": return 2 case 1: case "warn": return 1 default: return 0 } }
javascript
{ "resource": "" }
q48117
getCommentAt
train
function getCommentAt(message, sourceCode) { if (sourceCode != null) { const loc = { line: message.line, column: message.column - 1 } const index = sourceCode.getIndexFromLoc(loc) const options = { includeComments: true } const comment = sourceCode.getTokenByRangeStart(index, options) if ( comment != null && (comment.type === "Line" || comment.type === "Block") ) { return comment } } return undefined }
javascript
{ "resource": "" }
q48118
format
train
function format(text) { const lintResult = linter.executeOnText(text) return lintResult.results[0].output || text }
javascript
{ "resource": "" }
q48119
createIndex
train
function createIndex(dirPath) { const dirName = path.basename(dirPath) return format(`/** DON'T EDIT THIS FILE; was created by scripts. */ "use strict" module.exports = { ${fs .readdirSync(dirPath) .map(file => path.basename(file, ".js")) .map(id => `"${id}": require("./${dirName}/${id}"),`) .join("\n ")} } `) }
javascript
{ "resource": "" }
q48120
operative
train
function operative(module, dependencies) { var getBase = operative.getBaseURL; var getSelf = operative.getSelfURL; var OperativeContext = operative.hasWorkerSupport ? operative.Operative.BrowserWorker : operative.Operative.Iframe; if (typeof module == 'function') { // Allow a single function to be passed. var o = new OperativeContext({ main: module }, dependencies, getBase, getSelf); var singularOperative = function() { return o.api.main.apply(o, arguments); }; singularOperative.transfer = function() { return o.api.main.transfer.apply(o, arguments); }; // Copy across exposable API to the returned function: for (var i in o.api) { if (hasOwn.call(o.api, i)) { singularOperative[i] = o.api[i]; } } return singularOperative; } return new OperativeContext(module, dependencies, getBase, getSelf).api; }
javascript
{ "resource": "" }
q48121
train
function(input, onlyPrimitives, options) { if ( typeof input === 'boolean' || typeof input === 'number' || typeof input === 'function' || input === null || input instanceof Date ) { return true; } if (typeof input === 'string' && input.indexOf('\n') === -1) { return true; } if (options.inlineArrays && !onlyPrimitives) { if (Array.isArray(input) && isSerializable(input[0], true, options)) { return true; } } return false; }
javascript
{ "resource": "" }
q48122
_handleCommandResult
train
function _handleCommandResult(result) { // if we're running via the cli, we can print human-friendly responses // otherwise we return proper JSON logger.info('handling command result'); if (result.result) { logger.debug(result.result); } else if (result.error) { logger.error(result.error); } if (result.error) { if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.reject(result.error); } else { console.error(JSON.stringify({ error:result.error.message })); process.exit(1); } } else { if (_.isString(result.result)) { var response = { message: result.result }; if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.resolve(response); } else { console.log(JSON.stringify(response)); process.exit(0); } } else { if (process.env.MAVENSMATE_CONTEXT !== 'cli') { result.resolve(result.result); } else { console.log(JSON.stringify(result.result)); process.exit(0); } } } }
javascript
{ "resource": "" }
q48123
train
function(opts) { this.name = opts.name; this.path = opts.path; this.workspace = opts.workspace; this.subscription = opts.subscription; this.origin = opts.origin; this.username = opts.username; this.password = opts.password; this.accessToken = opts.accessToken; this.refreshToken = opts.refreshToken; this.instanceUrl = opts.instanceUrl; this.package = opts.package; this.orgType = opts.orgType; this.sfdcClient = opts.sfdcClient; this.requiresAuthentication = true; this.settings = {}; this.packageXml = null; this.orgMetadata = null; this.lightningIndex = null; this.metadataHelper = null; this.keychainService = new KeychainService(); this.logService = new LogService(this); this.symbolService = new SymbolService(this); this.lightningService = new LightningService(this); }
javascript
{ "resource": "" }
q48124
_loadCmds
train
function _loadCmds(dirpath) { if (fs.existsSync(dirpath) && fs.statSync(dirpath).isDirectory()) { var commandFiles = util.walkSync(dirpath); _.each(commandFiles, function(cf) { _require(cf); }); } else { logger.debug('Directory not found '+dirpath); throw new Error('Command directory not found'); } }
javascript
{ "resource": "" }
q48125
_findProjectPathById
train
function _findProjectPathById(id) { logger.debug('_findProjectPathById'); logger.debug(id); var projectPathToReturn; var workspaces = config.get('mm_workspace'); if (!_.isArray(workspaces)) { workspaces = [workspaces]; } logger.silly(workspaces); _.each(workspaces, function(workspacePath) { // /foo/bar/project // /foo/bar/project/config/.settings logger.silly(workspacePath); var projectPaths = util.listDirectories(workspacePath); logger.silly(projectPaths); _.each(projectPaths, function(projectPath) { var settingsPath = path.join(projectPath, 'config', '.settings'); if (fs.existsSync(settingsPath)) { var settings = util.getFileBody(settingsPath, true); if (settings.id === id) { projectPathToReturn = projectPath; return false; } } }); }); return projectPathToReturn; }
javascript
{ "resource": "" }
q48126
IndexService
train
function IndexService(opts) { util.applyProperties(this, opts); if (this.project) { this.metadataHelper = new MetadataHelper({ sfdcClient : this.project.sfdcClient }); this.sfdcClient = this.project.sfdcClient; } else if (this.sfdcClient) { this.metadataHelper = new MetadataHelper({ sfdcClient : this.sfdcClient }); } }
javascript
{ "resource": "" }
q48127
LI
train
function LI(props) { return ( <MenuItem style={{cursor: 'pointer', userSelect: 'none'}} highlightedStyle={{background: 'gray'}} onItemChosen={e => { console.log(`selected ${props.children}, byKeyboard: ${String(e.byKeyboard)}`); }} {...props} /> ); }
javascript
{ "resource": "" }
q48128
train
function (src, callback, context) { /*eslint max-statements: [2, 32]*/ var setup; if (callback && typeof callback !== "function") { context = callback.context || context; setup = callback.setup; callback = callback.callback; } var script = document.createElement("script"); var done = false; var err; var _cleanup; // _must_ be set below. /** * Final handler for error or completion. * * **Note**: Will only be called _once_. * * @returns {void} */ var _finish = function () { // Only call once. if (done) { return; } done = true; // Internal cleanup. _cleanup(); // Callback. if (callback) { callback.call(context, err); } }; /** * Error handler * * @returns {void} */ var _error = function () { err = new Error(src || "EMPTY"); _finish(); }; if (script.readyState && !("async" in script)) { /*eslint-disable consistent-return*/ // This section is only for IE<10. Some other old browsers may // satisfy the above condition and enter this branch, but we don't // support those browsers anyway. var id = scriptCounter++; var isReady = { loaded: true, complete: true }; var inserted = false; // Clear out listeners, state. _cleanup = function () { script.onreadystatechange = script.onerror = null; pendingScripts[id] = void 0; }; // Attach the handler before setting src, otherwise we might // miss events (consider that IE could fire them synchronously // upon setting src, for example). script.onreadystatechange = function () { var firstState = script.readyState; // Protect against any errors from state change randomness. if (err) { return; } if (!inserted && isReady[firstState]) { inserted = true; // Append to DOM. _addScript(script); } // -------------------------------------------------------------------- // GLORIOUS IE8 HACKAGE!!! // -------------------------------------------------------------------- // // Oh IE8, how you disappoint. IE8 won't call `script.onerror`, so // we have to resort to drastic measures. // See, e.g. http://www.quirksmode.org/dom/events/error.html#t02 // // As with all things development, there's a Stack Overflow comment that // asserts the following combinations of state changes in IE8 indicate a // script load error. And crazily, it seems to work! // // http://stackoverflow.com/a/18840568/741892 // // The `script.readyState` transitions we're interested are: // // * If state starts as `loaded` // * Call `script.children`, which _should_ change state to `complete` // * If state is now `loading`, then **we have a load error** // // For the reader's amusement, here is HeadJS's catalog of various // `readyState` transitions in normal operation for IE: // https://github.com/headjs/headjs/blob/master/src/2.0.0/load.js#L379-L419 if (firstState === "loaded") { // The act of accessing the property should change the script's // `readyState`. // // And, oh yeah, this hack is so hacky-ish we need the following // eslint disable... /*eslint-disable no-unused-expressions*/ script.children; /*eslint-enable no-unused-expressions*/ if (script.readyState === "loading") { // State transitions indicate we've hit the load error. // // **Note**: We are not intending to _return_ a value, just have // a shorter short-circuit code path here. return _error(); } } // It's possible for readyState to be "complete" immediately // after we insert (and execute) the script in the branch // above. So check readyState again here and react without // waiting for another onreadystatechange. if (script.readyState === "complete") { _finish(); } }; // Onerror handler _may_ work here. script.onerror = _error; // Since we're not appending the script to the DOM yet, the // reference to our script element might get garbage collected // when this function ends, without onreadystatechange ever being // fired. This has been witnessed to happen. Adding it to // `pendingScripts` ensures this can't happen. pendingScripts[id] = script; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script); } // This triggers a request for the script, but its contents won't // be executed until we append it to the DOM. script.src = src; // In some cases, the readyState is already "loaded" immediately // after setting src. It's a lie! Don't append to the DOM until // the onreadystatechange event says so. } else { // This section is for modern browsers, including IE10+. // Clear out listeners. _cleanup = function () { script.onload = script.onerror = null; }; script.onerror = _error; script.onload = _finish; script.async = true; script.charset = "utf-8"; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script); } script.src = src; // Append to DOM. _addScript(script); } }
javascript
{ "resource": "" }
q48129
imageCompression
train
async function imageCompression (file, options) { let compressedFile options.maxSizeMB = options.maxSizeMB || Number.POSITIVE_INFINITY options.useWebWorker = typeof options.useWebWorker === 'boolean' ? options.useWebWorker : true if (!(file instanceof Blob || file instanceof File)) { throw new Error('The file given is not an instance of Blob or File') } else if (!/^image/.test(file.type)) { throw new Error('The file given is not an image') } // try run in web worker, fall back to run in main thread const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope // if (inWebWorker) { // console.log('run compression in web worker') // } else { // console.log('run compression in main thread') // } if (options.useWebWorker && typeof Worker === 'function' && !inWebWorker) { try { // "compressOnWebWorker" is kind of like a recursion to call "imageCompression" again inside web worker compressedFile = await compressOnWebWorker(file, options) } catch (e) { // console.error('run compression in web worker failed', e) compressedFile = await compress(file, options) } } else { compressedFile = await compress(file, options) } try { compressedFile.name = file.name compressedFile.lastModified = file.lastModified } catch (e) {} return compressedFile }
javascript
{ "resource": "" }
q48130
sign
train
function sign(x) { // eslint-disable-next-line no-self-compare return typeof x === "number" ? x ? x < 0 ? -1 : 1 : x === x ? x : NaN : NaN; }
javascript
{ "resource": "" }
q48131
findPhraseInDirection
train
function findPhraseInDirection(node, index, parent, offset) { var children = parent.children var nodes = [] var stems = [] var words = [] var queue = [] var child while (children[(index += offset)]) { child = children[index] if (child.type === 'WhiteSpaceNode') { queue.push(child) } else if (isImportant(child)) { nodes = nodes.concat(queue, [child]) words.push(child) stems.push(stemNode(child)) queue = [] } else { break } } return { stems: stems, words: words, nodes: nodes } }
javascript
{ "resource": "" }
q48132
getKeyphrases
train
function getKeyphrases(results, maximum) { var stemmedPhrases = {} var initialWords = [] var stemmedPhrase var index var length var otherIndex var keyword var matches var phrase var stems var score var first var match // Iterate over all grouped important words... for (keyword in results) { matches = results[keyword].matches length = matches.length index = -1 // Iterate over every occurence of a certain keyword... while (++index < length) { phrase = findPhrase(matches[index]) stemmedPhrase = stemmedPhrases[phrase.value] first = phrase.nodes[0] match = { nodes: phrase.nodes, parent: matches[index].parent } // If we've detected the same stemmed phrase somewhere. if (own.call(stemmedPhrases, phrase.value)) { // Add weight per phrase to the score of the phrase. stemmedPhrase.score += stemmedPhrase.weight // If this is the first time we walk over the phrase (exact match but // containing another important word), add it to the list of matching // phrases. if (initialWords.indexOf(first) === -1) { initialWords.push(first) stemmedPhrase.matches.push(match) } } else { otherIndex = -1 score = -1 stems = phrase.stems initialWords.push(first) // For every stem in phrase, add its score to score. while (stems[++otherIndex]) { score += results[stems[otherIndex]].score } stemmedPhrases[phrase.value] = { score: score, weight: score, stems: stems, value: phrase.value, matches: [match] } } } } for (stemmedPhrase in stemmedPhrases) { phrase = stemmedPhrases[stemmedPhrase] // Modify its score to be the rounded result of multiplying it with the // number of occurances, and dividing it by the ammount of words in the // phrase. phrase.score = Math.round( (phrase.score * phrase.matches.length) / phrase.stems.length ) } return filterResults(stemmedPhrases, maximum) }
javascript
{ "resource": "" }
q48133
filterResults
train
function filterResults(results, maximum) { var filteredResults = [] var indices = [] var matrix = {} var column var key var score var interpolated var index var otherIndex var maxScore for (key in results) { score = results[key].score if (!matrix[score]) { matrix[score] = [] indices.push(score) } matrix[score].push(results[key]) } indices.sort(reverse) maxScore = indices[0] index = -1 while (indices[++index]) { score = indices[index] column = matrix[score] interpolated = score / maxScore otherIndex = -1 while (column[++otherIndex]) { column[otherIndex].score = interpolated } filteredResults = filteredResults.concat(column) if (filteredResults.length >= maximum) { break } } return filteredResults }
javascript
{ "resource": "" }
q48134
merge
train
function merge(prev, current, next) { return prev .concat() .reverse() .concat([current], next) }
javascript
{ "resource": "" }
q48135
findPhrase
train
function findPhrase(match) { var node = match.node var prev = findPhraseInDirection(node, match.index, match.parent, -1) var next = findPhraseInDirection(node, match.index, match.parent, 1) var stems = merge(prev.stems, stemNode(node), next.stems) return { stems: stems, value: stems.join(' '), nodes: merge(prev.nodes, node, next.nodes) } }
javascript
{ "resource": "" }
q48136
getImportantWords
train
function getImportantWords(node) { var words = {} visit(node, 'WordNode', visitor) return words function visitor(word, index, parent) { var match var stem if (isImportant(word)) { stem = stemNode(word) match = { node: word, index: index, parent: parent } if (!own.call(words, stem)) { words[stem] = { matches: [match], stem: stem, score: 1 } } else { words[stem].matches.push(match) words[stem].score++ } } } }
javascript
{ "resource": "" }
q48137
cloneMatches
train
function cloneMatches(words) { var result = {} var key var match for (key in words) { match = words[key] result[key] = { matches: match.matches, stem: match.stem, score: match.score } } return result }
javascript
{ "resource": "" }
q48138
isImportant
train
function isImportant(node) { return ( node && node.data && node.data.partOfSpeech && (node.data.partOfSpeech.indexOf('N') === 0 || (node.data.partOfSpeech === 'JJ' && isUpperCase(nlcstToString(node).charAt(0)))) ) }
javascript
{ "resource": "" }
q48139
postScreenshot
train
function postScreenshot (options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getUploadOptions(options), 'Unable to upload document'); }
javascript
{ "resource": "" }
q48140
postFile
train
function postFile (options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getUploadOptions(options), 'Unable to upload document'); }
javascript
{ "resource": "" }
q48141
getLanguages
train
function getLanguages(options) { options.hash = _private.getDevHash(options.secret); return _private.makeRequest(_getLink(options), 'Unable to fetch project languages'); }
javascript
{ "resource": "" }
q48142
createRows
train
function createRows(items, columns, columnNames, paddingChr) { return items.map(item => { let row = [] let numLines = 0 columnNames.forEach(columnName => { numLines = Math.max(numLines, item[columnName].length) }) // combine matching lines of each rows for (let i = 0; i < numLines; i++) { row[i] = row[i] || [] columnNames.forEach(columnName => { let column = columns[columnName] let val = item[columnName][i] || '' // || '' ensures empty columns get padded if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr)) else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr)) else row[i].push(padRight(val, column.width, paddingChr)) }) } return row }) }
javascript
{ "resource": "" }
q48143
endsWith
train
function endsWith(target, searchString, position) { position = position || target.length; position = position - searchString.length; let lastIndex = target.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; }
javascript
{ "resource": "" }
q48144
repeatString
train
function repeatString(str, len) { return Array.apply(null, {length: len + 1}).join(str).slice(0, len) }
javascript
{ "resource": "" }
q48145
padRight
train
function padRight(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str) if (length <= 0) return str return str + repeatString(chr || ' ', length) }
javascript
{ "resource": "" }
q48146
padCenter
train
function padCenter(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str) if (length <= 0) return str var lengthLeft = Math.floor(length/2) var lengthRight = length - lengthLeft return repeatString(chr || ' ', lengthLeft) + str + repeatString(chr || ' ', lengthRight) }
javascript
{ "resource": "" }
q48147
splitIntoLines
train
function splitIntoLines(str, max) { function _splitIntoLines(str, max) { return str.trim().split(' ').reduce(function(lines, word) { var line = lines[lines.length - 1] if (line && wcwidth(line.join(' ')) + wcwidth(word) < max) { lines[lines.length - 1].push(word) // add to line } else lines.push([word]) // new line return lines }, []).map(function(l) { return l.join(' ') }) } return str.split('\n').map(function(str) { return _splitIntoLines(str, max) }).reduce(function(lines, line) { return lines.concat(line) }, []) }
javascript
{ "resource": "" }
q48148
splitLongWords
train
function splitLongWords(str, max, truncationChar) { str = str.trim() var result = [] var words = str.split(' ') var remainder = '' var truncationWidth = wcwidth(truncationChar) while (remainder || words.length) { if (remainder) { var word = remainder remainder = '' } else { var word = words.shift() } if (wcwidth(word) > max) { // slice is based on length no wcwidth var i = 0 var wwidth = 0 var limit = max - truncationWidth while (i < word.length) { var w = wcwidth(word.charAt(i)) if (w + wwidth > limit) { break } wwidth += w ++i } remainder = word.slice(i) // get remainder // save remainder for next loop word = word.slice(0, i) // grab truncated word word += truncationChar // add trailing … or whatever } result.push(word) } return result.join(' ') }
javascript
{ "resource": "" }
q48149
truncateString
train
function truncateString(str, max) { str = str != null ? str : '' str = String(str) if(max == Infinity) return str var i = 0 var wwidth = 0 while (i < str.length) { var w = wcwidth(str.charAt(i)) if(w + wwidth > max) break wwidth += w ++i } return str.slice(0, i) }
javascript
{ "resource": "" }
q48150
initTranslate
train
function initTranslate(props) { const element = props.element, elementStyle = props.elementStyle, curPosition = getBBox(element), // Get BBox before change style. RESTORE_PROPS = ['display', 'marginTop', 'marginBottom', 'width', 'height']; RESTORE_PROPS.unshift(cssPropTransform); // Reset `transition-property` every time because it might be changed frequently. const orgTransitionProperty = elementStyle[cssPropTransitionProperty]; elementStyle[cssPropTransitionProperty] = 'none'; // Disable animation const fixPosition = getBBox(element); if (!props.orgStyle) { props.orgStyle = RESTORE_PROPS.reduce((orgStyle, prop) => { orgStyle[prop] = elementStyle[prop] || ''; return orgStyle; }, {}); props.lastStyle = {}; } else { RESTORE_PROPS.forEach(prop => { // Skip this if it seems user changed it. (it can't check perfectly.) if (props.lastStyle[prop] == null || elementStyle[prop] === props.lastStyle[prop]) { elementStyle[prop] = props.orgStyle[prop]; } }); } const orgSize = getBBox(element), cmpStyle = window.getComputedStyle(element, ''); // https://www.w3.org/TR/css-transforms-1/#transformable-element if (cmpStyle.display === 'inline') { elementStyle.display = 'inline-block'; ['Top', 'Bottom'].forEach(dirProp => { const padding = parseFloat(cmpStyle[`padding${dirProp}`]); // paddingTop/Bottom make padding but don't make space -> negative margin in inline-block // marginTop/Bottom don't work in inline element -> `0` in inline-block elementStyle[`margin${dirProp}`] = padding ? `-${padding}px` : '0'; }); } elementStyle[cssPropTransform] = 'translate(0, 0)'; // Get document offset. let newBBox = getBBox(element); const offset = props.htmlOffset = {left: newBBox.left ? -newBBox.left : 0, top: newBBox.top ? -newBBox.top : 0}; // avoid `-0` // Restore position elementStyle[cssPropTransform] = `translate(${curPosition.left + offset.left}px, ${curPosition.top + offset.top}px)`; // Restore size ['width', 'height'].forEach(prop => { if (newBBox[prop] !== orgSize[prop]) { // Ignore `box-sizing` elementStyle[prop] = orgSize[prop] + 'px'; newBBox = getBBox(element); if (newBBox[prop] !== orgSize[prop]) { // Retry elementStyle[prop] = orgSize[prop] - (newBBox[prop] - orgSize[prop]) + 'px'; } } props.lastStyle[prop] = elementStyle[prop]; }); // Restore `transition-property` element.offsetWidth; /* force reflow */ // eslint-disable-line no-unused-expressions elementStyle[cssPropTransitionProperty] = orgTransitionProperty; if (fixPosition.left !== curPosition.left || fixPosition.top !== curPosition.top) { // It seems that it is moving. elementStyle[cssPropTransform] = `translate(${fixPosition.left + offset.left}px, ${fixPosition.top + offset.top}px)`; } return fixPosition; }
javascript
{ "resource": "" }
q48151
validPPValue
train
function validPPValue(value) { // Get PPValue from string (all `/s` were already removed) function string2PPValue(inString) { var matches = /^(.+?)(%)?$/.exec(inString); var value = void 0, isRatio = void 0; return matches && isFinite(value = parseFloat(matches[1])) ? { value: (isRatio = !!(matches[2] && value)) ? value / 100 : value, isRatio: isRatio } : null; // 0% -> 0 } return isFinite(value) ? { value: value, isRatio: false } : typeof value === 'string' ? string2PPValue(value.replace(/\s/g, '')) : null; }
javascript
{ "resource": "" }
q48152
validPPBBox
train
function validPPBBox(bBox) { if (!isObject(bBox)) { return null; } var ppValue = void 0; if ((ppValue = validPPValue(bBox.left)) || (ppValue = validPPValue(bBox.x))) { bBox.left = bBox.x = ppValue; } else { return null; } if ((ppValue = validPPValue(bBox.top)) || (ppValue = validPPValue(bBox.y))) { bBox.top = bBox.y = ppValue; } else { return null; } if ((ppValue = validPPValue(bBox.width)) && ppValue.value >= 0) { bBox.width = ppValue; delete bBox.right; } else if (ppValue = validPPValue(bBox.right)) { bBox.right = ppValue; delete bBox.width; } else { return null; } if ((ppValue = validPPValue(bBox.height)) && ppValue.value >= 0) { bBox.height = ppValue; delete bBox.bottom; } else if (ppValue = validPPValue(bBox.bottom)) { bBox.bottom = ppValue; delete bBox.height; } else { return null; } return bBox; }
javascript
{ "resource": "" }
q48153
resolvePPBBox
train
function resolvePPBBox(ppBBox, baseBBox) { var prop2Axis = { left: 'x', right: 'x', x: 'x', width: 'x', top: 'y', bottom: 'y', y: 'y', height: 'y' }, baseOriginXY = { x: baseBBox.left, y: baseBBox.top }, baseSizeXY = { x: baseBBox.width, y: baseBBox.height }; return validBBox(Object.keys(ppBBox).reduce(function (bBox, prop) { bBox[prop] = resolvePPValue(ppBBox[prop], prop === 'width' || prop === 'height' ? 0 : baseOriginXY[prop2Axis[prop]], baseSizeXY[prop2Axis[prop]]); return bBox; }, {})); }
javascript
{ "resource": "" }
q48154
initAnim
train
function initAnim(element, gpuTrigger) { var style = element.style; style.webkitTapHighlightColor = 'transparent'; // Only when it has no shadow var cssPropBoxShadow = CSSPrefix.getName('boxShadow'), boxShadow = window.getComputedStyle(element, '')[cssPropBoxShadow]; if (!boxShadow || boxShadow === 'none') { style[cssPropBoxShadow] = '0 0 1px transparent'; } if (gpuTrigger && cssPropTransform) { style[cssPropTransform] = 'translateZ(0)'; } return element; }
javascript
{ "resource": "" }
q48155
moveTranslate
train
function moveTranslate(props, position) { var elementBBox = props.elementBBox; if (position.left !== elementBBox.left || position.top !== elementBBox.top) { var offset = props.htmlOffset; props.elementStyle[cssPropTransform] = 'translate(' + (position.left + offset.left) + 'px, ' + (position.top + offset.top) + 'px)'; return true; } return false; }
javascript
{ "resource": "" }
q48156
move
train
function move(props, position, cbCheck) { var elementBBox = props.elementBBox; function fix() { if (props.minLeft >= props.maxLeft) { // Disabled position.left = elementBBox.left; } else if (position.left < props.minLeft) { position.left = props.minLeft; } else if (position.left > props.maxLeft) { position.left = props.maxLeft; } if (props.minTop >= props.maxTop) { // Disabled position.top = elementBBox.top; } else if (position.top < props.minTop) { position.top = props.minTop; } else if (position.top > props.maxTop) { position.top = props.maxTop; } } fix(); if (cbCheck) { if (cbCheck(position) === false) { return false; } fix(); // Again } var moved = props.moveElm(props, position); if (moved) { // Update elementBBox props.elementBBox = validBBox({ left: position.left, top: position.top, width: elementBBox.width, height: elementBBox.height }); } return moved; }
javascript
{ "resource": "" }
q48157
train
function (options) { return qfs.listTree('.', function (filePath) { var file = path.basename(filePath) // Do not traverse into the node_modules directory if (file === 'node_modules' || file === '.git') { return null } // Collect all files "credits.md" if (file === 'credits.md.hbs') { return true } return false }).then(function (creditFiles) { return deep(creditFiles.map(function (creditFile) { console.log("Using credit file", creditFile) var input = _.merge({}, this, { __dirname: path.dirname(creditFile), __filename: creditFile }) return qfs.read(creditFile).then(function (contents) { return options.customize.engine.compile(contents)(input) }) })) }) }
javascript
{ "resource": "" }
q48158
createPartialTree
train
function createPartialTree (currentFile, partials, visitedFiles) { if (visitedFiles[currentFile.name]) { return { label: '*' + currentFile.name + '*', name: currentFile.name } } visitedFiles[currentFile.name] = true var result = { label: currentFile.name, name: currentFile.name, summary: _.trunc(chainOrUndefined(currentFile, 'apidocs', 0, 'parsed', 'description'), { separator: ' ', length: 50 }) } if (currentFile.children.length > 0) { _.merge(result, { children: currentFile.children.map(function (child) { return createPartialTree(partials[child], partials, visitedFiles) }) }) } return result }
javascript
{ "resource": "" }
q48159
train
function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }
javascript
{ "resource": "" }
q48160
train
function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }
javascript
{ "resource": "" }
q48161
train
function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }
javascript
{ "resource": "" }
q48162
train
function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }
javascript
{ "resource": "" }
q48163
train
function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }
javascript
{ "resource": "" }
q48164
train
function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }
javascript
{ "resource": "" }
q48165
train
function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }
javascript
{ "resource": "" }
q48166
train
function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }
javascript
{ "resource": "" }
q48167
train
function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy'); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }
javascript
{ "resource": "" }
q48168
train
function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }
javascript
{ "resource": "" }
q48169
train
function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }
javascript
{ "resource": "" }
q48170
train
function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; }
javascript
{ "resource": "" }
q48171
train
function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }
javascript
{ "resource": "" }
q48172
train
function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; }
javascript
{ "resource": "" }
q48173
train
function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }
javascript
{ "resource": "" }
q48174
train
function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } return root[inside] = ret; }
javascript
{ "resource": "" }
q48175
updateMetrics
train
function updateMetrics() { var dprM; isVwDirty = false; DPR = window.devicePixelRatio; cssCache = {}; sizeLengthCache = {}; dprM = (DPR || 1) * cfg.xQuant; if(!cfg.uT){ cfg.maxX = Math.max(1.3, cfg.maxX); dprM = Math.min( dprM, cfg.maxX ); ri.DPR = dprM; } units.width = Math.max(window.innerWidth || 0, docElem.clientWidth); units.height = Math.max(window.innerHeight || 0, docElem.clientHeight); units.vw = units.width / 100; units.vh = units.height / 100; units.em = ri.getEmValue(); units.rem = units.em; lazyFactor = cfg.lazyFactor / 2; lazyFactor = (lazyFactor * dprM) + lazyFactor; substractCurRes = 0.4 + (0.1 * dprM); lowTreshHold = 0.5 + (0.2 * dprM); partialLowTreshHold = 0.5 + (0.25 * dprM); tMemory = dprM + 1.3; if(!(isLandscape = units.width > units.height)){ lazyFactor *= 0.9; } if(supportAbort){ lazyFactor *= 0.9; } evalID = [units.width, units.height, dprM].join('-'); }
javascript
{ "resource": "" }
q48176
getIndex
train
function getIndex(increment) { var max = $related.length, newIndex = (index + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; }
javascript
{ "resource": "" }
q48177
appendHTML
train
function appendHTML() { if (!$box && document.body) { init = false; $window = $(window); $box = $tag(div).attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}).hide(); $overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $tag(div, "Wrapper"); $content = $tag(div, "Content").append( $loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")), $title = $tag(div, "Title"), $current = $tag(div, "Current"), $next = $tag(div, "Next"), $prev = $tag(div, "Previous"), $slideshow = $tag(div, "Slideshow").bind(event_open, slideshow), $close = $tag(div, "Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $tag(div).append( $tag(div, "TopLeft"), $topBorder = $tag(div, "TopCenter"), $tag(div, "TopRight") ), $tag(div, false, 'clear:left').append( $leftBorder = $tag(div, "MiddleLeft"), $content, $rightBorder = $tag(div, "MiddleRight") ), $tag(div, false, 'clear:left').append( $tag(div, "BottomLeft"), $bottomBorder = $tag(div, "BottomCenter"), $tag(div, "BottomRight") ) ).find('div div').css({'float': 'left'}); $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $groupControls = $next.add($prev).add($current).add($slideshow); $(document.body).append($overlay, $box.append($wrap, $loadingBay)); } }
javascript
{ "resource": "" }
q48178
addBindings
train
function addBindings() { if ($box) { if (!init) { init = true; // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6 interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Setting padding to remove the need to do size conversions during the animation step. $box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}); // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1]) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); $('.' + boxElement, document).live('click', function (e) { // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt. // See: http://jacklmoore.com/notes/click-events/ if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) { e.preventDefault(); launch(this); } }); } return true; } return false; }
javascript
{ "resource": "" }
q48179
train
function(layouts) { var currentLayout; layouts = layouts.slice(0); currentLayout = self.compile(str, layoutFile); layouts.push(currentLayout); if (useCache) { self.cache[layoutFile] = layouts.slice(0); } cb(null, layouts); }
javascript
{ "resource": "" }
q48180
parseLayout
train
function parseLayout(str, filename, cb) { var layoutFile = self.declaredLayoutFile(str, filename); if (layoutFile) { self.cacheLayout(layoutFile, options.cache, cb); } else { cb(null, null); } }
javascript
{ "resource": "" }
q48181
renderTemplate
train
function renderTemplate(template, locals, cb) { var res; try { var localTemplateOptions = self.getLocalTemplateOptions(locals); var localsClone = _.extend({}, locals); self.updateLocalTemplateOptions(localsClone, undefined); res = template(localsClone, _.merge({}, self._options.templateOptions, localTemplateOptions)); } catch (err) { if (err.message) { err.message = '[' + template.__filename + '] ' + err.message; } else if (typeof err === 'string') { return cb('[' + template.__filename + '] ' + err, null); } return cb(err, null); } cb(null, res); }
javascript
{ "resource": "" }
q48182
render
train
function render(template, locals, layoutTemplates, cb) { if (!layoutTemplates) layoutTemplates = []; // We'll render templates from bottom to top of the stack, each template // being passed the rendered string of the previous ones as `body` var i = layoutTemplates.length - 1; var _stackRenderer = function(err, htmlStr) { if (err) return cb(err); if (i >= 0) { locals.body = htmlStr; renderTemplate(layoutTemplates[i--], locals, _stackRenderer); } else { cb(null, htmlStr); } }; // Start the rendering with the innermost page template renderTemplate(template, locals, _stackRenderer); }
javascript
{ "resource": "" }
q48183
loadBeautify
train
function loadBeautify() { if (!self.beautify) { self.beautify = require('js-beautify').html; var rc = path.join(process.cwd(), '.jsbeautifyrc'); if (fs.existsSync(rc)) { self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8')); } } }
javascript
{ "resource": "" }
q48184
getSourceTemplate
train
function getSourceTemplate(cb) { if (options.cache) { var info = self.cache[filename]; if (info) { return cb(null, info.source, info.template); } } fs.readFile(filename, 'utf8', function(err, source) { if (err) return cb(err); var template = self.compile(source, filename); if (options.cache) { self.cache[filename] = { source: source, template: template }; } return cb(null, source, template); }); }
javascript
{ "resource": "" }
q48185
compileFile
train
function compileFile(locals, cb) { getSourceTemplate(function(err, source, template) { if (err) return cb(err); // Try to get the layout parseLayout(source, filename, function(err, layoutTemplates) { if (err) return cb(err); function renderIt(layoutTemplates) { if (self._options.beautify) { return render(template, locals, layoutTemplates, function(err, html) { if (err) return cb(err); loadBeautify(); return cb(null, self.beautify(html, self.beautifyrc)); }); } return render(template, locals, layoutTemplates, cb); } // Determine which layout to use if (typeof options.layout !== 'undefined' && !options.layout) { // If options.layout is falsy, behave as if no layout should be used - suppress defaults renderIt(null); } else if (layoutTemplates) { // 1. Layout specified in template renderIt(layoutTemplates); } else if (typeof options.layout !== 'undefined' && options.layout) { // 2. Layout specified by options from render var layoutFile = self.layoutPath(filename, options.layout); self.cacheLayout(layoutFile, options.cache, function(err, layoutTemplates) { if (err) return cb(err); renderIt(layoutTemplates); }); } else if (self.defaultLayoutTemplates) { // 3. Default layout specified when middleware was configured. renderIt(self.defaultLayoutTemplates); } else { // render without a template renderIt(null); } }); }); }
javascript
{ "resource": "" }
q48186
toBuffer
train
function toBuffer(value, encoding) { if( typeof value === 'string') { encoding = encoding || 'hex'; if( !re.test(encoding) ) { throw new Error('[toBuffer] bad encoding. Must be: utf8|ascii|binary|hex|utf16le|ucs2|base64'); } try { return Buffer.from(value, encoding); } catch (e) { throw new Error('[toBuffer] string value could not be converted to a buffer :' + e.message); } } else if( typeof value === 'object' ) { if( Buffer.isBuffer(value) ) { return value; } else if( value instanceof Array ) { try { return Buffer.from(value); } catch (e) { throw new Error('[toBuffer] Array could not be converted to a buffer :' + e.message); } } } throw new Error('[toBuffer] unsupported type in value. Use Buffer, string or Array'); }
javascript
{ "resource": "" }
q48187
raiseOnUnsafeCSS
train
function raiseOnUnsafeCSS() { var css = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var foundInName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '\'not provided\''; css = new _cleanCss2.default({ shorthandCompacting: false }).minify(css).styles; if (css.match(/-moz-binding/i)) { throw new Error('Unsafe CSS found in ' + foundInName + ': "-moz-binding"'); } else if (css.match(/expression/i)) { throw new Error('Unsafe CSS found in ' + foundInName + ': "expression"'); } return css; }
javascript
{ "resource": "" }
q48188
sortTags
train
function sortTags(tagA, tagB) { if ((tagA[0] === tagA[0].toUpperCase()) && (tagB[0] !== tagB[0].toUpperCase())) { return 1; } else if ((tagA[0] !== tagA[0].toUpperCase()) && (tagB[0] === tagB[0].toUpperCase())) { return -1; } else { return tagA < tagB; } }
javascript
{ "resource": "" }
q48189
Encoder
train
function Encoder (opts) { if (!(this instanceof Encoder)) { return new Encoder(opts); } Transform.call(this, opts); // lame malloc()s the "gfp" buffer this.gfp = binding.lame_init(); // set default options if (!opts) opts = {}; if (null == opts.channels) opts.channels = 2; if (null == opts.bitDepth) opts.bitDepth = 16; if (null == opts.sampleRate) opts.sampleRate = 44100; if (null == opts.signed) opts.signed = opts.bitDepth != 8; if (opts.float && opts.bitDepth == DOUBLE_BITS) { this.inputType = PCM_TYPE_DOUBLE; } else if (opts.float && opts.bitDepth == FLOAT_BITS) { this.inputType = PCM_TYPE_FLOAT; } else if (!opts.float && opts.bitDepth == SHORT_BITS) { this.inputType = PCM_TYPE_SHORT_INT; } else { throw new Error('unsupported PCM format!'); } // copy over opts to the encoder instance Object.keys(opts).forEach(function(key){ if (key[0] != '_' && Encoder.prototype.hasOwnProperty(key)) { debug('setting opt %j', key); this[key] = opts[key]; } }, this); }
javascript
{ "resource": "" }
q48190
Decoder
train
function Decoder (opts) { if (!(this instanceof Decoder)) { return new Decoder(opts); } Transform.call(this, opts); var ret; ret = binding.mpg123_new(opts ? opts.decoder : null); if (Buffer.isBuffer(ret)) { this.mh = ret; } else { throw new Error('mpg123_new() failed: ' + ret); } ret = binding.mpg123_open_feed(this.mh); if (MPG123_OK != ret) { throw new Error('mpg123_open_feed() failed: ' + ret); } debug('created new Decoder instance'); }
javascript
{ "resource": "" }
q48191
train
function() { if (bodiesCount === 0) return true; // TODO: This will never fire 'stable' var lastMove = physicsSimulator.step(); // Save the movement in case if someone wants to query it in the step // callback. api.lastMove = lastMove; // Allow listeners to perform low-level actions after nodes are updated. api.fire('step'); var ratio = lastMove/bodiesCount; var isStableNow = ratio <= 0.01; // TODO: The number is somewhat arbitrary... if (wasStable !== isStableNow) { wasStable = isStableNow; onStableChanged(isStableNow); } return isStableNow; }
javascript
{ "resource": "" }
q48192
train
function (nodeId) { var body = getInitializedBody(nodeId); body.setPosition.apply(body, Array.prototype.slice.call(arguments, 1)); physicsSimulator.invalidateBBox(); }
javascript
{ "resource": "" }
q48193
isNodeOriginallyPinned
train
function isNodeOriginallyPinned(node) { return (node && (node.isPinned || (node.data && node.data.isPinned))); }
javascript
{ "resource": "" }
q48194
toRawDoc
train
function toRawDoc(typeInfo, obj) { obj = extend(true, {}, obj); var doc = {}; if (obj.rev) { doc._rev = obj.rev; delete obj.rev; } if (obj.attachments) { doc._attachments = obj.attachments; delete obj.attachments; } var id = obj.id || uuid(); delete obj.id; doc._id = serialize(typeInfo.documentType, id); if (typeInfo.relations) { Object.keys(typeInfo.relations).forEach(function (field) { var relationDef = typeInfo.relations[field]; var relationType = Object.keys(relationDef)[0]; if (relationType === 'belongsTo') { if (obj[field] && typeof obj[field].id !== 'undefined') { obj[field] = obj[field].id; } } else { // hasMany var relatedType = relationDef[relationType]; if (relatedType.options && relatedType.options.queryInverse) { delete obj[field]; return; } if (obj[field]) { var dependents = obj[field].map(function (dependent) { if (dependent && typeof dependent.id !== 'undefined') { return dependent.id; } return dependent; }); obj[field] = dependents; } else { obj[field] = []; } } }); } doc.data = obj; return doc; }
javascript
{ "resource": "" }
q48195
fromRawDoc
train
function fromRawDoc(pouchDoc) { var obj = pouchDoc.data; obj.id = deserialize(pouchDoc._id); obj.rev = pouchDoc._rev; if (pouchDoc._attachments) { obj.attachments = pouchDoc._attachments; } return obj; }
javascript
{ "resource": "" }
q48196
isDeleted
train
function isDeleted(type, id) { var typeInfo = getTypeInfo(type); return db.get(serialize(typeInfo.documentType, id)) .then(function (doc) { return !!doc._deleted; }) .catch(function (err) { return err.reason === "deleted" ? true : null; }); }
javascript
{ "resource": "" }
q48197
initKarmaParallelizer
train
function initKarmaParallelizer(root, karma, shardIndexInfoMap) { var idParamExtractor = /(\?|&)id=(\d+)(&|$)/; var matches = idParamExtractor.exec(parent.location.search); var id = (matches && matches[2]) || null; if ( !id || !shardIndexInfoMap.hasOwnProperty(id) || !shardIndexInfoMap[id].shouldShard ) { /* eslint-disable-next-line no-console */ console.warn( 'Skipping sharding. Could not find karma-parallel initialization data.' ); return; } var shardIndexInfo = shardIndexInfoMap[id]; var strategy = overrideSuiteStategy(getSpecSuiteStrategy(shardIndexInfo)); var fakeContextStatus = createFakeTestContext(root, strategy); var origStart = karma.start; karma.start = function() { fakeContextStatus.beforeStartup(); origStart.call(this); }; }
javascript
{ "resource": "" }
q48198
wrap
train
function wrap(fn, isFocus, isDescription, isSpec) { if (!fn) return fn; return function(name, def) { if (isDescription && depth === 0) { // Reset isFaking on top-level descriptions isFaking = !shouldUseDescription(name, def); } hasOwnSpecs = hasOwnSpecs || (isSpec && !isFaking); hasOtherSpecs = hasOtherSpecs || (isSpec && isFaking); hasFocusedWhileFaking = hasFocusedWhileFaking || (isFocus && isFaking); hasFocusedWithoutFaking = hasFocusedWithoutFaking || (isFocus && !isFaking); if (isDescription) def = wrapDescription(def); if (!isFaking || forceDescribe) { // Call through to framework and return the result return fn.call(this, name, def); } else if (isDescription) { // If its a fake description, then we need to call through to eval inner its() looking for focuses // TODO, do we ever need parameters? def(); } }; }
javascript
{ "resource": "" }
q48199
wrapWithDispatch
train
function wrapWithDispatch(asyncItems) { return asyncItems.map((item) => { const { key } = item; if (!key) return item; return { ...item, promise: (options) => { const { store: { dispatch } } = options; const next = item.promise(options); // NOTE: possibly refactor this with a breaking change in mind for future versions // we can return result of processed promise/thunk if need be if (isPromise(next)) { dispatch(load(key)); // add action dispatchers next .then(data => dispatch(loadSuccess(key, data))) .catch(err => dispatch(loadFail(key, err))); } else if (next) { dispatch(loadSuccess(key, next)); } return next; }, }; }); }
javascript
{ "resource": "" }