_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q24700
getDirectoryContents
train
function getDirectoryContents(remotePath, options) { const getOptions = merge(baseOptions, options || {}); return directoryContents.getDirectoryContents(remotePath, getOptions); }
javascript
{ "resource": "" }
q24701
getFileContents
train
function getFileContents(remoteFilename, options) { const getOptions = merge(baseOptions, options || {}); getOptions.format = getOptions.format || "binary"; if (["binary", "text"].indexOf(getOptions.format) < 0) { throw new Error("Unknown format: " + getOptions.format); } return getOptions.format === "text" ? getFile.getFileContentsString(remoteFilename, getOptions) : getFile.getFileContentsBuffer(remoteFilename, getOptions); }
javascript
{ "resource": "" }
q24702
getFileDownloadLink
train
function getFileDownloadLink(remoteFilename, options) { const getOptions = merge(baseOptions, options || {}); return getFile.getFileLink(remoteFilename, getOptions); }
javascript
{ "resource": "" }
q24703
getFileUploadLink
train
function getFileUploadLink(remoteFilename, options) { var putOptions = merge(baseOptions, options || {}); return putFile.getFileUploadLink(remoteFilename, putOptions); }
javascript
{ "resource": "" }
q24704
moveFile
train
function moveFile(remotePath, targetRemotePath, options) { const moveOptions = merge(baseOptions, options || {}); return move.moveFile(remotePath, targetRemotePath, moveOptions); }
javascript
{ "resource": "" }
q24705
putFileContents
train
function putFileContents(remoteFilename, data, options) { const putOptions = merge(baseOptions, options || {}); return putFile.putFileContents(remoteFilename, data, putOptions); }
javascript
{ "resource": "" }
q24706
stat
train
function stat(remotePath, options) { const getOptions = merge(baseOptions, options || {}); return stats.getStat(remotePath, getOptions); }
javascript
{ "resource": "" }
q24707
encodePath
train
function encodePath(path) { const replaced = path.replace(/\//g, SEP_PATH_POSIX).replace(/\\\\/g, SEP_PATH_WINDOWS); const formatted = encodeURIComponent(replaced); return formatted .split(SEP_PATH_WINDOWS) .join("\\\\") .split(SEP_PATH_POSIX) .join("/"); }
javascript
{ "resource": "" }
q24708
callApi
train
function callApi() { vm.pageInfiniteScroll++; vm.loadingInfiniteScroll = true; return $http .get( 'https://randomuser.me/api/?results=10&seed=lumapps&page=' + vm.pageInfiniteScroll ) .then(function(response) { if (response.data && response.data.results) { return response.data.results.map(function(person) { return { name: person.name.first, email: person.email, age: person.dob.age }; }); } else { return []; } }) .catch(function() { return []; }) .finally(function() { vm.loadingInfiniteScroll = false; }); }
javascript
{ "resource": "" }
q24709
reComputeElementsPosition
train
function reComputeElementsPosition() { var baseOffset = 0; for (var idx = notificationList.length -1; idx >= 0; idx--) { notificationList[idx].height = getElementHeight(notificationList[idx].elem[0]); notificationList[idx].margin = baseOffset; notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px'); baseOffset += notificationList[idx].height + 24; } }
javascript
{ "resource": "" }
q24710
buildDialogActions
train
function buildDialogActions(_buttons, _callback, _unbind) { var $compile = $injector.get('$compile'); var dialogActions = angular.element('<div/>', { class: 'dialog__footer' }); var dialogLastBtn = angular.element('<button/>', { class: 'btn btn--m btn--blue btn--flat', text: _buttons.ok }); if (angular.isDefined(_buttons.cancel)) { var dialogFirstBtn = angular.element('<button/>', { class: 'btn btn--m btn--red btn--flat', text: _buttons.cancel }); dialogFirstBtn.attr('lx-ripple', ''); $compile(dialogFirstBtn)($rootScope); dialogActions.append(dialogFirstBtn); dialogFirstBtn.bind('click', function() { _callback(false); closeDialog(); }); } dialogLastBtn.attr('lx-ripple', ''); $compile(dialogLastBtn)($rootScope); dialogActions.append(dialogLastBtn); dialogLastBtn.bind('click', function() { _callback(true); closeDialog(); }); if (!_unbind) { idEventScheduler = LxEventSchedulerService.register('keyup', function(event) { if (event.keyCode == 13) { _callback(true); closeDialog(); } else if (event.keyCode == 27) { _callback(angular.isUndefined(_buttons.cancel)); closeDialog(); } event.stopPropagation(); }); } return dialogActions; }
javascript
{ "resource": "" }
q24711
_closePanes
train
function _closePanes() { toggledPanes = {}; if (lxSelect.choicesViewSize === 'large') { if (angular.isDefined(lxSelect.choices) && lxSelect.choices !== null) { lxSelect.panes = [lxSelect.choices]; } else { lxSelect.panes = []; } } else { if (angular.isDefined(lxSelect.choices) && lxSelect.choices !== null) { lxSelect.openedPanes = [lxSelect.choices]; } else { lxSelect.openedPanes = []; } } }
javascript
{ "resource": "" }
q24712
_findIndex
train
function _findIndex(haystack, needle) { if (angular.isUndefined(haystack) || haystack.length === 0) { return -1; } for (var i = 0, len = haystack.length; i < len; i++) { if (haystack[i] === needle) { return i; } } return -1; }
javascript
{ "resource": "" }
q24713
_getLongestMatchingPath
train
function _getLongestMatchingPath(containing) { if (angular.isUndefined(lxSelect.matchingPaths) || lxSelect.matchingPaths.length === 0) { return undefined; } containing = containing || lxSelect.matchingPaths[0]; var longest = lxSelect.matchingPaths[0]; var longestSize = longest.split('.').length; for (var i = 1, len = lxSelect.matchingPaths.length; i < len; i++) { var matchingPath = lxSelect.matchingPaths[i]; if (!matchingPath) { continue; } if (matchingPath.indexOf(containing) === -1) { break; } var size = matchingPath.split('.').length; if (size > longestSize) { longest = matchingPath; longestSize = size; } } return longest; }
javascript
{ "resource": "" }
q24714
_keyLeft
train
function _keyLeft() { if (lxSelect.choicesViewMode !== 'panes' || lxSelect.panes.length < 2) { return; } var previousPaneIndex = lxSelect.panes.length - 2; lxSelect.activeChoiceIndex = ( Object.keys(lxSelect.panes[previousPaneIndex]) || [] ).indexOf( (toggledPanes[previousPaneIndex] || {}).key ); _closePane(previousPaneIndex); }
javascript
{ "resource": "" }
q24715
_keyRight
train
function _keyRight() { if (lxSelect.choicesViewMode !== 'panes' || lxSelect.activeChoiceIndex === -1) { return; } var paneOpened = _openPane((lxSelect.panes.length - 1), lxSelect.activeChoiceIndex, true); if (paneOpened) { lxSelect.activeChoiceIndex = 0; } else { _keySelect(); } }
javascript
{ "resource": "" }
q24716
_keySelect
train
function _keySelect() { var filteredChoices; if (lxSelect.choicesViewMode === 'panes') { filteredChoices = lxSelect.panes[(lxSelect.panes.length - 1)]; if (!lxSelect.isLeaf(filteredChoices[lxSelect.activeChoiceIndex])) { return; } } else { filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel); } if (filteredChoices.length && filteredChoices[lxSelect.activeChoiceIndex]) { lxSelect.toggleChoice(filteredChoices[lxSelect.activeChoiceIndex]); } else if (lxSelect.filterModel && lxSelect.allowNewValue) { if (angular.isArray(getSelectedModel())) { var value = angular.isFunction(lxSelect.newValueTransform) ? lxSelect.newValueTransform(lxSelect.filterModel) : lxSelect.filterModel; var identical = getSelectedModel().some(function (item) { return angular.equals(item, value); }); if (!identical) { lxSelect.getSelectedModel().push(value); } } lxSelect.filterModel = undefined; LxDropdownService.close('dropdown-' + lxSelect.uuid); } }
javascript
{ "resource": "" }
q24717
_openPane
train
function _openPane(parentIndex, indexOrKey, checkIsLeaf) { if (angular.isDefined(toggledPanes[parentIndex])) { return false; } var pane = pane || lxSelect.choicesViewSize === 'large' ? lxSelect.panes[parentIndex] : lxSelect.openedPanes[parentIndex]; if (angular.isUndefined(pane)) { return false; } var key = indexOrKey; if (angular.isObject(pane) && angular.isNumber(key)) { key = (Object.keys(pane) || [])[key]; } if (checkIsLeaf && lxSelect.isLeaf(pane[key])) { return false; } if (lxSelect.choicesViewSize === 'large') { lxSelect.panes.push(pane[key]); } else { lxSelect.openedPanes.push(pane[key]); } toggledPanes[parentIndex] = { key: key, position: lxSelect.choicesViewSize === 'large' ? lxSelect.panes.length - 1 : lxSelect.openedPanes.length - 1, path: (parentIndex === 0) ? key : toggledPanes[parentIndex - 1].path + '.' + key, }; return true; }
javascript
{ "resource": "" }
q24718
_searchPath
train
function _searchPath(container, regexp, previousKey, limitToFields) { limitToFields = limitToFields || []; limitToFields = (angular.isArray(limitToFields)) ? limitToFields : [limitToFields]; var results = []; angular.forEach(container, function forEachItemsInContainer(items, key) { if (limitToFields.length > 0 && limitToFields.indexOf(key) === -1) { return; } var pathToMatching = (previousKey) ? previousKey + '.' + key : key; var previousKeyAdded = false; var isLeaf = lxSelect.isLeaf(items); if ((!isLeaf && angular.isString(key) && regexp.test(key)) || (angular.isString(items) && regexp.test(items))) { if (!previousKeyAdded && previousKey) { results.push(previousKey); } if (!isLeaf) { results.push(pathToMatching); } } if (angular.isArray(items) || angular.isObject(items)) { var newPaths = _searchPath(items, regexp, pathToMatching, (isLeaf) ? lxSelect.filterFields : []); if (angular.isDefined(newPaths) && newPaths.length > 0) { if (previousKey) { results.push(previousKey); previousKeyAdded = true; } results = results.concat(newPaths); } } }); return results; }
javascript
{ "resource": "" }
q24719
isLeaf
train
function isLeaf(obj) { if (angular.isUndefined(obj)) { return false; } if (angular.isArray(obj)) { return false; } if (!angular.isObject(obj)) { return true; } if (obj.isLeaf) { return true; } var isLeaf = false; var keys = Object.keys(obj); for (var i = 0, len = keys.length; i < len; i++) { var property = keys[i]; if (property.charAt(0) === '$') { continue; } if (!angular.isArray(obj[property]) && !angular.isObject(obj[property])) { isLeaf = true; break; } } return isLeaf; }
javascript
{ "resource": "" }
q24720
isPaneToggled
train
function isPaneToggled(parentIndex, indexOrKey) { var pane = lxSelect.choicesViewSize === 'large' ? lxSelect.panes[parentIndex] : lxSelect.openedPanes[parentIndex]; if (angular.isUndefined(pane)) { return false; } var key = indexOrKey; if (angular.isObject(pane) && angular.isNumber(indexOrKey)) { key = (Object.keys(pane) || [])[indexOrKey]; } return angular.isDefined(toggledPanes[parentIndex]) && toggledPanes[parentIndex].key === key; }
javascript
{ "resource": "" }
q24721
isMatchingPath
train
function isMatchingPath(parentIndex, indexOrKey) { var pane = lxSelect.choicesViewSize === 'large' ? lxSelect.panes[parentIndex] : lxSelect.openedPanes[parentIndex]; if (angular.isUndefined(pane)) { return; } var key = indexOrKey; if (angular.isObject(pane) && angular.isNumber(indexOrKey)) { key = (Object.keys(pane) || [])[indexOrKey]; } if (parentIndex === 0) { return _findIndex(lxSelect.matchingPaths, key) !== -1; } var previous = toggledPanes[parentIndex - 1]; if (angular.isUndefined(previous)) { return false; } return _findIndex(lxSelect.matchingPaths, previous.path + '.' + key) !== -1; }
javascript
{ "resource": "" }
q24722
keyEvent
train
function keyEvent(evt) { if (evt.keyCode !== 8) { lxSelect.activeSelectedIndex = -1; } if (!LxDropdownService.isOpen('dropdown-' + lxSelect.uuid)) { lxSelect.activeChoiceIndex = -1; } switch (evt.keyCode) { case 8: _keyRemove(); break; case 13: _keySelect(); evt.preventDefault(); break; case 37: if (lxSelect.activeChoiceIndex > -1) { _keyLeft(); evt.preventDefault(); } break; case 38: _keyUp(); evt.preventDefault(); break; case 39: if (lxSelect.activeChoiceIndex > -1) { _keyRight(); evt.preventDefault(); } break; case 40: _keyDown(); evt.preventDefault(); break; default: break; } }
javascript
{ "resource": "" }
q24723
toggleChoice
train
function toggleChoice(choice, evt) { if (lxSelect.multiple && !lxSelect.autocomplete && angular.isDefined(evt)) { evt.stopPropagation(); } if (lxSelect.areChoicesOpened() && lxSelect.multiple) { var dropdownElement = angular.element(angular.element(evt.target).closest('.dropdown-menu--is-open')[0]); // If the dropdown element is scrollable, fix the content div height to keep the current scroll state. if (dropdownElement.scrollTop() > 0) { var dropdownContentElement = angular.element(dropdownElement.find('.dropdown-menu__content')[0]); var dropdownFilterElement = angular.element(dropdownContentElement.find('.lx-select-choices__filter')[0]); var newHeight = dropdownContentElement.height(); newHeight -= (dropdownFilterElement.length) ? dropdownFilterElement.outerHeight() : 0; var dropdownListElement = angular.element(dropdownContentElement.find('ul > div')[0]); dropdownListElement.css('height', newHeight + 'px'); // This function is called when the ng-change attached to the filter input is called. lxSelect.resetDropdownSize = function() { dropdownListElement.css('height', 'auto'); lxSelect.resetDropdownSize = undefined; } } } if (lxSelect.multiple && isSelected(choice)) { lxSelect.unselect(choice); } else { lxSelect.select(choice); } if (lxSelect.autocomplete) { lxSelect.activeChoiceIndex = -1; lxSelect.filterModel = undefined; } if (lxSelect.autocomplete || (lxSelect.choicesViewMode === 'panes' && !lxSelect.multiple)) { LxDropdownService.close('dropdown-' + lxSelect.uuid); } }
javascript
{ "resource": "" }
q24724
togglePane
train
function togglePane(evt, parentIndex, indexOrKey, selectLeaf) { selectLeaf = (angular.isUndefined(selectLeaf)) ? true : selectLeaf; var pane = lxSelect.choicesViewSize === 'large' ? lxSelect.panes[parentIndex] : lxSelect.openedPanes[parentIndex]; if (angular.isUndefined(pane)) { return; } var key = indexOrKey; if (angular.isObject(pane) && angular.isNumber(indexOrKey)) { key = (Object.keys(pane) || [])[indexOrKey]; } if (angular.isDefined(toggledPanes[parentIndex])) { var previousKey = toggledPanes[parentIndex].key; _closePane(parentIndex); if (previousKey === key) { return; } } var isLeaf = lxSelect.isLeaf(pane[key]); if (isLeaf) { if (selectLeaf) { lxSelect.toggleChoice(pane[key], evt); } return; } _openPane(parentIndex, key, false); }
javascript
{ "resource": "" }
q24725
updateFilter
train
function updateFilter() { if (angular.isFunction(lxSelect.resetDropdownSize)) { lxSelect.resetDropdownSize(); } if (angular.isDefined(lxSelect.filter)) { lxSelect.matchingPaths = lxSelect.filter({ newValue: lxSelect.filterModel }); } else if (lxSelect.choicesViewMode === 'panes') { lxSelect.matchingPaths = lxSelect.searchPath(lxSelect.filterModel); _closePanes(); } if (lxSelect.autocomplete) { lxSelect.activeChoiceIndex = -1; if (lxSelect.filterModel) { LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid); } else { LxDropdownService.close('dropdown-' + lxSelect.uuid); } } if (lxSelect.choicesViewMode === 'panes' && angular.isDefined(lxSelect.matchingPaths) && lxSelect.matchingPaths.length > 0) { var longest = _getLongestMatchingPath(); if (!longest) { return; } var longestPath = longest.split('.'); if (longestPath.length === 0) { return; } angular.forEach(longestPath, function forEachPartOfTheLongestPath(part, index) { _openPane(index, part, index === (longestPath.length - 1)); }); } }
javascript
{ "resource": "" }
q24726
searchPath
train
function searchPath(newValue) { if (!newValue || newValue.length < 2) { return undefined; } var regexp = new RegExp(LxUtils.escapeRegexp(newValue), 'ig'); return _searchPath(lxSelect.choices, regexp); }
javascript
{ "resource": "" }
q24727
createEnterARButton
train
function createEnterARButton (clickHandler) { var arButton; // Create elements. arButton = document.createElement('button'); arButton.className = ENTER_AR_BTN_CLASS; arButton.setAttribute('title', 'Enter AR mode.'); arButton.setAttribute('aframe-injected', ''); arButton.addEventListener('click', function (evt) { document.getElementsByClassName(ENTER_AR_BTN_CLASS)[0].style.display = 'none'; document.getElementsByClassName(EXIT_AR_BTN_CLASS)[0].style.display = 'inline-block'; clickHandler(); }); return arButton; }
javascript
{ "resource": "" }
q24728
LocationLinks
train
function LocationLinks(props) { const elements = props.locations.map((location, index, locations) => { let buildingName; if (location.match(/\d+\s*$/i)) { buildingName = location.replace(/\d+\s*$/i, ''); } else { buildingName = location; } let optionalComma = null; if (index !== locations.length - 1) { optionalComma = ', '; } if (location.toUpperCase() === 'TBA' || location.toUpperCase() === 'LOCATION TBA') { if (locations.length > 1) { return null; } return location; } if (location.toUpperCase() === 'BOSTON DEPT') { return ( <span key='Boston DEPT'> TBA &nbsp;(Boston Campus) </span> ); } // The <a> tag needs to be on one line, or else react will insert spaces in the generated HTML. // And we only want spaces between these span elements, and not after the location and the comma. // eg YMCA, Hurting Hall and not YMCA , Hurting Hall return ( <span key={ location }> <a target='_blank' rel='noopener noreferrer' href={ `https://maps.google.com/?q=${macros.collegeName} ${buildingName}` }> {location} </a> {optionalComma} </span> ); }); return ( <span> {elements} </span> ); }
javascript
{ "resource": "" }
q24729
setCookie
train
function setCookie(pr_name, exdays) { var d = new Date(); d = (d.getTime() + (exdays*24*60*60*1000)); document.cookie = pr_name+"="+d + ";" + ";path=/"; }
javascript
{ "resource": "" }
q24730
getCookie
train
function getCookie(pr_name) { var name = pr_name + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; c = c.trim(); if (c.indexOf(pr_name+"=") === 0) { return c.substring(name.length, c.length); } } return ""; }
javascript
{ "resource": "" }
q24731
App
train
function App(options) { this.clientId = options.clientId; this.clientSecret = options.clientSecret || null; this.redirectUri = options.redirectUri || null; this.scope = options.scope || 'default'; this.asanaBaseUrl = options.asanaBaseUrl || 'https://app.asana.com/'; }
javascript
{ "resource": "" }
q24732
ChromeExtensionFlow
train
function ChromeExtensionFlow(options) { BaseBrowserFlow.call(this, options); this._authorizationPromise = null; this._receiverUrl = chrome.runtime.getURL( options.receiverPath || 'asana_oauth_receiver.html'); }
javascript
{ "resource": "" }
q24733
NativeFlow
train
function NativeFlow(options) { this.app = options.app; this.instructions = options.instructions || defaultInstructions; this.prompt = options.prompt || defaultPrompt; this.redirectUri = oauthUtil.NATIVE_REDIRECT_URI; }
javascript
{ "resource": "" }
q24734
Collection
train
function Collection(response, dispatcher, dispatchOptions) { if (!Collection.isCollectionResponse(response)) { throw new Error( 'Cannot create Collection from response that does not have resources'); } this.data = response.data; this._response = response; this._dispatcher = dispatcher; this._dispatchOptions = dispatchOptions; }
javascript
{ "resource": "" }
q24735
ResourceStream
train
function ResourceStream(collection) { var me = this; BufferedReadable.call(me, { objectMode: true }); // @type {Collection} The collection whose data was last pushed into the // stream, such that if we have to go back for more, we should fetch // its `nextPage`. me._collection = collection; // @type {boolean} True iff a request for more items is in flight. me._fetching = false; // Ensure the initial collection's data is in the stream. me._pushCollection(); }
javascript
{ "resource": "" }
q24736
OauthAuthenticator
train
function OauthAuthenticator(options) { Authenticator.call(this); if (typeof(options.credentials) === 'string') { this.credentials = { 'access_token': options.credentials }; } else { this.credentials = options.credentials || null; } this.flow = options.flow || null; this.app = options.app; }
javascript
{ "resource": "" }
q24737
Client
train
function Client(dispatcher, options) { options = options || {}; /** * The internal dispatcher. This is mostly used by the resources but provided * for custom requests to the API or API features that have not yet been added * to the client. * @type {Dispatcher} */ this.dispatcher = dispatcher; /** * An instance of the Attachments resource. * @type {Attachments} */ this.attachments = new resources.Attachments(this.dispatcher); /** * An instance of the CustomFieldSettings resource. * @type {CustomFieldSettings} */ this.customFieldSettings = new resources.CustomFieldSettings(this.dispatcher); /** * An instance of the CustomFields resource. * @type {CustomFields} */ this.customFields = new resources.CustomFields(this.dispatcher); /** * An instance of the Events resource. * @type {Events} */ this.events = new resources.Events(this.dispatcher); /** * An instance of the OrganizationExports resource. * @type {Events} */ this.organizationExports = new resources.OrganizationExports(this.dispatcher); /** * An instance of the Projects resource. * @type {Projects} */ this.projects = new resources.Projects(this.dispatcher); /** * An instance of the ProjectMemberships resource. * @type {ProjectMemberships} */ this.projectMemberships = new resources.ProjectMemberships(this.dispatcher); /** * An instance of the ProjectStatuses resource. * @type {ProjectStatuses} */ this.projectStatuses = new resources.ProjectStatuses(this.dispatcher); /** * An instance of the Sections resource. * @type {Sections} */ this.sections = new resources.Sections(this.dispatcher); /** * An instance of the Stories resource. * @type {Stories} */ this.stories = new resources.Stories(this.dispatcher); /** * An instance of the Tags resource. * @type {Tags} */ this.tags = new resources.Tags(this.dispatcher); /** * An instance of the Tasks resource. * @type {Tasks} */ this.tasks = new resources.Tasks(this.dispatcher); /** * An instance of the Teams resource. * @type {Teams} */ this.teams = new resources.Teams(this.dispatcher); /** * An instance of the Users resource. * @type {Users} */ this.users = new resources.Users(this.dispatcher); /** * An instance of the Workspaces resource. * @type {Workspaces} */ this.workspaces = new resources.Workspaces(this.dispatcher); /** * An instance of the Webhooks resource. * @type {Webhooks} */ this.webhooks = new resources.Webhooks(this.dispatcher); // Store off Oauth info. this.app = new App(options); }
javascript
{ "resource": "" }
q24738
browserTask
train
function browserTask(minify) { return function() { var task = browserify( { entries: [index], standalone: 'Asana' }) .bundle() .pipe(vinylSourceStream('asana' + (minify ? '-min' : '') + '.js')); if (minify) { task = task .pipe(vinylBuffer()) .pipe(uglify()); } return task.pipe(gulp.dest('dist')); }; }
javascript
{ "resource": "" }
q24739
autoDetect
train
function autoDetect(env) { env = env || defaultEnvironment(); if (typeof(env.chrome) !== 'undefined' && env.chrome.runtime && env.chrome.runtime.id) { if (env.chrome.tabs && env.chrome.tabs.create) { return ChromeExtensionFlow; } else { // Chrome packaged app, not supported yet. return null; } } if (typeof(env.window) !== 'undefined' && env.window.navigator) { // Browser return RedirectFlow; } if (typeof(env.process) !== 'undefined' && env.process.env) { // NodeJS script return NativeFlow; } return null; }
javascript
{ "resource": "" }
q24740
createClient
train
function createClient() { return Asana.Client.create({ clientId: clientId, clientSecret: clientSecret, redirectUri: 'http://localhost:' + port + '/oauth_callback' }); }
javascript
{ "resource": "" }
q24741
parseOauthResultFromUrl
train
function parseOauthResultFromUrl(currentUrl) { var oauthUrl = url.parse(currentUrl); return oauthUrl.hash ? querystring.parse(oauthUrl.hash.substr(1)) : null; }
javascript
{ "resource": "" }
q24742
removeOauthResultFromCurrentUrl
train
function removeOauthResultFromCurrentUrl() { if (window.history && window.history.replaceState) { var url = window.location.href; var hashIndex = url.indexOf('#'); window.history.replaceState({}, document.title, url.substring(0, hashIndex)); } else { window.location.hash = ''; } }
javascript
{ "resource": "" }
q24743
stringSource
train
function stringSource(s) { var i=0; return function() { return i < s.length ? s.charCodeAt(i++) : null; }; }
javascript
{ "resource": "" }
q24744
stringDestination
train
function stringDestination() { var cs = [], ps = []; return function() { if (arguments.length === 0) return ps.join('')+stringFromCharCode.apply(String, cs); if (cs.length + arguments.length > 1024) ps.push(stringFromCharCode.apply(String, cs)), cs.length = 0; Array.prototype.push.apply(cs, arguments); }; }
javascript
{ "resource": "" }
q24745
assertLong
train
function assertLong(value, unsigned) { if (typeof value === 'number') { return Long.fromNumber(value, unsigned); } else if (typeof value === 'string') { return Long.fromString(value, unsigned); } else if (value && value instanceof Long) { if (typeof unsigned !== 'undefined') { if (unsigned && !value.unsigned) return value.toUnsigned(); if (!unsigned && value.unsigned) return value.toSigned(); } return value; } else throw TypeError("Illegal value: "+value+" (not an integer or Long)"); }
javascript
{ "resource": "" }
q24746
assertOffset
train
function assertOffset(offset, min, cap, size) { if (typeof offset !== 'number' || offset % 1 !== 0) throw TypeError("Illegal offset: "+offset+" (not an integer)"); offset = offset | 0; if (offset < min || offset > cap-size) throw RangeError("Illegal offset: "+min+" <= "+value+" <= "+cap+"-"+size); return offset; }
javascript
{ "resource": "" }
q24747
assertRange
train
function assertRange(begin, end, min, cap) { if (typeof begin !== 'number' || begin % 1 !== 0) throw TypeError("Illegal begin: "+begin+" (not a number)"); begin = begin | 0; if (typeof end !== 'number' || end % 1 !== 0) throw TypeError("Illegal end: "+range[1]+" (not a number)"); end = end | 0; if (begin < min || begin > end || end > cap) throw RangeError("Illegal range: "+min+" <= "+begin+" <= "+end+" <= "+cap); rangeVal[0] = begin; rangeVal[1] = end; }
javascript
{ "resource": "" }
q24748
train
function(controller) { /** * Plugin controller. */ this.controller = controller; /** * IMA SDK AdDisplayContainer. */ this.adDisplayContainer = null; /** * True if the AdDisplayContainer has been initialized. False otherwise. */ this.adDisplayContainerInitialized = false; /** * IMA SDK AdsLoader */ this.adsLoader = null; /** * IMA SDK AdsManager */ this.adsManager = null; /** * IMA SDK AdsRenderingSettings. */ this.adsRenderingSettings = null; /** * VAST, VMAP, or ad rules response. Used in lieu of fetching a response * from an ad tag URL. */ this.adsResponse = null; /** * Current IMA SDK Ad. */ this.currentAd = null; /** * Timer used to track ad progress. */ this.adTrackingTimer = null; /** * True if ALL_ADS_COMPLETED has fired, false until then. */ this.allAdsCompleted = false; /** * True if ads are currently displayed, false otherwise. * True regardless of ad pause state if an ad is currently being displayed. */ this.adsActive = false; /** * True if ad is currently playing, false if ad is paused or ads are not * currently displayed. */ this.adPlaying = false; /** * True if the ad is muted, false otherwise. */ this.adMuted = false; /** * Listener to be called to trigger manual ad break playback. */ this.adBreakReadyListener = undefined; /** * Tracks whether or not we have already called adsLoader.contentComplete(). */ this.contentCompleteCalled = false; /** * Stores the dimensions for the ads manager. */ this.adsManagerDimensions = { width: 0, height: 0, }; /** * Boolean flag to enable manual ad break playback. */ this.autoPlayAdBreaks = true; if (this.controller.getSettings().autoPlayAdBreaks === false) { this.autoPlayAdBreaks = false; } // Set SDK settings from plugin settings. if (this.controller.getSettings().locale) { /* eslint no-undef: 'error' */ /* global google */ google.ima.settings.setLocale(this.controller.getSettings().locale); } if (this.controller.getSettings().disableFlashAds) { google.ima.settings.setDisableFlashAds( this.controller.getSettings().disableFlashAds); } if (this.controller.getSettings().disableCustomPlaybackForIOS10Plus) { google.ima.settings.setDisableCustomPlaybackForIOS10Plus( this.controller.getSettings().disableCustomPlaybackForIOS10Plus); } }
javascript
{ "resource": "" }
q24749
train
function(player, options) { /** * Stores user-provided settings. * @type {Object} */ this.settings = {}; /** * Content and ads ended listeners passed by the publisher to the plugin. * These will be called when the plugin detects that content *and all * ads* have completed. This differs from the contentEndedListeners in that * contentEndedListeners will fire between content ending and a post-roll * playing, whereas the contentAndAdsEndedListeners will fire after the * post-roll completes. */ this.contentAndAdsEndedListeners = []; /** * Whether or not we are running on a mobile platform. */ this.isMobile = (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)); /** * Whether or not we are running on an iOS platform. */ this.isIos = (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)); this.initWithSettings(options); /** * Stores contrib-ads default settings. */ const contribAdsDefaults = { debug: this.settings.debug, timeout: this.settings.timeout, prerollTimeout: this.settings.prerollTimeout, }; const adsPluginSettings = this.extend( {}, contribAdsDefaults, options.contribAdsSettings || {}); this.playerWrapper = new PlayerWrapper(player, adsPluginSettings, this); this.adUi = new AdUi(this); this.sdkImpl = new SdkImpl(this); }
javascript
{ "resource": "" }
q24750
train
function (geofences, success, error) { if (!Array.isArray(geofences)) { geofences = [geofences]; } geofences.forEach(coerceProperties); if (isIOS) { return addOrUpdateIOS(geofences, success, error); } return execPromise(success, error, "GeofencePlugin", "addOrUpdate", geofences); }
javascript
{ "resource": "" }
q24751
train
function (ids, success, error) { if (!Array.isArray(ids)) { ids = [ids]; } return execPromise(success, error, "GeofencePlugin", "remove", ids); }
javascript
{ "resource": "" }
q24752
newClientStub
train
function newClientStub() { // First create the appropriate TLS certs with dgraph cert: // $ dgraph cert // $ dgraph cert -n localhost // $ dgraph cert -c user const rootCaCert = fs.readFileSync(path.join(__dirname, 'tls', 'ca.crt')); const clientCertKey = fs.readFileSync(path.join(__dirname, 'tls', 'client.user.key')); const clientCert = fs.readFileSync(path.join(__dirname, 'tls', 'client.user.crt')); return new dgraph.DgraphClientStub( "localhost:9080", grpc.credentials.createSsl(rootCaCert, clientCertKey, clientCert)); }
javascript
{ "resource": "" }
q24753
dropAll
train
async function dropAll(dgraphClient) { const op = new dgraph.Operation(); op.setDropAll(true); await dgraphClient.alter(op); }
javascript
{ "resource": "" }
q24754
createData
train
async function createData(dgraphClient) { // Create a new transaction. const txn = dgraphClient.newTxn(); try { // Create data. const p = { name: "Alice", age: 26, married: true, loc: { type: "Point", coordinates: [1.1, 2], }, dob: new Date(1980, 1, 1, 23, 0, 0, 0), friend: [ { name: "Bob", age: 24, }, { name: "Charlie", age: 29, } ], school: [ { name: "Crown Public School", } ] }; // Run mutation. const mu = new dgraph.Mutation(); mu.setSetJson(p); const assigned = await txn.mutate(mu); // Commit transaction. await txn.commit(); // Get uid of the outermost object (person named "Alice"). // Assigned#getUidsMap() returns a map from blank node names to uids. // For a json mutation, blank node names "blank-0", "blank-1", ... are used // for all the created nodes. console.log(`Created person named "Alice" with uid = ${assigned.getUidsMap().get("blank-0")}\n`); console.log("All created nodes (map from blank node names to uids):"); assigned.getUidsMap().forEach((uid, key) => console.log(`${key} => ${uid}`)); console.log(); } finally { // Clean up. Calling this after txn.commit() is a no-op // and hence safe. await txn.discard(); } }
javascript
{ "resource": "" }
q24755
yyyymmddDateFromMonthDayYearDate
train
function yyyymmddDateFromMonthDayYearDate(monthDayYearDate) { var yyyy = monthDayYearDate.split(',')[1].trim(); var dd = monthDayYearDate.split(' ')[1].split(',')[0]; var mm = ''; switch (monthDayYearDate.split(' ')[0]) { case 'January': mm = '01'; break; case 'February': mm = '02'; break; case 'March': mm = '03'; break; case 'April': mm = '04'; break; case 'May': mm = '05'; break; case 'June': mm = '06'; break; case 'July': mm = '07'; break; case 'August': mm = '08'; break; case 'September': mm = '09'; break; case 'October': mm = '10'; break; case 'November': mm = '11'; break; case 'December': mm = '12'; break; } return yyyy + '-' + mm + '-' + dd; }
javascript
{ "resource": "" }
q24756
getTitleFromChartItem
train
function getTitleFromChartItem(chartItem) { var title; try { title = chartItem.children[1].children[5].children[1].children[1].children[1].children[0].data.replace(/\n/g, ''); } catch (e) { title = ''; } return title; }
javascript
{ "resource": "" }
q24757
getArtistFromChartItem
train
function getArtistFromChartItem(chartItem) { var artist; try { artist = chartItem.children[1].children[5].children[1].children[3].children[0].data.replace(/\n/g, ''); } catch (e) { artist = ''; } if (artist.trim().length < 1) { try { artist = chartItem.children[1].children[5].children[1].children[3].children[1].children[0].data.replace(/\n/g, ''); } catch (e) { artist = ''; } } return artist; }
javascript
{ "resource": "" }
q24758
getPositionLastWeekFromChartItem
train
function getPositionLastWeekFromChartItem(chartItem) { var positionLastWeek; try { if (chartItem.children[3].children.length > 5) { positionLastWeek = chartItem.children[3].children[5].children[3].children[3].children[0].data } else { positionLastWeek = chartItem.children[3].children[3].children[1].children[3].children[0].data; } } catch (e) { positionLastWeek = ''; } return parseInt(positionLastWeek); }
javascript
{ "resource": "" }
q24759
getPeakPositionFromChartItem
train
function getPeakPositionFromChartItem(chartItem) { var peakPosition; try { if (chartItem.children[3].children.length > 5) { peakPosition = chartItem.children[3].children[5].children[5].children[3].children[0].data; } else { peakPosition = chartItem.children[3].children[3].children[3].children[3].children[0].data; } } catch (e) { peakPosition = chartItem.attribs['data-rank']; } return parseInt(peakPosition); }
javascript
{ "resource": "" }
q24760
getWeeksOnChartFromChartItem
train
function getWeeksOnChartFromChartItem(chartItem) { var weeksOnChart; try { if (chartItem.children[3].children.length > 5) { weeksOnChart = chartItem.children[3].children[5].children[7].children[3].children[0].data; } else { weeksOnChart = chartItem.children[3].children[3].children[5].children[3].children[0].data; } } catch (e) { weeksOnChart = '1'; } return parseInt(weeksOnChart); }
javascript
{ "resource": "" }
q24761
getNeighboringChart
train
function getNeighboringChart(chartItem, neighboringWeek) { if (neighboringWeek == NeighboringWeek.Previous) { if (chartItem[0].attribs.class.indexOf('dropdown__date-selector-option--disabled') == -1) { return { url: BILLBOARD_BASE_URL + chartItem[0].children[1].attribs.href, date: chartItem[0].children[1].attribs.href.split('/')[3] }; } } else { if (chartItem[1].attribs.class.indexOf('dropdown__date-selector-option--disabled') == -1) { return { url: BILLBOARD_BASE_URL + chartItem[1].children[1].attribs.href, date: chartItem[1].children[1].attribs.href.split('/')[3] }; } } return { url: '', date: '' } }
javascript
{ "resource": "" }
q24762
getChart
train
function getChart(chartName, date, cb) { // check if chart was specified if (typeof chartName === 'function') { // if chartName not specified, default to hot-100 chart for current week, // and set callback method accordingly cb = chartName; chartName = 'hot-100'; date = ''; } // check if date was specified if (typeof date === 'function') { // if date not specified, default to specified chart for current week, // and set callback method accordingly cb = date; date = ''; } var chart = {}; /** * A song * @typedef {Object} Song * @property {string} title - The title of the song * @property {string} artist - The song's artist */ /** * Array of songs */ chart.songs = []; // build request URL string for specified chart and date var requestURL = BILLBOARD_CHARTS_URL + chartName + '/' + date; request(requestURL, function completedRequest(error, response, html) { if (error) { cb(error, null); return; } var $ = cheerio.load(html); // get chart week chart.week = yyyymmddDateFromMonthDayYearDate($('.chart-detail-header__date-selector-button')[0].children[0].data.replace(/\n/g, '')); // get previous and next charts chart.previousWeek = getNeighboringChart($('.dropdown__date-selector-option '), NeighboringWeek.Previous); chart.nextWeek = getNeighboringChart($('.dropdown__date-selector-option '), NeighboringWeek.Next); // push remaining ranked songs into chart.songs array $('.chart-list-item').each(function(index, item) { var rank = index + 1; chart.songs.push({ "rank": rank, "title": getTitleFromChartItem(item), "artist": getArtistFromChartItem(item), "cover": getCoverFromChartItem(item, rank), "position" : { "positionLastWeek": getPositionLastWeekFromChartItem(item), "peakPosition": getPeakPositionFromChartItem(item), "weeksOnChart": getWeeksOnChartFromChartItem(item) } }); }); // callback with chart if chart.songs array was populated if (chart.songs.length > 1){ cb(null, chart); return; } else { cb("Songs not found.", null); return; } }); }
javascript
{ "resource": "" }
q24763
listCharts
train
function listCharts(cb) { if (typeof cb !== 'function') { cb('Specified callback is not a function.', null); return; } request(BILLBOARD_CHARTS_URL, function completedRequest(error, response, html) { if (error) { cb(error, null); return; } var $ = cheerio.load(html); /** * A chart * @typedef {Object} Chart * @property {string} name - The name of the chart * @property {string} url - The url of the chat */ /** * Array of charts */ var charts = []; // push charts into charts array $('.chart-panel__link').each(function(index, item) { var chart = {}; chart.name = toTitleCase($(this)[0].attribs.href.replace('/charts/', '').replace(/-/g, ' ')); chart.url = "https://www.billboard.com" + $(this)[0].attribs.href; charts.push(chart); }); // callback with charts if charts array was populated if (charts.length > 0){ cb(null, charts); return; } else { cb("No charts found.", null); return; } }); }
javascript
{ "resource": "" }
q24764
WooCommerceAPI
train
function WooCommerceAPI(opt) { if (!(this instanceof WooCommerceAPI)) { return new WooCommerceAPI(opt); } opt = opt || {}; if (!(opt.url)) { throw new Error('url is required'); } if (!(opt.consumerKey)) { throw new Error('consumerKey is required'); } if (!(opt.consumerSecret)) { throw new Error('consumerSecret is required'); } this.classVersion = '1.4.2'; this._setDefaultsOptions(opt); }
javascript
{ "resource": "" }
q24765
resolveExternalPath
train
function resolveExternalPath(importPath, options) { let baseIndex = importPath[0] === '@' ? importPath.indexOf('/') + 1 : 0; let addonName = importPath.substring(0, importPath.indexOf('/', baseIndex)); let addon = options.parent.addons.find(addon => addon.name === addonName); if (!addon) { throw new Error(`Unable to resolve styles from addon ${addonName}; is it installed?`); } let pathWithinAddon = importPath.substring(addonName.length + 1); let addonTreePath = path.join(addon.root, addon.treePaths.addon); let absolutePath = ensurePosixPath(path.resolve(addonTreePath, pathWithinAddon)); let keyPath = options.addonModulesRoot + addonName + '/' + pathWithinAddon; return new DependencyPath('external', absolutePath, keyPath); }
javascript
{ "resource": "" }
q24766
isStage1ClassDescriptor
train
function isStage1ClassDescriptor(possibleDesc) { let [target] = possibleDesc; return ( possibleDesc.length === 1 && typeof target === 'function' && 'prototype' in target && !target.__isComputedDecorator ); }
javascript
{ "resource": "" }
q24767
train
function() { this.inner.setAttribute('tabindex', 0); this.inner.addEventListener('keyup', (e) => { if (e.target !== this.inner) { return; } switch(e.keyCode) { case 13: this.mediator.trigger("block:create", 'Text', null, this.el, { autoFocus: true }); break; case 8: this.onDeleteClick.call(this, new CustomEvent('click')); return; } }); }
javascript
{ "resource": "" }
q24768
train
function(){ var dataObj = {}; var content = this.getTextBlock().html(); if (content.length > 0) { dataObj.text = SirTrevor.toMarkdown(content, this.type); } this.setData(dataObj); }
javascript
{ "resource": "" }
q24769
removeWrappingParagraphForFirefox
train
function removeWrappingParagraphForFirefox(value) { var fakeContent = document.createElement('div'); fakeContent.innerHTML = value; if (fakeContent.childNodes.length === 1) { var node = [].slice.call(fakeContent.childNodes)[0]; if (node && node.nodeName === "P") { value = node.innerHTML; } } return value; }
javascript
{ "resource": "" }
q24770
eachObj
train
function eachObj(obj, iteratee, context) { for (var key in obj) { if (obj.hasOwnProperty(key)) { iteratee.call(context || obj, key, obj[key]); } } }
javascript
{ "resource": "" }
q24771
jsxTagName
train
function jsxTagName(tagName) { var name = tagName.toLowerCase(); if (ELEMENT_TAG_NAME_MAPPING.hasOwnProperty(name)) { name = ELEMENT_TAG_NAME_MAPPING[name]; } return name; }
javascript
{ "resource": "" }
q24772
trimEnd
train
function trimEnd(haystack, needle) { return endsWith(haystack, needle) ? haystack.slice(0, -needle.length) : haystack; }
javascript
{ "resource": "" }
q24773
isNumeric
train
function isNumeric(input) { return input !== undefined && input !== null && (typeof input === 'number' || parseInt(input, 10) == input); }
javascript
{ "resource": "" }
q24774
train
function (html) { this.reset(); var containerEl = createElement('div'); containerEl.innerHTML = '\n' + this._cleanInput(html) + '\n'; if (this.config.createClass) { if (this.config.outputClassName) { this.output = 'var ' + this.config.outputClassName + ' = React.createClass({\n'; } else { this.output = 'React.createClass({\n'; } this.output += this.config.indent + 'render: function() {' + "\n"; this.output += this.config.indent + this.config.indent + 'return (\n'; } if (this._onlyOneTopLevel(containerEl)) { // Only one top-level element, the component can return it directly // No need to actually visit the container element this._traverse(containerEl); } else { // More than one top-level element, need to wrap the whole thing in a // container. this.output += this.config.indent + this.config.indent + this.config.indent; this.level++; this._visit(containerEl); } this.output = this.output.trim() + '\n'; if (this.config.createClass) { this.output += this.config.indent + this.config.indent + ');\n'; this.output += this.config.indent + '}\n'; this.output += '});'; } else { this.output = this._removeJSXClassIndention(this.output, this.config.indent); } return this.output; }
javascript
{ "resource": "" }
q24775
train
function (containerEl) { // Only a single child element if ( containerEl.childNodes.length === 1 && containerEl.childNodes[0].nodeType === NODE_TYPE.ELEMENT ) { return true; } // Only one element, and all other children are whitespace var foundElement = false; for (var i = 0, count = containerEl.childNodes.length; i < count; i++) { var child = containerEl.childNodes[i]; if (child.nodeType === NODE_TYPE.ELEMENT) { if (foundElement) { // Encountered an element after already encountering another one // Therefore, more than one element at root level return false; } else { foundElement = true; } } else if (child.nodeType === NODE_TYPE.TEXT && !isEmpty(child.textContent)) { // Contains text content return false; } } return true; }
javascript
{ "resource": "" }
q24776
train
function (node) { this.level++; for (var i = 0, count = node.childNodes.length; i < count; i++) { this._visit(node.childNodes[i]); } this.level--; }
javascript
{ "resource": "" }
q24777
train
function (node) { switch (node.nodeType) { case NODE_TYPE.ELEMENT: this._beginVisitElement(node); break; case NODE_TYPE.TEXT: this._visitText(node); break; case NODE_TYPE.COMMENT: this._visitComment(node); break; default: console.warn('Unrecognised node type: ' + node.nodeType); } }
javascript
{ "resource": "" }
q24778
train
function (node) { switch (node.nodeType) { case NODE_TYPE.ELEMENT: this._endVisitElement(node); break; // No ending tags required for these types case NODE_TYPE.TEXT: case NODE_TYPE.COMMENT: break; } }
javascript
{ "resource": "" }
q24779
train
function (node) { var tagName = jsxTagName(node.tagName); var attributes = []; for (var i = 0, count = node.attributes.length; i < count; i++) { attributes.push(this._getElementAttribute(node, node.attributes[i])); } if (tagName === 'textarea') { // Hax: textareas need their inner text moved to a "defaultValue" attribute. attributes.push('defaultValue={' + JSON.stringify(node.value) + '}'); } if (tagName === 'style') { // Hax: style tag contents need to be dangerously set due to liberal curly brace usage attributes.push('dangerouslySetInnerHTML={{__html: ' + JSON.stringify(node.textContent) + ' }}'); } if (tagName === 'pre') { this._inPreTag = true; } this.output += '<' + tagName; if (attributes.length > 0) { this.output += ' ' + attributes.join(' '); } if (!this._isSelfClosing(node)) { this.output += '>'; } }
javascript
{ "resource": "" }
q24780
train
function (node) { var tagName = jsxTagName(node.tagName); // De-indent a bit // TODO: It's inefficient to do it this way :/ this.output = trimEnd(this.output, this.config.indent); if (this._isSelfClosing(node)) { this.output += ' />'; } else { this.output += '</' + tagName + '>'; } if (tagName === 'pre') { this._inPreTag = false; } }
javascript
{ "resource": "" }
q24781
train
function (node) { var parentTag = node.parentNode && jsxTagName(node.parentNode.tagName); if (parentTag === 'textarea' || parentTag === 'style') { // Ignore text content of textareas and styles, as it will have already been moved // to a "defaultValue" attribute and "dangerouslySetInnerHTML" attribute respectively. return; } var text = escapeSpecialChars(node.textContent); if (this._inPreTag) { // If this text is contained within a <pre>, we need to ensure the JSX // whitespace coalescing rules don't eat the whitespace. This means // wrapping newlines and sequences of two or more spaces in variables. text = text .replace(/\r/g, '') .replace(/( {2,}|\n|\t|\{|\})/g, function (whitespace) { return '{' + JSON.stringify(whitespace) + '}'; }); } else { // Handle any curly braces. text = text .replace(/(\{|\})/g, function (brace) { return '{\'' + brace + '\'}'; }); // If there's a newline in the text, adjust the indent level if (text.indexOf('\n') > -1) { text = text.replace(/\n\s*/g, this._getIndentedNewline()); } } this.output += text; }
javascript
{ "resource": "" }
q24782
train
function (node, attribute) { switch (attribute.name) { case 'style': return this._getStyleAttribute(attribute.value); default: var tagName = jsxTagName(node.tagName); var name = (ELEMENT_ATTRIBUTE_MAPPING[tagName] && ELEMENT_ATTRIBUTE_MAPPING[tagName][attribute.name]) || ATTRIBUTE_MAPPING[attribute.name] || attribute.name; var result = name; // Numeric values should be output as {123} not "123" if (isNumeric(attribute.value)) { result += '={' + attribute.value + '}'; } else if (attribute.value.length > 0) { result += '="' + attribute.value.replace(/"/gm, '&quot;') + '"'; } return result; } }
javascript
{ "resource": "" }
q24783
train
function (output, indent) { var classIndention = new RegExp('\\n' + indent + indent + indent, 'g'); return output.replace(classIndention, '\n'); }
javascript
{ "resource": "" }
q24784
train
function (rawStyle) { this.styles = {}; rawStyle.split(';').forEach(function (style) { style = style.trim(); var firstColon = style.indexOf(':'); var key = style.substr(0, firstColon); var value = style.substr(firstColon + 1).trim(); if (key !== '') { // Style key should be case insensitive key = key.toLowerCase(); this.styles[key] = value; } }, this); }
javascript
{ "resource": "" }
q24785
train
function () { var output = []; eachObj(this.styles, function (key, value) { output.push(this.toJSXKey(key) + ': ' + this.toJSXValue(value)); }, this); return output.join(', '); }
javascript
{ "resource": "" }
q24786
train
function (value) { if (isNumeric(value)) { return value } else if (value.startsWith("'") || value.startsWith("\"")) { return value } else { return '\'' + value.replace(/'/g, '"') + '\''; } }
javascript
{ "resource": "" }
q24787
imageToImageData
train
function imageToImageData ( image ) { if ( image instanceof HTMLImageElement ) { // http://stackoverflow.com/a/3016076/229189 if ( ! image.naturalWidth || ! image.naturalHeight || image.complete === false ) { throw new Error( "This this image hasn't finished loading: " + image.src ); } const canvas = new Canvas( image.naturalWidth, image.naturalHeight ); const ctx = canvas.getContext( '2d' ); ctx.drawImage( image, 0, 0, canvas.width, canvas.height ); const imageData = ctx.getImageData( 0, 0, canvas.width, canvas.height ); if ( imageData.data && imageData.data.length ) { if ( typeof imageData.width === 'undefined' ) { imageData.width = image.naturalWidth; } if ( typeof imageData.height === 'undefined' ) { imageData.height = image.naturalHeight; } } return imageData; } else { throw new Error( 'This object does not seem to be an image.' ); return; } }
javascript
{ "resource": "" }
q24788
transferAnnotations
train
function transferAnnotations (doc, path, offset, newPath, newOffset) { var index = doc.getIndex('annotations') var annotations = index.get(path, offset) for (let i = 0; i < annotations.length; i++) { let a = annotations[i] var isInside = (offset > a.start.offset && offset < a.end.offset) var start = a.start.offset var end = a.end.offset // 1. if the cursor is inside an annotation it gets either split or truncated if (isInside) { // create a new annotation if the annotation is splittable if (a.canSplit()) { let newAnno = a.toJSON() newAnno.id = uuid(a.type + '_') newAnno.start.path = newPath newAnno.start.offset = newOffset newAnno.end.path = newPath newAnno.end.offset = newOffset + a.end.offset - offset doc.create(newAnno) } // in either cases truncate the first part let newStartOffset = a.start.offset let newEndOffset = offset // if after truncate the anno is empty, delete it if (newEndOffset === newStartOffset) { doc.delete(a.id) // ... otherwise update the range } else { // TODO: Use coordintate ops! if (newStartOffset !== start) { doc.set([a.id, 'start', 'offset'], newStartOffset) } if (newEndOffset !== end) { doc.set([a.id, 'end', 'offset'], newEndOffset) } } // 2. if the cursor is before an annotation then simply transfer the annotation to the new node } else if (a.start.offset >= offset) { // TODO: Use coordintate ops! // Note: we are preserving the annotation so that anything which is connected to the annotation // remains valid. doc.set([a.id, 'start', 'path'], newPath) doc.set([a.id, 'start', 'offset'], newOffset + a.start.offset - offset) doc.set([a.id, 'end', 'path'], newPath) doc.set([a.id, 'end', 'offset'], newOffset + a.end.offset - offset) } } // TODO: fix support for container annotations // // same for container annotation anchors // index = doc.getIndex('container-annotation-anchors'); // var anchors = index.get(path); // var containerAnnoIds = []; // forEach(anchors, function(anchor) { // containerAnnoIds.push(anchor.id); // var start = anchor.offset; // if (offset <= start) { // // TODO: Use coordintate ops! // let coor = anchor.isStart?'start':'end' // doc.set([anchor.id, coor, 'path'], newPath); // doc.set([anchor.id, coor, 'offset'], newOffset + anchor.offset - offset); // } // }); // // check all anchors after that if they have collapsed and remove the annotation in that case // forEach(uniq(containerAnnoIds), function(id) { // var anno = doc.get(id); // var annoSel = anno.getSelection(); // if(annoSel.isCollapsed()) { // // console.log("...deleting container annotation because it has collapsed" + id); // doc.delete(id); // } // }); }
javascript
{ "resource": "" }
q24789
_disconnect
train
function _disconnect (context) { /* eslint-disable no-invalid-this */ // Remove all connections to the context forEach(this.__events__, (bindings, event) => { for (let i = bindings.length - 1; i >= 0; i--) { // bindings[i] may have been removed by the previous steps // so check it still exists if (bindings[i] && bindings[i].context === context) { _off.call(this, event, bindings[i].method, context) } } }) return this /* eslint-enable no-invalid-this */ }
javascript
{ "resource": "" }
q24790
_create
train
function _create (state, vel) { let comp = vel._comp console.assert(!comp, 'Component instance should not exist when this method is used.') let parent = vel.parent._comp // making sure the parent components have been instantiated if (!parent) { parent = _create(state, vel.parent) } // TODO: probably we should do something with forwarded/forwarding components here? if (vel._isVirtualComponent) { console.assert(parent, 'A Component should have a parent.') comp = state.componentFactory.createComponent(vel.ComponentClass, parent, vel.props) // HACK: making sure that we have the right props // TODO: instead of HACK add an assertion, and make otherwise sure that vel.props is set correctly vel.props = comp.props if (vel._forwardedEl) { let forwardedEl = vel._forwardedEl let forwardedComp = state.componentFactory.createComponent(forwardedEl.ComponentClass, comp, forwardedEl.props) // HACK same as before forwardedEl.props = forwardedComp.props comp._forwardedComp = forwardedComp } } else if (vel._isVirtualHTMLElement) { comp = state.componentFactory.createElementComponent(parent, vel) } else if (vel._isVirtualTextNode) { comp = state.componentFactory.createTextNodeComponent(parent, vel) } if (vel._ref) { comp._ref = vel._ref } if (vel._owner) { comp._owner = vel._owner._comp } vel._comp = comp return comp }
javascript
{ "resource": "" }
q24791
compressPubKey
train
function compressPubKey (pubKey) { const x = pubKey.substring(2, 66) const y = pubKey.substring(66, 130) const even = parseInt(y.substring(62, 64), 16) % 2 === 0 const prefix = even ? '02' : '03' return prefix + x }
javascript
{ "resource": "" }
q24792
pubKeyToAddress
train
function pubKeyToAddress (pubKey, network, type) { pubKey = ensureBuffer(pubKey) const pubKeyHash = hash160(pubKey) const addr = pubKeyHashToAddress(pubKeyHash, network, type) return addr }
javascript
{ "resource": "" }
q24793
pubKeyHashToAddress
train
function pubKeyHashToAddress (pubKeyHash, network, type) { pubKeyHash = ensureBuffer(pubKeyHash) const prefixHash = Buffer.concat([Buffer.from(networks[network][type], 'hex'), pubKeyHash]) const checksum = Buffer.from(sha256(sha256(prefixHash)).slice(0, 8), 'hex') const addr = base58.encode(Buffer.concat([prefixHash, checksum]).slice(0, 25)) return addr }
javascript
{ "resource": "" }
q24794
getAddressNetwork
train
function getAddressNetwork (address) { const prefix = base58.decode(address).toString('hex').substring(0, 2).toUpperCase() const networkKey = findKey(networks, network => [network.pubKeyHash, network.scriptHash].includes(prefix)) return networks[networkKey] }
javascript
{ "resource": "" }
q24795
ensureBuffer
train
function ensureBuffer (message) { if (Buffer.isBuffer(message)) return message switch (typeof message) { case 'string': message = isHex(message) ? Buffer.from(message, 'hex') : Buffer.from(message) break case 'object': message = Buffer.from(JSON.stringify(message)) break } return Buffer.isBuffer(message) ? message : false }
javascript
{ "resource": "" }
q24796
padHexStart
train
function padHexStart (hex, length) { let len = length || hex.length len += len % 2 return hex.padStart(len, '0') }
javascript
{ "resource": "" }
q24797
runApp
train
function runApp (appDir, appName) { var binPath = path.join(appDir, 'Contents', 'MacOS', appName); events.emit('log', 'Starting: ' + binPath); return spawn(binPath); }
javascript
{ "resource": "" }
q24798
isReactClass
train
function isReactClass (node) { if (!node || !t.isCallExpression(node)) return false // not _createClass call if (!node.callee || node.callee.name !== '_createClass') return false // no call arguments const args = node.arguments if (!args || args.length !== 2) return false if (!t.isIdentifier(args[0])) return false if (!t.isArrayExpression(args[1])) return false // no render method if (!args[1].elements || !args[1].elements.some((el) => { return isRenderMethod(el.properties) })) return false return true }
javascript
{ "resource": "" }
q24799
isRenderMethod
train
function isRenderMethod (props) { return props.some((prop) => { return prop.key.name === 'key' && prop.value.value === 'render' }) && props.some((prop) => { return prop.key.name === 'value' && t.isFunctionExpression(prop.value) }) }
javascript
{ "resource": "" }