_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q1400
fileChanged
train
function fileChanged(status, filepath) { // If file was deleted and then re-added, consider it changed. if (changedFiles[filepath] === 'deleted' && status === 'added') { status = 'changed'; } // Keep track of changed status for later. changedFiles[filepath] = status; // Emit watch events if anyone is listening if (grunt.event.listeners('watch').length > 0) { var matchingTargets = []; targets.forEach(function(target) { if (grunt.file.match(target.files, filepath).length > 0) { matchingTargets.push(target.name);
javascript
{ "resource": "" }
q1401
watchFile
train
function watchFile(filepath) { if (!watchedFiles[filepath]) { // add a new file to watched files var statStructure = null; try { statStructure = fs.statSync(filepath); } catch (e) { // StatSync can throw an error if the
javascript
{ "resource": "" }
q1402
makeArray
train
function makeArray( obj ) { var ary = []; if ( isArray( obj ) ) { // use object if already an array ary = obj; } else if ( typeof obj.length === 'number'
javascript
{ "resource": "" }
q1403
train
function(context, pkg, source) { source = source || "{}"; var packageJSON = JSON.parse(source);
javascript
{ "resource": "" }
q1404
train
function(context, pkg){ var deps = crawl.getDependencyMap(context.loader, pkg, true); var pluginsPromise = crawl.loadPlugins(context, pkg, true, deps, true); var stealPromise =
javascript
{ "resource": "" }
q1405
train
function(context, pkg, isRoot) { var deps = crawl.getDependencies(context.loader, pkg, isRoot); return Promise.all(utils.filter(utils.map(deps, function(childPkg){ return crawl.fetchDep(context, pkg, childPkg, isRoot); }), truthy)).then(function(packages){ // at this point all dependencies of pkg have been loaded, it's ok to get their children return Promise.all(utils.map(packages, function(childPkg){ // Also load 'steal'
javascript
{ "resource": "" }
q1406
train
function(context, parentPkg, childPkg, isRoot){ var pkg = parentPkg; var isFlat = context.isFlatFileStructure; // if a peer dependency, and not isRoot if(childPkg._isPeerDependency && !isRoot ) { // check one node_module level higher childPkg.origFileUrl = nodeModuleAddress(pkg.fileUrl)+"/"+childPkg.name+"/package.json"; } else if(isRoot) { childPkg.origFileUrl = utils.path.depPackage(pkg.fileUrl, childPkg.name); } else { // npm 2 childPkg.origFileUrl = childPkg.nestedFileUrl = utils.path.depPackage(pkg.fileUrl, childPkg.name); if(isFlat) { // npm 3 childPkg.origFileUrl = crawl.parentMostAddress(context, childPkg); } } // check if childPkg matches a parent's version ... if
javascript
{ "resource": "" }
q1407
train
function(context, pkg, isRoot, deps){ var stealPkg = utils.filter(deps, function(dep){ return dep && dep.name === "steal"; })[0]; if(stealPkg) { return crawl.fetchDep(context, pkg, stealPkg, isRoot) .then(function(childPkg){
javascript
{ "resource": "" }
q1408
train
function(loader, packageJSON, isRoot){ var deps = crawl.getDependencyMap(loader, packageJSON, isRoot); var dependencies = [];
javascript
{ "resource": "" }
q1409
train
function(loader, packageJSON, isRoot){ var config = utils.pkg.config(packageJSON); var hasConfig = !!config; // convert npmIgnore var npmIgnore = hasConfig && config.npmIgnore; function convertToMap(arr) { var npmMap = {}; for(var i = 0; i < arr.length; i++) { npmMap[arr[i]] = true; } return npmMap; } if(npmIgnore && typeof npmIgnore.length === 'number') { npmIgnore = config.npmIgnore = convertToMap(npmIgnore); } // convert npmDependencies var npmDependencies = hasConfig && config.npmDependencies; if(npmDependencies && typeof npmDependencies.length === "number") { config.npmDependencies = convertToMap(npmDependencies); }
javascript
{ "resource": "" }
q1410
train
function(context, childPkg){ var curAddress = childPkg.origFileUrl; var parentAddress = utils.path.parentNodeModuleAddress(childPkg.origFileUrl); while(parentAddress) { var packageAddress = parentAddress+"/"+childPkg.name+"/package.json"; var parentPkg = context.paths[packageAddress]; if(parentPkg && SemVer.valid(parentPkg.version)) { if(SemVer.satisfies(parentPkg.version, childPkg.version)) {
javascript
{ "resource": "" }
q1411
train
function(pkg){ var pkg = pkg || this.getPackage(); var requestedVersion = this.requestedVersion; return SemVer.validRange(requestedVersion) &&
javascript
{ "resource": "" }
q1412
train
function(){ // If a task is currently loading this fileUrl, // wait for it to complete var loadingTask = this.context.loadingPaths[this.fileUrl]; if (!loadingTask) return; var task = this; return loadingTask.promise.then(function() { task._fetchedPackage = loadingTask.getPackage(); var firstTaskFailed = loadingTask.hadErrorLoading(); var currentTaskIsCompatible = task.isCompatibleVersion(); var firstTaskIsNotCompatible = !loadingTask.isCompatibleVersion(); // Do not flag the current task as failed if: // // - Current task fetches a version in rage and // - First task had no error loading at all or // - First task fetched an incompatible version // // otherwise, assume current task will fail for the same
javascript
{ "resource": "" }
q1413
train
function(){ // If it is already loaded check to see if it's semver compatible // and if so use it. Otherwise reject. var loadedPkg =
javascript
{ "resource": "" }
q1414
train
function(){ var pkg = utils.extend({}, this.orig); var isFlat = this.context.isFlatFileStructure; var fileUrl = this.pkg.fileUrl; var context = this.context; if(isFlat && !pkg.__crawledNestedPosition) { pkg.__crawledNestedPosition = true; pkg.nextFileUrl = pkg.nestedFileUrl; } else { // make sure we aren't loading something we've already loaded var parentAddress = utils.path.parentNodeModuleAddress(fileUrl); if(!parentAddress) {
javascript
{ "resource": "" }
q1415
npmLoad
train
function npmLoad(context, pkg){ var task = new FetchTask(context, pkg); return task.load().then(function(){ if(task.failed) { // Recurse. Calling task.next gives us a new pkg object // with the fileUrl
javascript
{ "resource": "" }
q1416
transformToString
train
function transformToString(xform) { var m = xform.matrix, text = ''; switch(xform.type) { case 1: // MATRIX text = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')'; break; case 2: // TRANSLATE text = 'translate(' + m.e + ',' + m.f + ')'; break; case 3: // SCALE
javascript
{ "resource": "" }
q1417
basicIdentityIsSet
train
function basicIdentityIsSet(){ return _.has(user, 'identities') && _.has(user.identities,
javascript
{ "resource": "" }
q1418
exists
train
function exists(cmd) { return run(`which ${cmd}`).then(stdout => { if (stdout.trim().length === 0) { // maybe an empty command was supplied? // are we running on Windows?? return Promise.reject(new Error("No output"));
javascript
{ "resource": "" }
q1419
Fireproof
train
function Fireproof(firebaseRef, promise) { if (!Fireproof.Promise) { try { Fireproof.Promise = Promise; } catch(e) { throw new Error('You must supply a Promise library to Fireproof!'); } } else if (typeof Fireproof.Promise !== 'function') { throw new Error('The supplied value of Fireproof.Promise is not a constructor (got ' + Fireproof.Promise + ')'); }
javascript
{ "resource": "" }
q1420
train
function(win, elems) { var mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } var is_node = (mode == "pathedit"); // if elems[1] is present, then we have more than one element selectedElement = (elems.length === 1 || elems[1] == null ? elems[0] : null); multiselected = (elems.length >= 2 && elems[1] != null); if (selectedElement != null) { // unless we're already in always set the mode of the editor to select because // upon creation of a text element the editor is switched into // select mode and this event fires - we need our UI to be in sync if (!is_node) {
javascript
{ "resource": "" }
q1421
train
function(win, elems) { var mode = svgCanvas.getMode(); var elem = elems[0]; if (!elem) { return; } multiselected = (elems.length >= 2 && elems[1] != null); // Only updating fields for single elements for now if (!multiselected) { switch (mode) { case 'rotate': var ang = svgCanvas.getRotationAngle(elem); $('#angle').val(ang);
javascript
{ "resource": "" }
q1422
train
function(win, elems) { var i, mode = svgCanvas.getMode(); if (mode === 'select') { setSelectMode(); } for (i = 0; i < elems.length; ++i) { var elem = elems[i]; // if the element changed was the svg, then it could be a resolution change if (elem && elem.tagName === 'svg') { populateLayers(); updateCanvas(); } // Update selectedElement if element is no longer part of the image. // This occurs for the text elements in Firefox else if (elem && selectedElement && selectedElement.parentNode == null) { // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why selectedElement = elem; } } Editor.showSaveWarning = true; // we update the contextual panel with potentially new
javascript
{ "resource": "" }
q1423
train
function(event) { var options = opts; //find the currently selected tool if comes from keystroke if (event.type === 'keydown') { var flyoutIsSelected = $(options.parent + '_show').hasClass('tool_button_current'); var currentOperation = $(options.parent + '_show').attr('data-curopt'); $.each(holders[opts.parent], function(i, tool) { if (tool.sel == currentOperation) { if (!event.shiftKey || !flyoutIsSelected) { options = tool; } else { options = holders[opts.parent][i+1] || holders[opts.parent][0]; } } }); } if ($(this).hasClass('disabled')) {return false;} if (toolButtonClick(show_sel)) { options.fn(); } var icon; if (options.icon) {
javascript
{ "resource": "" }
q1424
train
function(close) { var w = $('#sidepanels').width(); var deltaX = (w > 2 || close ? 2
javascript
{ "resource": "" }
q1425
train
function(width, height) { var newImage = svgCanvas.addSvgElementFromJson({ element: 'image', attr: { x: 0, y: 0, width: width, height: height, id: svgCanvas.getNextId(), style: 'pointer-events:inherit' } });
javascript
{ "resource": "" }
q1426
train
function(data, hashId, key) { if (hashId == -1) { // record key data.inputChar = key; data.lastEvent = "input"; } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { // check for repeated keypress if (data.lastEvent == "input") { data.lastEvent = "input1"; } else if (data.lastEvent == "input1") {
javascript
{ "resource": "" }
q1427
convertPropertyNames
train
function convertPropertyNames (context, pkg, map , root, waiting) { if(!map) { return map; } var clone = {}, value; for(var property in map ) { value = convertName(context, pkg, map, root, property, waiting); if(typeof value === 'string') { clone[value] = map[property]; } // do root paths b/c we don't know if they are going to be included with the package name or
javascript
{ "resource": "" }
q1428
convertPropertyNamesAndValues
train
function convertPropertyNamesAndValues (context, pkg, map, root, waiting) { if(!map) { return map; } var clone = {}, val, name; for(var property in map ) { val = map[property]; name = convertName(context, pkg, map, root, property, waiting); val = typeof val === "object" ?
javascript
{ "resource": "" }
q1429
convertBrowser
train
function convertBrowser(pkg, browser) { var type = typeof browser; if(type === "string" || type === "undefined") { return browser; } var map = {}; for(var fromName in browser) {
javascript
{ "resource": "" }
q1430
convertForPackage
train
function convertForPackage(context, pkg) { var name = pkg.name; var version = pkg.version; var conv = context.deferredConversions; var pkgConv = conv[name]; var depPkg, fns, keys = 0; if(pkgConv) { for(var range in
javascript
{ "resource": "" }
q1431
rebuildInput
train
function rebuildInput(form) { form.empty(); var inp = $('<input type="file" name="svg_file">').appendTo(form); function submit() { // This submits the form, which returns the file data using svgEditor.processFile() form.submit(); rebuildInput(form); $.process_cancel("Uploading...", function() {
javascript
{ "resource": "" }
q1432
max
train
function max(compare, iterable, dflt = undefined) { let iterator = (0, _iter.iter)(iterable); let first = iterator.next(); if (first.done) return dflt; let largest = first.value; for (let candidate of iterator)
javascript
{ "resource": "" }
q1433
train
function() { self.value += stepValue; self.setValue(self.value); self.triggerScrollEvent(self.value);
javascript
{ "resource": "" }
q1434
SelectList
train
function SelectList(options) { this.options = $.extend({ holder: null, maxVisibleItems: 10, selectOnClick: true, useHoverClass: false, useCustomScroll: false, handleResize: true, multipleSelectWithoutKey: false, alwaysPreventMouseWheel: false, indexAttribute: 'data-index', cloneClassPrefix: 'jcf-option-', containerStructure: '<span class="jcf-list"><span class="jcf-list-content"></span></span>', containerSelector: '.jcf-list-content',
javascript
{ "resource": "" }
q1435
isSerializedHelper
train
function isSerializedHelper(obj){ if (typeReflections.isPrimitive(obj)) { return true; } if(hasUpdateSymbol(obj)) { return false; } return
javascript
{ "resource": "" }
q1436
train
function(obj){ var hasOwnKey = obj[canSymbol.for("can.hasOwnKey")]; if(hasOwnKey) { return hasOwnKey.bind(obj); } else { var map =
javascript
{ "resource": "" }
q1437
addPatch
train
function addPatch(patches, patch) { var lastPatch = patches[patches.length -1]; if(lastPatch) { // same number of deletes and counts as the index is back if(lastPatch.deleteCount === lastPatch.insert.length && (patch.index - lastPatch.index === lastPatch.deleteCount) )
javascript
{ "resource": "" }
q1438
setComparator
train
function setComparator() { // If the first three letters are "asc", sort in ascending order // and remove the prefix. if (by.substring(0,3) == 'asc') { var i = by.substring(3); comp = function(a, b) { return a[i] - b[i]; }; } else { // Otherwise sort in descending order. comp = function(a, b)
javascript
{ "resource": "" }
q1439
initComparator
train
function initComparator() { by = 'rating'; // Default to sort by rating. // If the sortBy cookie is set, use that instead. if (document.cookie.length > 0) { var start = document.cookie.indexOf('sortBy='); if (start != -1) { start = start + 7; var end = document.cookie.indexOf(";",
javascript
{ "resource": "" }
q1440
show
train
function show(id) { $('#ao' + id).hide(); $('#ah' + id).show(); var context = $.extend({id: id}, opts); var popup = $(renderTemplate(popupTemplate, context)).hide(); popup.find('textarea[name="proposal"]').hide(); popup.find('a.by' + by).addClass('sel'); var form = popup.find('#cf' + id);
javascript
{ "resource": "" }
q1441
hide
train
function hide(id) { $('#ah' + id).hide(); $('#ao' + id).show(); var div = $('#sc' +
javascript
{ "resource": "" }
q1442
getComments
train
function getComments(id) { $.ajax({ type: 'GET', url: opts.getCommentsURL, data: {node: id}, success: function(data, textStatus, request) { var ul = $('#cl' + id); var speed = 100; $('#cf' + id) .find('textarea[name="proposal"]') .data('source', data.source); if (data.comments.length === 0) { ul.html('<li>No comments yet.</li>'); ul.data('empty', true); } else { // If there are comments, sort them and put them in the list. var comments = sortComments(data.comments); speed = data.comments.length * 100;
javascript
{ "resource": "" }
q1443
addComment
train
function addComment(form) { var node_id = form.find('input[name="node"]').val(); var parent_id = form.find('input[name="parent"]').val(); var text = form.find('textarea[name="comment"]').val(); var proposal = form.find('textarea[name="proposal"]').val(); if (text == '') { showError('Please enter a comment.'); return; } // Disable the form that is being submitted. form.find('textarea,input').attr('disabled', 'disabled'); // Send the comment to the server. $.ajax({ type: "POST", url: opts.addCommentURL, dataType: 'json', data: { node: node_id, parent: parent_id, text: text, proposal: proposal }, success: function(data, textStatus, error) { // Reset the form. if (node_id) { hideProposeChange(node_id); } form.find('textarea') .val('') .add(form.find('input')) .removeAttr('disabled'); var ul = $('#cl' + (node_id || parent_id)); if (ul.data('empty')) { $(ul).empty();
javascript
{ "resource": "" }
q1444
appendComments
train
function appendComments(comments, ul) { $.each(comments, function() { var div = createCommentDiv(this); ul.append($(document.createElement('li')).html(div)); appendComments(this.children, div.find('ul.comment-children')); // To avoid stagnating
javascript
{ "resource": "" }
q1445
insertComment
train
function insertComment(comment) { var div = createCommentDiv(comment); // To avoid stagnating data, don't store the comments children in data. comment.children = null; div.data('comment', comment); var ul = $('#cl' + (comment.node || comment.parent)); var siblings = getChildren(ul); var li = $(document.createElement('li')); li.hide(); // Determine where in the parents children list to insert this comment. for(i=0; i < siblings.length; i++) { if (comp(comment, siblings[i]) <= 0) { $('#cd' + siblings[i].id) .parent()
javascript
{ "resource": "" }
q1446
handleReSort
train
function handleReSort(link) { var classes = link.attr('class').split(/\s+/); for (var i=0; i<classes.length; i++) { if (classes[i] != 'sort-option') { by = classes[i].substring(2); } } setComparator(); // Save/update the sortBy cookie. var expiration = new Date(); expiration.setDate(expiration.getDate() + 365); document.cookie= 'sortBy=' + escape(by) +
javascript
{ "resource": "" }
q1447
handleVote
train
function handleVote(link) { if (!opts.voting) { showError("You'll need to login to vote."); return; } var id = link.attr('id'); if (!id) { // Didn't click on one of the voting arrows. return; } // If it is an unvote, the new vote value is 0, // Otherwise it's 1 for an upvote, or -1 for a downvote. var value = 0; if (id.charAt(1) != 'u') { value = id.charAt(0) == 'u' ? 1 : -1; } // The data to be sent to the server. var d = { comment_id: id.substring(2), value: value }; // Swap the vote and unvote links. link.hide(); $('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id) .show();
javascript
{ "resource": "" }
q1448
openReply
train
function openReply(id) { // Swap out the reply link for the hide link $('#rl' + id).hide(); $('#cr' + id).show(); // Add the reply li to the children ul. var div = $(renderTemplate(replyTemplate, {id: id})).hide(); $('#cl' + id) .prepend(div) // Setup the submit handler for the reply form. .find('#rf' + id) .submit(function(event) {
javascript
{ "resource": "" }
q1449
sortComments
train
function sortComments(comments) { comments.sort(comp); $.each(comments, function() { this.children
javascript
{ "resource": "" }
q1450
getChildren
train
function getChildren(ul, recursive) { var children = []; ul.children().children("[id^='cd']") .each(function() { var comment = $(this).data('comment'); if (recursive)
javascript
{ "resource": "" }
q1451
createCommentDiv
train
function createCommentDiv(comment) { if (!comment.displayed && !opts.moderator) { return $('<div class="moderate">Thank you! Your comment will show up ' + 'once it is has been approved by a moderator.</div>'); } // Prettify the comment rating. comment.pretty_rating = comment.rating + ' point' + (comment.rating == 1 ? '' : 's'); // Make a class (for displaying not yet moderated comments differently) comment.css_class = comment.displayed ? '' : ' moderate'; // Create a div for this comment. var context = $.extend({}, opts, comment); var div = $(renderTemplate(commentTemplate, context)); // If the user has voted on this comment, highlight the correct arrow. if (comment.vote) { var direction = (comment.vote == 1) ? 'u' : 'd'; div.find('#' + direction + 'v'
javascript
{ "resource": "" }
q1452
showError
train
function showError(message) { $(document.createElement('div')).attr({'class': 'popup-error'}) .append($(document.createElement('div')) .attr({'class': 'error-message'}).text(message))
javascript
{ "resource": "" }
q1453
train
function(object, otherterms) { var filenames = this._index.filenames; var docnames = this._index.docnames; var objects = this._index.objects; var objnames = this._index.objnames; var titles = this._index.titles; var i; var results = []; for (var prefix in objects) { for (var name in objects[prefix]) { var fullname = (prefix ? prefix + '.' : '') + name; if (fullname.toLowerCase().indexOf(object) > -1) { var score = 0; var parts = fullname.split('.'); // check for different match types: exact matches of full name or // "last name" (i.e. last dotted part) if (fullname == object || parts[parts.length - 1] == object) { score += Scorer.objNameMatch; // matches in last name } else if (parts[parts.length - 1].indexOf(object) > -1) { score += Scorer.objPartialMatch; } var match = objects[prefix][name]; var objname = objnames[match[1]][2]; var title = titles[match[0]]; // If more than one term searched for, we require other words to be // found in the name/title/description if (otherterms.length > 0) { var haystack = (prefix + ' ' + name + ' ' + objname + ' ' + title).toLowerCase(); var allfound = true; for (i = 0; i < otherterms.length; i++) { if (haystack.indexOf(otherterms[i]) == -1) { allfound = false; break; } }
javascript
{ "resource": "" }
q1454
train
function(searchterms, excluded, terms, titleterms) { var docnames = this._index.docnames; var filenames = this._index.filenames; var titles = this._index.titles; var i, j, file; var fileMap = {}; var scoreMap = {}; var results = []; // perform the search on the required terms for (i = 0; i < searchterms.length; i++) { var word = searchterms[i]; var files = []; var _o = [ {files: terms[word], score: Scorer.term}, {files: titleterms[word], score: Scorer.title} ]; // no match but word was a required one if ($u.every(_o, function(o){return o.files === undefined;})) { break; } // found search word in contents $u.each(_o, function(o) { var _files = o.files; if (_files === undefined) return if (_files.length === undefined) _files = [_files]; files = files.concat(_files); // set score for the word in each file to Scorer.term for (j = 0; j < _files.length; j++) {
javascript
{ "resource": "" }
q1455
clean
train
function clean(args) { return Array.prototype.filter.
javascript
{ "resource": "" }
q1456
json
train
function json (program, callback) { var formatterRedux = formatter(jsonRedux())
javascript
{ "resource": "" }
q1457
getPythonExecutable
train
function getPythonExecutable(options, platform) { if (options.virtualenv) { var isWin = /^win/.test(platform); var pythonExec = isWin ? path.join(options.virtualenv, 'Scripts', 'python.exe') :
javascript
{ "resource": "" }
q1458
getPythonCode
train
function getPythonCode(options) { var pythonCode = [], internalPylint = !options.externalPylint, pylintPath = path.join(__dirname, 'lib'), initHook = options.initHook; delete options.initHook; if (initHook) { pythonCode.push(initHook); } if (internalPylint) { pythonCode.push('import sys',
javascript
{ "resource": "" }
q1459
train
function (options) { var pylintArgs = []; var enable = options.enable; delete options.enable; if (enable) { pylintArgs.push('--enable=' + enable); } var disable = options.disable; delete options.disable; if (disable) { pylintArgs.push('--disable=' + disable); } var messageTemplate = options.messageTemplate; delete options.messageTemplate; if (messageTemplate) { var aliases = { 'short': "line {line}: {msg} ({symbol})", 'msvs': "{path}({line}): [{msg_id}({symbol}){obj}] {msg}", 'parseable': "{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}", }; if (aliases[messageTemplate] !== undefined) { pylintArgs.push('--msg-template="' + aliases[messageTemplate] + '"'); } else { pylintArgs.push('--msg-template="' + messageTemplate + '"'); } } var outputFormat = options.outputFormat; delete options.outputFormat; if (outputFormat) { pylintArgs.push('--output-format=' + outputFormat); } var report = options.report; delete options.report; // Make compatible with --reports as well if (options.reports) { report = options.reports; delete options.reports; } if (report) { pylintArgs.push('--reports=y'); } else { pylintArgs.push('--reports=n'); } var rcfile = options.rcfile;
javascript
{ "resource": "" }
q1460
normalizeDistance
train
function normalizeDistance(distance = 0) { if (typeof distance !== 'object')
javascript
{ "resource": "" }
q1461
mark
train
function mark(markName) { if (enabled) { marks[markName] = ts.timestamp(); counts[markName] =
javascript
{ "resource": "" }
q1462
measure
train
function measure(measureName, startMarkName, endMarkName) { if (enabled) { var end = endMarkName && marks[endMarkName] || ts.timestamp();
javascript
{ "resource": "" }
q1463
find
train
function find(array, predicate) { for (var i = 0, len = array.length; i < len; i++) {
javascript
{ "resource": "" }
q1464
findMap
train
function findMap(array, callback) { for (var i = 0, len = array.length; i < len; i++) {
javascript
{ "resource": "" }
q1465
filter
train
function filter(array, f) { if (array) { var len = array.length; var i = 0; while (i < len && f(array[i])) i++; if (i < len) { var result = array.slice(0, i); i++; while (i < len) { var item = array[i];
javascript
{ "resource": "" }
q1466
getOwnKeys
train
function getOwnKeys(map) { var keys = []; for (var key in map) if (hasOwnProperty.call(map, key)) {
javascript
{ "resource": "" }
q1467
reduceProperties
train
function reduceProperties(map, callback, initial) { var result = initial; for (var key in map) {
javascript
{ "resource": "" }
q1468
equalOwnProperties
train
function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; if (!left || !right) return false; for (var key in left) if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false;
javascript
{ "resource": "" }
q1469
removeTrailingDirectorySeparator
train
function removeTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) === ts.directorySeparator) { return
javascript
{ "resource": "" }
q1470
ensureTrailingDirectorySeparator
train
function ensureTrailingDirectorySeparator(path) { if (path.charAt(path.length - 1) !== ts.directorySeparator) { return
javascript
{ "resource": "" }
q1471
getBasePaths
train
function getBasePaths(path, includes, useCaseSensitiveFileNames) { // Storage for our results in the form of literal paths (e.g. the paths as written by the user). var basePaths = [path]; if (includes) { // Storage for literal base paths amongst the include patterns. var includeBasePaths = []; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); var includeBasePath = wildcardOffset < 0 ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) : absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); // Append the literal and canonical candidate base paths. includeBasePaths.push(includeBasePath); } // Sort the offsets array using either the literal or
javascript
{ "resource": "" }
q1472
isWhiteSpaceSingleLine
train
function isWhiteSpaceSingleLine(ch) { // Note: nextLine is in the Zs space, and should be considered to be a whitespace. // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ || ch === 160 /* nonBreakingSpace */ || ch === 133 /* nextLine */ ||
javascript
{ "resource": "" }
q1473
isRequireCall
train
function isRequireCall(expression, checkArgumentIsStringLiteral) { // of the form 'require("name")' var isRequire = expression.kind === 174 /* CallExpression */ && expression.expression.kind === 69 /* Identifier */ && expression.expression.text === "require" &&
javascript
{ "resource": "" }
q1474
isDeclarationOfFunctionExpression
train
function isDeclarationOfFunctionExpression(s) { if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) {
javascript
{ "resource": "" }
q1475
cloneNode
train
function cloneNode(node, location, flags, parent) { // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = location !== undefined ? ts.createNode(node.kind, location.pos, location.end) : createSynthesizedNode(node.kind); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
javascript
{ "resource": "" }
q1476
cloneEntityName
train
function cloneEntityName(node, parent) { var clone = cloneNode(node, node, node.flags, parent); if (isQualifiedName(clone)) {
javascript
{ "resource": "" }
q1477
getExternalModuleNameFromPath
train
function getExternalModuleNameFromPath(host, fileName) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
javascript
{ "resource": "" }
q1478
emitDetachedComments
train
function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { // removeComments is true, only reserve pinned comment at the top of file // For example: // /*! Pinned Comment */ // // var x = 10; if (node.pos === 0) { leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; var lastComment = void 0; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so // far. break; } } detachedComments.push(comment); lastComment = comment; } if (detachedComments.length) { // All comments look like they could have been part of the copyright header.
javascript
{ "resource": "" }
q1479
tryExtractTypeScriptExtension
train
function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension,
javascript
{ "resource": "" }
q1480
convertToBase64
train
function convertToBase64(input) { var result = ""; var charCodes = getExpandedCharCodes(input); var i = 0; var length = charCodes.length; var byte1, byte2, byte3, byte4; while (i < length) { // Convert every 6-bits in the input 3 character points // into a base64 digit byte1 = charCodes[i] >> 2; byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
javascript
{ "resource": "" }
q1481
collapseTextChangeRangesAcrossMultipleVersions
train
function collapseTextChangeRangesAcrossMultipleVersions(changes) { if (changes.length === 0) { return ts.unchangedTextChangeRange; } if (changes.length === 1) { return changes[0]; } // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. var change0 = changes[0]; var oldStartN = change0.span.start; var oldEndN = textSpanEnd(change0.span); var newEndN = oldStartN + change0.newLength; for (var i = 1; i < changes.length; i++) { var nextChange = changes[i]; // Consider the following case: // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. // i.e. the span starting at 30 with length 30 is increased to length 40. // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------------------------------------------------- // | / // | /---- // T1 | /---- // | /---- // | /---- // ------------------------------------------------------------------------------------------------------- // | \ // | \ // T2 | \ // | \ // | \ // ------------------------------------------------------------------------------------------------------- // // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial // it's just the min of the old and new starts. i.e.: // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------*------------------------------------------ // | / // | /---- // T1 | /---- // | /---- // | /---- // ----------------------------------------$-------------------$------------------------------------------ // . | \ // . | \ // T2 . | \ // . | \ // . | \ // ----------------------------------------------------------------------*-------------------------------- // // (Note the dots represent the newly inferred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // // 0 10 20 30 40 50 60 70 80 90 100 // --------------------------------------------------------------------------------*---------------------- // | / // | /---- // T1 | /---- // |
javascript
{ "resource": "" }
q1482
isIdentifier
train
function isIdentifier() { if (token() === 69 /* Identifier */) { return true; } // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is // considered a keyword and is not an identifier. if (token() === 114 /* YieldKeyword */ && inYieldContext()) { return false; } // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
javascript
{ "resource": "" }
q1483
isListElement
train
function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); if (node) { return true; } switch (parsingContext) { case 0 /* SourceElements */: case 1 /* BlockStatements */: case 3 /* SwitchClauseStatements */: // If we're in error recovery, then we don't want to treat ';' as an empty statement. // The problem is that ';' can show up in far too many contexts, and if we see one // and assume it's a statement, then we may bail out inappropriately from whatever // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. return !(token() === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); case 2 /* SwitchClauses */: return token() === 71 /* CaseKeyword */ || token() === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: // We allow semicolons as class elements (as specified by ES6) as long as we're // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. return lookAhead(isClassMemberStart) || (token() === 23 /* SemicolonToken */ && !inErrorRecovery); case 6 /* EnumMembers */: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: return token() === 19 /* OpenBracketToken */ || token() === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: return token() === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. if (token() === 15 /* OpenBraceToken */) { return lookAhead(isValidHeritageClauseObjectLiteral); } if (!inErrorRecovery) { return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); } else { // If we're in error recovery we tighten up what we're willing to match. // That way we don't treat something like "this" as a valid heritage clause // element during recovery. return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); } case 8 /* VariableDeclarations */: return isIdentifierOrPattern();
javascript
{ "resource": "" }
q1484
isInSomeParsingContext
train
function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
javascript
{ "resource": "" }
q1485
parseList
train
function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue;
javascript
{ "resource": "" }
q1486
parseDelimitedList
train
function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { continue; } commaStart = -1; // Back to the state where the last token was not a comma if (isListTerminator(kind)) { break; } // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. parseExpected(24 /* CommaToken */); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. if (considerSemicolonAsDelimiter && token() === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; }
javascript
{ "resource": "" }
q1487
parseUnaryExpressionOrHigher
train
function parseUnaryExpressionOrHigher() { /** * ES7 UpdateExpression: * 1) LeftHandSideExpression[?Yield] * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- * 4) ++UnaryExpression[?Yield] * 5) --UnaryExpression[?Yield] */ if (isUpdateExpression()) { var incrementExpression = parseIncrementExpression(); return token() === 38 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } /** * ES7 UnaryExpression: * 1) UpdateExpression[?yield] * 2) delete UpdateExpression[?yield] * 3) void UpdateExpression[?yield] * 4) typeof UpdateExpression[?yield] * 5) + UpdateExpression[?yield] * 6) - UpdateExpression[?yield] * 7) ~ UpdateExpression[?yield] * 8) ! UpdateExpression[?yield] */
javascript
{ "resource": "" }
q1488
parseIncrementExpression
train
function parseIncrementExpression() { if (token() === 41 /* PlusPlusToken */ || token() === 42 /* MinusMinusToken */) { var node = createNode(185 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); return finishNode(node); } else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { // JSXElement is part of primaryExpression return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } var expression = parseLeftHandSideExpressionOrHigher();
javascript
{ "resource": "" }
q1489
parseEnumMember
train
function parseEnumMember() { var node = createNode(255 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName();
javascript
{ "resource": "" }
q1490
tryFile
train
function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures && state.host.fileExists(fileName)) { if (state.traceEnabled) { ts.trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); } return fileName; } else { if (state.traceEnabled) {
javascript
{ "resource": "" }
q1491
tryAddingExtensions
train
function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { onlyRecordFailures = !directoryProbablyExists(directory, state.host); } }
javascript
{ "resource": "" }
q1492
getDeclarationName
train
function getDeclarationName(node) { if (node.name) { if (ts.isAmbientModule(node)) { return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } if (node.name.kind === 140 /* ComputedPropertyName */) { var nameExpression = node.name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression.kind)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } return node.name.text; } switch (node.kind) { case 148 /* Constructor */: return "__constructor"; case 156 /* FunctionType */: case 151 /* CallSignature */: return "__call"; case 157 /* ConstructorType */: case 152 /* ConstructSignature */: return "__new"; case 153 /* IndexSignature */: return "__index"; case 236 /* ExportDeclaration */: return "__export"; case 235 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; case 187 /* BinaryExpression */:
javascript
{ "resource": "" }
q1493
declareSymbol
train
function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); var isDefaultExport = node.flags & 512 /* Default */; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name === undefined) { symbol = createSymbol(0 /* None */, "__missing"); } else { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't // give the new symbol any flags *yet*. This ensures that it will not conflict // with the 'excludes' flags we pass in. // // If we do get an existing symbol, see if it conflicts with the new symbol we're // creating. For example, a 'var' symbol and a 'class' symbol will conflict within // the same symbol table. If we have a conflict, report the issue on each // declaration we have for this symbol, and then create a new symbol for this // declaration. // // Note that when properties declared in Javascript constructors // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. // Always. This allows the common Javascript pattern of overwriting a prototype method // with an bound instance method of the same type: `this.method = this.method.bind(this)` // // If we created a new symbol, either because we didn't have a symbol with this name //
javascript
{ "resource": "" }
q1494
bindContainer
train
function bindContainer(node, containerFlags) { // Before we recurse into a node's children, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. var saveContainer = container; var savedBlockScopeContainer = blockScopeContainer; // Depending on what kind of node this is, we may have to adjust the current container // and block-container. If the current node is a container, then it is automatically // considered the current block-container as well. Also, for containers that we know // may contain locals, we proactively initialize the .locals field. We do this because // it's highly likely that the .locals will be needed to place some child in (for example, // a parameter, or variable declaration). // // However, we do not proactively create the .locals for block-containers because it's // totally normal and common for block-containers to never actually have a block-scoped // variable in them. We don't want to end up allocating an object for every 'block' we // run into when most of them won't be necessary. // // Finally, if this is a block-container, then we clear out any existing .locals object // it may contain within it. This happens in incremental scenarios. Because we can be // reusing a node from a previous compilation, that node may have had 'locals' created // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { container.locals = ts.createMap(); } addToContainerChain(container); } else if (containerFlags & 2 /* IsBlockScopedContainer */) { blockScopeContainer = node; blockScopeContainer.locals = undefined; } if (containerFlags & 4 /* IsControlFlowContainer */) { var saveCurrentFlow = currentFlow; var saveBreakTarget = currentBreakTarget; var saveContinueTarget = currentContinueTarget; var saveReturnTarget = currentReturnTarget; var saveActiveLabels = activeLabels; var saveHasExplicitReturn = hasExplicitReturn; var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !!ts.getImmediatelyInvokedFunctionExpression(node); // An IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (isIIFE) { currentReturnTarget = createBranchLabel(); } else { currentFlow = { flags: 2 /* Start */ }; if (containerFlags & 16 /* IsFunctionExpression */) { currentFlow.container = node; } currentReturnTarget = undefined; } currentBreakTarget = undefined; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false;
javascript
{ "resource": "" }
q1495
checkStrictModeIdentifier
train
function checkStrictModeIdentifier(node) { if (inStrictMode && node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && node.originalKeywordKind <= 114 /* LastFutureReservedWord */ && !ts.isIdentifierName(node) &&
javascript
{ "resource": "" }
q1496
getSymbolsOfParameterPropertyDeclaration
train
function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */);
javascript
{ "resource": "" }
q1497
getEntityNameForExtendingInterface
train
function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 69 /* Identifier */: case 172 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; case 194 /* ExpressionWithTypeArguments */:
javascript
{ "resource": "" }
q1498
getSymbolOfPartOfRightHandSideOfImportEquals
train
function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration, dontResolveAlias) { // There are three things we might try to look for. In the following examples, // the search term is enclosed in |...|: // // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
javascript
{ "resource": "" }
q1499
extendExportSymbols
train
function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !target[id]) { target[id] = source[id]; if (lookupTable && exportNode) { lookupTable[id] = { specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) }; } }
javascript
{ "resource": "" }