_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q35000
unsubscribe
train
function unsubscribe (state, tokens, suspend) { tokens = typeof tokens === 'string' ? tokens.split(/,\s*/) : tokens; tokens = !tokens.length ? [tokens] : tokens; var result = curryMap( {topics: state._topics, suspend: suspend}, removeSubscriber, tokens ); return result.length === 1 ? result[0] : result; }
javascript
{ "resource": "" }
q35001
resubscribe
train
function resubscribe (state, tokens) { tokens = typeof tokens === 'string' ? tokens.split(/,\s*/) : tokens; tokens = !tokens.length ? [tokens] : tokens; var result = curryMap(state._topics, unsuspendSubscriber, tokens); return result.length === 1 ? result[0] : result; }
javascript
{ "resource": "" }
q35002
create
train
function create () { /** * Arbiter has a few options to affect the way that subscribers are * notified and PublicationPromises are resolved. * * @typedef Options * @memberof Arbiter * * @property {boolean} persist=false When true, subscribers are notified * of past messages. * @property {boolean} sync=false When true, invokes the subscription * functions synchronously. * @property {boolean} preventBubble=false When true, only the topics * that match the published topics exactly are invoked. * @property {number} latch=0.9999999999999999 When this number is less * than one, it is the ratio of subscribers that must fulfilled before * resolving the `PublicationPromise`. If greater or equal to one, * then it is a count of the subscribers that must fulfill. * @property {boolean} settlementLatch=false Changes the resolving logic * of `PublicationPromise` to be based off resolved rather than * fulfilled promises. This means that failed subscribers will count * toward the tally of latch. * @property {number} semaphor=Infinity The maximum number of subscribers * to allowed to be pending at any given point in time. * @property {boolean} updateAfterSettlement=false If true, updates the * `PublicationPromise` after it resolves. * * @example * * Arbiter.subscribe('a', log); * Arbiter.subscribe('a.b', log); * Arbiter.subscribe('a.b.c', log); * var promise = Arbiter.publish('a.b.c', {latch: 1}); * * // Remeber publish is async by default? * // promise.pending === 3; * // promise.fulfilled === 0; * // promise.rejected === 0; */ var topics = createNode(''), options = { persist: false, sync: false, preventBubble: false, latch: 0.9999999999999999, settlementLatch: false, semaphor: Infinity, updateAfterSettlement: false }, arbiter = { _topics: topics, options: options, version: 'v1.0.0', id: mkGenerator(), create: create }; arbiter.subscribe = partial1(subscribeDispatcher, arbiter); arbiter.publish = partial1(publish, arbiter); arbiter.unsubscribe = partial1(unsubscribe, arbiter); arbiter.resubscribe = partial1(resubscribe, arbiter); arbiter.removePersisted = partial1(removePersistedDispatcher, arbiter); return arbiter; }
javascript
{ "resource": "" }
q35003
hierarchicalTopicDispatcher
train
function hierarchicalTopicDispatcher (state, topic, data, options) { var lineage = findLineage(getTopic, isAncestorTopic, topic, state._topics), topicNode = lineage[lineage.length - 1], subscriptions = options.preventBubble ? topicNode.topic === topic ? topicNode.subscriptions : [] : mergeBy(getFingerArrayPriority, map(getSubscriptions, lineage)), fulfilledPromise = subscriptionDispatcher( topic, data, options, subscriptions ); if (options.persist) { var id = state.id(); topicNode = addTopicLine(topic, topicNode); topicNode.persisted.push( {topic: topic, data: data, order: id} ); fulfilledPromise.token = { topic: topic, id: id }; } return fulfilledPromise; }
javascript
{ "resource": "" }
q35004
resumeSubscriptionDispatcher
train
function resumeSubscriptionDispatcher ( topic, data, options, subscriptions, resolver, fulfill, reject ) { var promise = resolver.promise, subscription; for ( ; resolver.i >= 0 && promise.pending < options.semaphor; resolver.i -= 1 ) { subscription = subscriptions[resolver.i]; if (!subscription.suspended) { promise.pending += 1; subscriptionInvoker(subscription, data, topic).then(fulfill, reject); } } }
javascript
{ "resource": "" }
q35005
removePersistedDispatcher
train
function removePersistedDispatcher (state, tokens) { tokens = tokens && tokens.token || tokens || ''; tokens = typeof tokens === 'string' ? tokens.split(/,\s*/) : tokens; tokens = !tokens.length ? [tokens] : tokens; var result = curryMap(state._topics, removePersisted, tokens); return result.length === 1 ? result[0] : result; }
javascript
{ "resource": "" }
q35006
subscriptionDispatcher
train
function subscriptionDispatcher (topic, data, options, subscriptions) { var resolver = createResolver(), fulfill = resolveUse('fulfilledValues', 'fulfilled', options, resolver), reject = resolveUse('rejectedValues', 'rejected', options, resolver); resolver.i = subscriptions.length - 1; resolver.resume = { topic: topic, data: data, subscriptions: subscriptions, fulfill: fulfill, reject: reject }; resumeSubscriptionDispatcher( topic, data, options, subscriptions, resolver, fulfill, reject ); evaluateLatch(resolver, options); return resolver.promise; }
javascript
{ "resource": "" }
q35007
resolveUse
train
function resolveUse (appendList, increment, options, resolver) { return function resolveUseClosure (value) { // TODO This should state.options('update.. // TODO look at all of options.xxxx if (resolver.settled && !options.updateAfterSettlement) { return; } var promise = resolver.promise; resolver[appendList].push(value); promise[increment] += 1; promise.pending -= 1; if (resolver.i >= 0) { var resume = resolver.resume; resumeSubscriptionDispatcher( resume.topic, resume.data, options, resume.subscriptions, resolver, resume.fulfill, resume.reject ); return; } evaluateLatch(resolver, options); }; }
javascript
{ "resource": "" }
q35008
evaluateLatch
train
function evaluateLatch (resolver, options) { var settlementLatch = options.settlementLatch, latch = options.latch, promise = resolver.promise, fulfilled = promise.fulfilled, pending = promise.pending, rejected = promise.rejected, settled = fulfilled + rejected, maxFulfilled = fulfilled + pending, total = fulfilled + pending + rejected; if (resolver.settled) { return resolver.settled; } if (!settlementLatch && latch >= 1 && maxFulfilled < latch || !settlementLatch && latch < 1 && maxFulfilled / total < latch || settlementLatch && latch >= 1 && total < latch || settlementLatch && latch < 1 && total === 0 ) { resolver.settled = true; return resolver.reject(resolver.rejectedValues); } if (!settlementLatch && latch >= 1 && fulfilled >= latch || !settlementLatch && latch < 1 && fulfilled / total >= latch || settlementLatch && latch >= 1 && settled >= latch || settlementLatch && latch < 1 && settled / total >= latch ) { resolver.settled = true; return settlementLatch ? resolver.fulfill( resolver.fulfilledValues.concat(resolver.rejectedValues) ) : resolver.fulfill(resolver.fulfilledValues); } return resolver.settled; }
javascript
{ "resource": "" }
q35009
subscriptionInvoker
train
function subscriptionInvoker (subscription, data, topic) { var result; if (subscription.fn.length === 3) { return new Promise(function promiseResolver (fulfill, reject) { subscription.fn.call( subscription.context, data, topic, function callback (err, succ) { return err ? reject(err) : fulfill(succ); } ); }); } try { result = subscription.fn.call(subscription.context, data, topic); } catch (e) { return Promise.reject(e); } if (result && typeof result.then === 'function') { return result; } return Promise.resolve(result); }
javascript
{ "resource": "" }
q35010
subscribeDispatcher
train
function subscribeDispatcher (state, topic, subscriptions, options, context) { topic = typeof topic === 'string' ? topic.split(/,\s*/) : topic; topic = topic && topic.length ? topic : [topic]; var result = curryMap( [state, null, subscriptions, options, context], subscribeTopicApplier, topic ); return result.length === 1 ? result[0] : result; }
javascript
{ "resource": "" }
q35011
applyTopicDescendents
train
function applyTopicDescendents (f, property, topic, topics) { var node = ancestorTopicSearch(topic, topics); if (node.topic === topic) { return curryMap(property, f, descendents(node)); } return null; }
javascript
{ "resource": "" }
q35012
unsuspendSubscriber
train
function unsuspendSubscriber (topic, token) { if (typeof token === 'string') { return !!applyTopicDescendents( unsuspendTopic, 'subscriptions', token, topic ); } var node = ancestorTopicSearch(token.topic, topic); if (node.topic !== token.topic) { return false; } var i = searchAround( getId, getPriority, token.id, token.priority, binaryIndexBy(getPriority, token.priority, node.subscriptions), node.subscriptions ); if (i === -1) { return false; } return !!unsuspendNode(node.subscriptions[i]); }
javascript
{ "resource": "" }
q35013
removeSubscriber
train
function removeSubscriber (args, token) { var topics = args.topics, suspendSubs = args.suspend; if (typeof token === 'string') { return !!applyTopicDescendents( suspendSubs ? suspendTopic : empty, 'subscriptions', token, topics ); } var node = ancestorTopicSearch(token.topic, topics); if (node.topic !== token.topic) { return false; } var i = searchAround( getId, getPriority, token.id, token.priority, binaryIndexBy(getPriority, token.priority, node.subscriptions), node.subscriptions ); if (i === -1) { return false; } if (suspendSubs) { return !!suspendNode(node.subscriptions[i]); } return !!node.subscriptions.splice(i, 1); }
javascript
{ "resource": "" }
q35014
addTopicLine
train
function addTopicLine (topic, ancestor) { var ancestorTopic = ancestor.topic, additionalTopics = []; if (ancestorTopic !== topic) { // All of the generations to add seeded by the youngest existing ancestor additionalTopics = reduce( appendPrefixedTopic, [ancestorTopic], topic.substr(ancestorTopic.length).replace(/^\./, '').split('.') ); } // Add a node to the tree for each new topic return addFamilyLine( addChildTopic, map(createNode, additionalTopics.slice(1)), ancestor ); }
javascript
{ "resource": "" }
q35015
isAncestorTopic
train
function isAncestorTopic (topic, node) { var nodeTopic = getTopic(node); return topic === nodeTopic || startsWith(topic, nodeTopic + '.') || nodeTopic === ''; }
javascript
{ "resource": "" }
q35016
getFingerArrayOrder
train
function getFingerArrayOrder (fingerArray) { var item = getPointedFinger(fingerArray); return item !== SYMBOL_NOTHING ? getOrder(item) : Infinity; }
javascript
{ "resource": "" }
q35017
getFingerArrayPriority
train
function getFingerArrayPriority (fingerArray) { var item = getPointedFinger(fingerArray); return item !== SYMBOL_NOTHING ? getPriority(item) : Infinity; }
javascript
{ "resource": "" }
q35018
createResolver
train
function createResolver () { var resolver = { settled: false, fulfilledValues: [], rejectedValues: [] }, promise = new Promise(function promiseResolver (fulfill, reject) { resolver.fulfill = fulfill; resolver.reject = reject; }); promise.fulfilled = 0; promise.rejected = 0; promise.pending = 0; resolver.promise = promise; return resolver; }
javascript
{ "resource": "" }
q35019
createSubscription
train
function createSubscription (state, fn, options, context) { return { id: state.id(), fn: typeof fn === 'function' ? fn : noop, suspended: false, priority: +options.priority || 0, context: context || null }; }
javascript
{ "resource": "" }
q35020
addChild
train
function addChild (getValue, newChild, tree) { tree.children.splice( binaryIndexBy(getValue, getValue(newChild), tree.children), 0, newChild ); return newChild; }
javascript
{ "resource": "" }
q35021
insert
train
function insert (getValue, item, list) { var index = binaryIndexBy(getValue, getValue(item), list); list.splice(index, 0, item); return item; }
javascript
{ "resource": "" }
q35022
minBy
train
function minBy (valueComputer, list) { var idx = 0, winner = list[idx], computedWinner = valueComputer(winner), computedCurrent; while (++idx < list.length) { computedCurrent = valueComputer(list[idx]); if (computedCurrent < computedWinner) { computedWinner = computedCurrent; winner = list[idx]; } } return winner; }
javascript
{ "resource": "" }
q35023
getPointedFinger
train
function getPointedFinger (fArray) { var pointer = fArray.pointer, array = fArray.array; return array.length > pointer ? array[pointer] : SYMBOL_NOTHING; }
javascript
{ "resource": "" }
q35024
partial1
train
function partial1 (f, x) { return function partiallyApplied1 () { // Using slice or splice on `arguments` causes the function to be // unoptimizable. Who doesn't like optimization? var args = map(identity, arguments); args.unshift(x); return f.apply(null, args); }; }
javascript
{ "resource": "" }
q35025
merge
train
function merge (a, b) { var result = {}; var x; for (x in a) { if (a.hasOwnProperty(x)) { result[x] = a[x]; } } for (x in b) { if (b.hasOwnProperty(x)) { result[x] = b[x]; } } return result; }
javascript
{ "resource": "" }
q35026
reduce
train
function reduce (f, seed, arr) { var result = seed, i, n; for (i = 0, n = arr.length; i < n; i++) { result = f(result, arr[i]); } return result; }
javascript
{ "resource": "" }
q35027
curryMap
train
function curryMap (args, f, arr) { var result = [], i, n; for (i = 0, n = arr.length; i < n; i++) { result.push(f(args, arr[i])); } return result; }
javascript
{ "resource": "" }
q35028
map
train
function map (f, arr) { var result = [], i, n; for (i = 0, n = arr.length; i < n; i++) { result.push(f(arr[i])); } return result; }
javascript
{ "resource": "" }
q35029
startsWith
train
function startsWith (haystack, needle, startPosition) { startPosition = startPosition || 0; return haystack.lastIndexOf(needle, startPosition) === startPosition; }
javascript
{ "resource": "" }
q35030
checkNpmVersion
train
function checkNpmVersion() { return execa.shell('npm -v') .then(({ stdout }) => stdout) .then((v) => { if (v && !(v.indexOf('3') === 0)) { log('Use npm v3.10.10 for unobtrusive symlinks: npm i -g npm@3.10.10'); } }); }
javascript
{ "resource": "" }
q35031
linkPackages
train
function linkPackages(pathToPkgs) { const pkgs = pathToPkgs.join(' '); return execa .shell(`npm link ${pkgs}`) .then(() => log('Succesfully linked')); }
javascript
{ "resource": "" }
q35032
getSharedDepDirs
train
function getSharedDepDirs(pkgs, hash) { return pkgs.map(({ name, dir }) => { if (hash[name]) { return dir; } return false; }).filter(Boolean); }
javascript
{ "resource": "" }
q35033
getSharedLinked
train
function getSharedLinked(pkgs, hash) { return pkgs.map((name) => { const module = hash[name]; if (module && module.isLinked) { return name; } return false; }).filter(Boolean); }
javascript
{ "resource": "" }
q35034
getSharedDeps
train
function getSharedDeps(pkgs, hash) { return pkgs.map(({ name }) => { if (hash[name]) { return name; } return false; }).filter(Boolean); }
javascript
{ "resource": "" }
q35035
getLinkedDeps
train
function getLinkedDeps(pkgs) { return pkgs.map((name) => { const isLinked = checkForLink(name); return isLinked ? name : false; }).filter(Boolean); }
javascript
{ "resource": "" }
q35036
showLinkedDeps
train
function showLinkedDeps() { const linkedDeps = getLinkedDeps(packageKeys, packageHash); if (linkedDeps.length) { logPkgsMsg('Linked', linkedDeps); } else { log('No linked dependencies found'); } }
javascript
{ "resource": "" }
q35037
train
function( option, list ) { var label = doc.createElement( 'label' ); label.setAttribute( 'for', 'cke_option' + option ); label.setHtml( list[ option ] ); if ( dialog.sLang == option ) // Current. dialog.chosed_lang = option; var div = doc.createElement( 'div' ); var radio = CKEDITOR.dom.element.createFromHtml( '<input id="cke_option' + option + '" type="radio" ' + ( dialog.sLang == option ? 'checked="checked"' : '' ) + ' value="' + option + '" name="scayt_lang" />' ); radio.on( 'click', function() { this.$.checked = true; dialog.chosed_lang = option; }); div.append( radio ); div.append( label ); return { lang : list[ option ], code : option, radio : div }; }
javascript
{ "resource": "" }
q35038
PointerDetectorWindowMediaParam
train
function PointerDetectorWindowMediaParam(pointerDetectorWindowMediaParamDict){ if(!(this instanceof PointerDetectorWindowMediaParam)) return new PointerDetectorWindowMediaParam(pointerDetectorWindowMediaParamDict) pointerDetectorWindowMediaParamDict = pointerDetectorWindowMediaParamDict || {} // Check pointerDetectorWindowMediaParamDict has the required fields // // checkType('String', 'pointerDetectorWindowMediaParamDict.id', pointerDetectorWindowMediaParamDict.id, {required: true}); // // checkType('int', 'pointerDetectorWindowMediaParamDict.height', pointerDetectorWindowMediaParamDict.height, {required: true}); // // checkType('int', 'pointerDetectorWindowMediaParamDict.width', pointerDetectorWindowMediaParamDict.width, {required: true}); // // checkType('int', 'pointerDetectorWindowMediaParamDict.upperRightX', pointerDetectorWindowMediaParamDict.upperRightX, {required: true}); // // checkType('int', 'pointerDetectorWindowMediaParamDict.upperRightY', pointerDetectorWindowMediaParamDict.upperRightY, {required: true}); // // checkType('String', 'pointerDetectorWindowMediaParamDict.activeImage', pointerDetectorWindowMediaParamDict.activeImage); // // checkType('float', 'pointerDetectorWindowMediaParamDict.imageTransparency', pointerDetectorWindowMediaParamDict.imageTransparency); // // checkType('String', 'pointerDetectorWindowMediaParamDict.image', pointerDetectorWindowMediaParamDict.image); // // Init parent class PointerDetectorWindowMediaParam.super_.call(this, pointerDetectorWindowMediaParamDict) // Set object properties Object.defineProperties(this, { id: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.id }, height: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.height }, width: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.width }, upperRightX: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.upperRightX }, upperRightY: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.upperRightY }, activeImage: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.activeImage }, imageTransparency: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.imageTransparency }, image: { writable: true, enumerable: true, value: pointerDetectorWindowMediaParamDict.image } }) }
javascript
{ "resource": "" }
q35039
renderTemplate
train
function renderTemplate(impl, targetFile){ var stappoImpl = fs.readFileSync(impl, "utf8"); return gulp.src([targetFile]) .pipe(replace('/*__stappo_impl__*/', stappoImpl)); }
javascript
{ "resource": "" }
q35040
train
function( html ) { var parts, tagName, nextIndex = 0, cdata; // The collected data inside a CDATA section. while ( ( parts = this._.htmlPartsRegex.exec( html ) ) ) { var tagIndex = parts.index; if ( tagIndex > nextIndex ) { var text = html.substring( nextIndex, tagIndex ); if ( cdata ) cdata.push( text ); else this.onText( text ); } nextIndex = this._.htmlPartsRegex.lastIndex; /* "parts" is an array with the following items: 0 : The entire match for opening/closing tags and comments. 1 : Group filled with the tag name for closing tags. 2 : Group filled with the comment text. 3 : Group filled with the tag name for opening tags. 4 : Group filled with the attributes part of opening tags. */ // Closing tag if ( ( tagName = parts[ 1 ] ) ) { tagName = tagName.toLowerCase(); if ( cdata && CKEDITOR.dtd.$cdata[ tagName ] ) { // Send the CDATA data. this.onCDATA( cdata.join('') ); cdata = null; } if ( !cdata ) { this.onTagClose( tagName ); continue; } } // If CDATA is enabled, just save the raw match. if ( cdata ) { cdata.push( parts[ 0 ] ); continue; } // Opening tag if ( ( tagName = parts[ 3 ] ) ) { tagName = tagName.toLowerCase(); // There are some tag names that can break things, so let's // simply ignore them when parsing. (#5224) if ( /="/.test( tagName ) ) continue; var attribs = {}, attribMatch, attribsPart = parts[ 4 ], selfClosing = !!( attribsPart && attribsPart.charAt( attribsPart.length - 1 ) == '/' ); if ( attribsPart ) { while ( ( attribMatch = attribsRegex.exec( attribsPart ) ) ) { var attName = attribMatch[1].toLowerCase(), attValue = attribMatch[2] || attribMatch[3] || attribMatch[4] || ''; if ( !attValue && emptyAttribs[ attName ] ) attribs[ attName ] = attName; else attribs[ attName ] = attValue; } } this.onTagOpen( tagName, attribs, selfClosing ); // Open CDATA mode when finding the appropriate tags. if ( !cdata && CKEDITOR.dtd.$cdata[ tagName ] ) cdata = []; continue; } // Comment if ( ( tagName = parts[ 2 ] ) ) this.onComment( tagName ); } if ( html.length > nextIndex ) this.onText( html.substring( nextIndex, html.length ) ); }
javascript
{ "resource": "" }
q35041
train
function() { var cache = this._.cache; if ( cache.startElement !== undefined ) return cache.startElement; var node, sel = this.getNative(); switch ( this.getType() ) { case CKEDITOR.SELECTION_ELEMENT : return this.getSelectedElement(); case CKEDITOR.SELECTION_TEXT : var range = this.getRanges()[0]; if ( range ) { if ( !range.collapsed ) { range.optimize(); // Decrease the range content to exclude particial // selected node on the start which doesn't have // visual impact. ( #3231 ) while ( 1 ) { var startContainer = range.startContainer, startOffset = range.startOffset; // Limit the fix only to non-block elements.(#3950) if ( startOffset == ( startContainer.getChildCount ? startContainer.getChildCount() : startContainer.getLength() ) && !startContainer.isBlockBoundary() ) range.setStartAfter( startContainer ); else break; } node = range.startContainer; if ( node.type != CKEDITOR.NODE_ELEMENT ) return node.getParent(); node = node.getChild( range.startOffset ); if ( !node || node.type != CKEDITOR.NODE_ELEMENT ) node = range.startContainer; else { var child = node.getFirst(); while ( child && child.type == CKEDITOR.NODE_ELEMENT ) { node = child; child = child.getFirst(); } } } else { node = range.startContainer; if ( node.type != CKEDITOR.NODE_ELEMENT ) node = node.getParent(); } node = node.$; } } return cache.startElement = ( node ? new CKEDITOR.dom.element( node ) : null ); }
javascript
{ "resource": "" }
q35042
train
function() { var root, retval, range = self.getRanges()[ 0 ], ancestor = range.getCommonAncestor( 1, 1 ), tags = { table:1,ul:1,ol:1,dl:1 }; for ( var t in tags ) { if ( root = ancestor.getAscendant( t, 1 ) ) break; } if ( root ) { // Enlarging the start boundary. var testRange = new CKEDITOR.dom.range( this.document ); testRange.setStartAt( root, CKEDITOR.POSITION_AFTER_START ); testRange.setEnd( range.startContainer, range.startOffset ); var enlargeables = CKEDITOR.tools.extend( tags, CKEDITOR.dtd.$listItem, CKEDITOR.dtd.$tableContent ), walker = new CKEDITOR.dom.walker( testRange ), // Check the range is at the inner boundary of the structural element. guard = function( walker, isEnd ) { return function( node, isWalkOut ) { if ( node.type == CKEDITOR.NODE_TEXT && ( !CKEDITOR.tools.trim( node.getText() ) || node.getParent().data( 'cke-bookmark' ) ) ) return true; var tag; if ( node.type == CKEDITOR.NODE_ELEMENT ) { tag = node.getName(); // Bypass bogus br at the end of block. if ( tag == 'br' && isEnd && node.equals( node.getParent().getBogus() ) ) return true; if ( isWalkOut && tag in enlargeables || tag in CKEDITOR.dtd.$removeEmpty ) return true; } walker.halted = 1; return false; }; }; walker.guard = guard( walker ); if ( walker.checkBackward() && !walker.halted ) { walker = new CKEDITOR.dom.walker( testRange ); testRange.setStart( range.endContainer, range.endOffset ); testRange.setEndAt( root, CKEDITOR.POSITION_BEFORE_END ); walker.guard = guard( walker, 1 ); if ( walker.checkForward() && !walker.halted ) retval = root.$; } } if ( !retval ) throw 0; return retval; }
javascript
{ "resource": "" }
q35043
train
function() { var ranges = this.getRanges(), startNode = ranges[ 0 ].startContainer, endNode = ranges[ ranges.length - 1 ].endContainer; return startNode.getCommonAncestor( endNode ); }
javascript
{ "resource": "" }
q35044
buildTable
train
function buildTable( entities, reverse ) { var table = {}, regex = []; // Entities that the browsers DOM don't transform to the final char // automatically. var specialTable = { nbsp : '\u00A0', // IE | FF shy : '\u00AD', // IE gt : '\u003E', // IE | FF | -- | Opera lt : '\u003C', // IE | FF | Safari | Opera amp : '\u0026' // ALL }; entities = entities.replace( /\b(nbsp|shy|gt|lt|amp)(?:,|$)/g, function( match, entity ) { var org = reverse ? '&' + entity + ';' : specialTable[ entity ], result = reverse ? specialTable[ entity ] : '&' + entity + ';'; table[ org ] = result; regex.push( org ); return ''; }); if ( !reverse && entities ) { // Transforms the entities string into an array. entities = entities.split( ',' ); // Put all entities inside a DOM element, transforming them to their // final chars. var div = document.createElement( 'div' ), chars; div.innerHTML = '&' + entities.join( ';&' ) + ';'; chars = div.innerHTML; div = null; // Add all chars to the table. for ( var i = 0 ; i < chars.length ; i++ ) { var charAt = chars.charAt( i ); table[ charAt ] = '&' + entities[ i ] + ';'; regex.push( charAt ); } } table.regex = regex.join( reverse ? '|' : '' ); return table; }
javascript
{ "resource": "" }
q35045
train
function(config) { this.config = config; this.appContext = null; this.injectAppContext = this.config.injectAppContext === true ? true : false; //cache of loaded dependencies this.moduleMap = {}; }
javascript
{ "resource": "" }
q35046
train
function(config, protoFactory, originalModule) { this.config = config; this.protoFactory = protoFactory; this.originalModule = originalModule || module; //defines if circular dependencies should throw an error or be gracefully handled this.allowCircular = this.config.allowCircular || false; this.modules = []; if(define.amd && typeof requirejs !== "undefined") { this._loader = require; } else if(define.amd && typeof curl !== "undefined") { this._loader = curl; } else { this._loader = this._commonRequire; } }
javascript
{ "resource": "" }
q35047
ConnectionState
train
function ConnectionState(code, stringId, connected) { if (arguments.length === 2) { connected = stringId; stringId = 'NONAME'; } if (!(this instanceof ConnectionState)) { return new ConnectionState(code, stringId, connected); } this.id = stringId; this.code = code; this.connected = connected; }
javascript
{ "resource": "" }
q35048
train
function( obj ) { var style = this.toString(); if ( style ) { obj instanceof CKEDITOR.dom.element ? obj.setAttribute( 'style', style ) : obj instanceof CKEDITOR.htmlParser.element ? obj.attributes.style = style : obj.style = style; } }
javascript
{ "resource": "" }
q35049
train
function( event ) { if ( this.mode != 'wysiwyg' ) return; switch ( event.data.keyCode ) { // Paste case CKEDITOR.CTRL + 86 : // CTRL+V case CKEDITOR.SHIFT + 45 : // SHIFT+INS var body = this.document.getBody(); // Simulate 'beforepaste' event for all none-IEs. if ( !CKEDITOR.env.ie && body.fire( 'beforepaste' ) ) event.cancel(); // Simulate 'paste' event for Opera/Firefox2. else if ( CKEDITOR.env.opera || CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) body.fire( 'paste' ); return; // Cut case CKEDITOR.CTRL + 88 : // CTRL+X case CKEDITOR.SHIFT + 46 : // SHIFT+DEL // Save Undo snapshot. var editor = this; this.fire( 'saveSnapshot' ); // Save before paste setTimeout( function() { editor.fire( 'saveSnapshot' ); // Save after paste }, 0 ); } }
javascript
{ "resource": "" }
q35050
train
function(start, end) { var date; var res = []; for (var key in holidays) { date = beginningOfDay(new Date(key)); // given `start` and `end` Date object are both normalized to beginning of the day if (beginningOfDay(start) <= date && date <= beginningOfDay(end)) { res.push(holiday(date, holidays[key])); } } return res; }
javascript
{ "resource": "" }
q35051
Route
train
function Route(method, route, fn) { this.method = method; this.route = route; this.fn = fn; return function (app) { var middleware = exports.isAppSettingsRoute(route) ? utils.getSettingsMiddlewares() : utils.getRequestMiddlewares(); if (method == "get") { app.get(route, middleware, fn) } else if (method == "post") { app.post(route, middleware, fn); } // var methodRoutes = app.routes[method]; // return methodRoutes[methodRoutes.length - 1]; }; }
javascript
{ "resource": "" }
q35052
normalizePath
train
function normalizePath(path, keys, params) { for (var name in params) { var param = params[name]; if (typeof param == "string" || param instanceof RegExp) params[name] = {type: param}; } path = path .concat("/?") .replace(/\/:([\w.\-_]+)(\*?)/g, function(match, key, wildcard) { keys.push(key); if (!params[key]) { params[key] = {}; } // url params default to type string and optional=false var param = params[key]; param.type = param.type || "string"; param.optional = false; if (!param.source) param.source = "url"; if (param.source !== "url") throw new Error( "Url parameters must have 'url' as source but found '" + param.source + "'" ); if (wildcard) return "(/*)"; else return "/([^\\/]+)"; }) .replace(/([/.])/g, "\\$1") .replace(/\*/g, "(.*)"); return new RegExp("^" + path + "$"); }
javascript
{ "resource": "" }
q35053
train
function (target, cb) { if(!target) return cb(new Error('WebBoot.prune: size to clear must be provided')) var cleared = 0, remove = [] function clear () { var n = remove.length while(remove.length) store.rm(remove.shift(), function () { if(--n) return if(cleared < target) cb(new Error('could not clear requested space'), cleared) else cb(null, cleared) }) } store.ls(function (err, ls) { if(err) return cb(err) log.unfiltered(function (err, unfiltered) { if(err) return cb(err) var stored = unfiltered.reverse() ls.forEach(function (a) { if(!unfiltered.find(function (b) { return a.id == b.id })) { cleared += a.size remove.push(a.id) } }) for(var i = 0; i < stored.length; i++) { var id = stored[i].value var item = ls.find(function (e) { return e.id === id }) if(item) { cleared += item.size remove.push(id) if(cleared >= target) return clear() } } clear() }) }) }
javascript
{ "resource": "" }
q35054
dice
train
function dice( source, target ) { var sources = dice.prepare( source ) var targets = dice.prepare( target ) var i, k, intersection = 0 var source_count = sources.length var target_count = targets.length var union = source_count + target_count for( i = 0; i < source_count; i++ ) { source = sources[i] for( k = 0; k < target_count; k++ ) { target = targets[k] if( source === target ) { intersection++ targets[k] = undefined break } } } return 2 * intersection / union }
javascript
{ "resource": "" }
q35055
createSocket
train
function createSocket(socket, options = {}) { if (!isSocket(socket)) { options = socket; // eslint-disable-line no-param-reassign if (isSocket(options.socket)) { // eslint-disable-next-line no-param-reassign, prefer-destructuring socket = options.socket; } else { socket = dgram.createSocket(options); // eslint-disable-line no-param-reassign socket.bind(options.port || 0, options.address || '0.0.0.0'); } } return new Socket(Object.assign({}, options, { socket })); }
javascript
{ "resource": "" }
q35056
sphereVsAabb
train
function sphereVsAabb(contactPoint, contactNormal, sphere, aabb) { findClosestPointFromAabbSurfaceToPoint(contactPoint, aabb, sphere.centerOfVolume); findAabbNormalFromContactPoint(contactNormal, contactPoint, aabb); vec3.negate(contactNormal, contactNormal); }
javascript
{ "resource": "" }
q35057
argsGetter
train
function argsGetter(args, lang) { return args.map(arg => rStrip( String(arg), (s, a, b, c, count) => { const data = JSON.parse(s) return toWrappedString(translatedGetter(data[0], () => data.slice(1), lang), void 0, count) }, level - 1 ) ) }
javascript
{ "resource": "" }
q35058
startSites
train
function startSites(config){ config.siteNames.forEach(function(item){ var cmd = 'iisexpress /site:"' + item + '"'; if(config.configFile !== ""){ cmd += ' /config:"' + config.configFile + '"'; } if (config.sysTray){ cmd += ' /systray:true'; }else{ cmd += ' /systray:false'; } gulp.src('') .pipe(shell([ cmd ],{ cwd: config.iisExpressPath })) .on('error', util.log); }); return gulp.src(''); }
javascript
{ "resource": "" }
q35059
maxPrerelease
train
function maxPrerelease (versions, prerelease) { return first(desc(versions), function (version) { return isPrerelease(version, prerelease); }); }
javascript
{ "resource": "" }
q35060
first
train
function first (array, filter) { var i = 0; var length = array.length; var item; for (; i < length; i ++) { item = array[i]; if (filter(item)) { return item; } } return null; }
javascript
{ "resource": "" }
q35061
serialEach
train
function serialEach(object, fn, callback) { var keys = Object.keys(object); next(); function next(err) { if (err) return callback(err); var key = keys.shift(); if (!key) return callback(); fn(key, object[key], next); } }
javascript
{ "resource": "" }
q35062
CacheItem
train
function CacheItem(permissionSchemaKey, actionsValue, permissions) { if (!actionsValue) { if (!utils.contains(permissionSchemaKey, TRIPLE_UNDERSCORE)) { throw new Error("Invalid permissions schema key.") } else { var key = permissionSchemaKey.split(TRIPLE_UNDERSCORE)[0]; actionsValue = cache.get(key).actionsValue; } } /** * Getter for permissionSchemaKey * @returns {String} */ this.getPermissionSchemaKey = function () { return permissionSchemaKey; }; /** * Returns action value. * @param action {String} Action key * @returns {String} */ this.getActionValue = function (action) { if (!action) { throw new Error('No arguments'); } return actionsValue[action]; }; /** * Returns array of action values for the role * @param roleId {Number} * @returns {Array} */ this.getRolePermissions = function (roleId) { if (!roleId) { throw new Error('No arguments'); } return permissions[roleId]; }; /** * Getter of permissions * @returns {Object} */ this.getPermissions = function () { return permissions; }; /** * Getter of actions values. * @returns {Object} */ this.getActionsValue = function () { return actionsValue; }; this.permissions = permissions this.actionsValue = actionsValue }
javascript
{ "resource": "" }
q35063
storeModel
train
function storeModel(model, permissionSchemaKey) { if (model && model.rolePermissions) { var obj = { permissionSchemaKey: permissionSchemaKey, rolePermissions: model.rolePermissions }; exports.store(obj); } }
javascript
{ "resource": "" }
q35064
train
function() { if ( combo ) { delete combo._.panel; delete combo._.list; combo._.committed = 0; combo._.items = {}; combo._.state = CKEDITOR.TRISTATE_OFF; } styles = {}; stylesList = []; loadStylesSet(); }
javascript
{ "resource": "" }
q35065
spellCheckText
train
function spellCheckText(text) { var src = new StructuredSource(text); var results = []; for (var i = 0, length = dictionaryItems.length; i < length; i++) { var dictionary = dictionaryItems[i]; var query = new RegExp(dictionary.pattern, dictionary.flag); var match = query.exec(text); if (!match) { continue; } var matchedString = match[0]; // s/Web/Web/iは大文字小文字無視してWebに変換したいという意味に対応する if (dictionary.flag != null) { var strictQuery = new RegExp(dictionary.pattern); var isStrictMatch = strictQuery.test(match[0]); // /Web/i でマッチするけど、 /Web/ でマッチするならそれは除外する if (isStrictMatch) { continue; } } // s/ベンダ/ベンダー/ のようにexpectedがpatternを包含している場合のexpectedを除外 var expected = matchedString.replace(query, dictionary.expected); if (text.slice(match.index).indexOf(expected) === 0) { // [start, end] continue; } var position = src.indexToPosition(match.index); /** * * @typedef {{actual: string, expected: string, paddingLine: number, paddingColumn: number}} SpellCheckResult */ var result = { actual: matchedString, expected: expected, paddingIndex: match.index, paddingLine: position.line - 1,// start with 0 paddingColumn: position.column// start with 0 }; results.push(result); } return results.reverse(); }
javascript
{ "resource": "" }
q35066
SettingsErrorRenderer
train
function SettingsErrorRenderer(err, req, res) { SettingsRenderer.call(this, req, res); Object.defineProperties(this, { err: { value: err || new Error() } }); req.attrs.isErrorPage = true; }
javascript
{ "resource": "" }
q35067
reset
train
function reset(html) { this.html = html || this.html; this.root = new VNode('div'); this.node = this.root; // current working node this.path = []; // current working node parents this.blocks = []; // recursive components }
javascript
{ "resource": "" }
q35068
push
train
function push() { this.path.push(this.node); this.node = this.node.children[this.node.children.length - 1]; }
javascript
{ "resource": "" }
q35069
ontext
train
function ontext(template, text, config) { var blockStubPos = -1, cursor = 0, children = null, nodes = [] ; config = extend({virtual: template.virtual}, config); // Ensures that consecutive textOnly components are merged into a single VText node function concatText(text) { if ((nodes.length > 0) && nodes[nodes.length - 1].addText) { nodes[nodes.length - 1].addText(text); } else { nodes.push(new VText(text, config)); } } // DRY parse function concatInterpolatedContent(content) { Expression.parseInterpolated(content, { ontext: function(text) { concatText(text); }, onexpression: function(expr) { if (expr.textOnly || (config.virtual === false)) { concatText(expr); } else { nodes.push(expr); } } }); } // While we find more interpolated handlebars blocks while ((blockStubPos = text.indexOf(_blockStub, cursor)) > -1) { // Get pre-text if (blockStubPos > cursor) { concatInterpolatedContent(text.substr(cursor, blockStubPos - cursor)); } // Add the block to the list of nodes block = template.blocks.shift(); if (config.virtual === false) { block.callback.virtual = false; concatText(block); } else { nodes.push(block); } // Advance the cursor cursor = blockStubPos + _blockStub.length; } // Get post-text (or the only text) if (cursor < text.length) { concatInterpolatedContent(text.substr(cursor)); } // textOnly is for things like tagName and attribute values return nodes; }
javascript
{ "resource": "" }
q35070
concatText
train
function concatText(text) { if ((nodes.length > 0) && nodes[nodes.length - 1].addText) { nodes[nodes.length - 1].addText(text); } else { nodes.push(new VText(text, config)); } }
javascript
{ "resource": "" }
q35071
attributesToJavascript
train
function attributesToJavascript(template, attr) { var i, name, value, js = []; for (i in attr) { if (attr.hasOwnProperty(i)) { // Translate name = Template.HTML_ATTRIBUTES[i] ? Template.HTML_ATTRIBUTES[i] : i; // Potentially interpolated attributes if (typeof attr[i] === 'string') { if (attr[i].length > 0) { js.push(JSON.stringify(name) + ':' + (ontext(template, attr[i], {virtual: false}).pop() || new VText).toJavascript()); } else { js.push(JSON.stringify(name) + ':""'); } } else { js.push(JSON.stringify(name) + ':' + JSON.stringify(attr[i])); } } } return '{' + js.join(',') + '}'; }
javascript
{ "resource": "" }
q35072
train
function() { var dialog = this.getDialog(), popupFeatures = dialog.getContentElement( 'target', 'popupFeatures' ), targetName = dialog.getContentElement( 'target', 'linkTargetName' ), value = this.getValue(); if ( !popupFeatures || !targetName ) return; popupFeatures = popupFeatures.getElement(); popupFeatures.hide(); targetName.setValue( '' ); switch ( value ) { case 'frame' : targetName.setLabel( editor.lang.link.targetFrameName ); targetName.getElement().show(); break; case 'popup' : popupFeatures.show(); targetName.setLabel( editor.lang.link.targetPopupName ); targetName.getElement().show(); break; default : targetName.setValue( value ); targetName.getElement().hide(); break; } }
javascript
{ "resource": "" }
q35073
train
function() { var dialog = this.getDialog(), partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions' ], typeValue = this.getValue(), uploadTab = dialog.definition.getContents( 'upload' ), uploadInitiallyHidden = uploadTab && uploadTab.hidden; if ( typeValue == 'url' ) { if ( editor.config.linkShowTargetTab ) dialog.showPage( 'target' ); if ( !uploadInitiallyHidden ) dialog.showPage( 'upload' ); } else { dialog.hidePage( 'target' ); if ( !uploadInitiallyHidden ) dialog.hidePage( 'upload' ); } for ( var i = 0 ; i < partIds.length ; i++ ) { var element = dialog.getContentElement( 'info', partIds[i] ); if ( !element ) continue; element = element.getElement().getParent().getParent(); if ( partIds[i] == typeValue + 'Options' ) element.show(); else element.hide(); } dialog.layout(); }
javascript
{ "resource": "" }
q35074
train
function() { var linkType = this.getContentElement( 'info', 'linkType' ), urlField; if ( linkType && linkType.getValue() == 'url' ) { urlField = this.getContentElement( 'info', 'url' ); urlField.select(); } }
javascript
{ "resource": "" }
q35075
failAfterStream
train
function failAfterStream(options) { if (!_.isObject(options)) { options = {}; } var files = []; return through.obj(function(chunk, enc, cb) { var stats = chunk[processStats.STATS_DATA_FIELD_NAME], isStats = chunk[processStats.STATS_FLAG_FIELD_NAME], filename = path.resolve(chunk.path); if (isStats && !_.includes(files, filename)) { var hasErrors = false, hasWarnings = false; if (options.errors === true) { hasErrors = stats.hasErrors(); } if (options.warnings === true) { hasWarnings = stats.hasWarnings(); } if (hasErrors || hasWarnings) { files.push(filename); } } cb(null, chunk); }, function(cb) { if (files.length > 0) { var message = messageFor(files); this.emit('error', wrapError(message, { showProperties: false, showStack: false })); } cb(); }); }
javascript
{ "resource": "" }
q35076
getMongoSortArray
train
function getMongoSortArray (field, prefix) { return (!field.startsWith('-')) ? [prefix + field, 1] : [prefix + field.substr(1), -1]; }
javascript
{ "resource": "" }
q35077
train
function () { var packages = [ 'ember-cli-autoprefixer', 'ember-cli-blanket', 'ember-cli-sass', 'ember-cpm', 'ember-feature-flags', 'ember-metrics', 'ember-moment', 'ember-responsive', 'ember-route-action-helper', 'ember-suave', 'ember-truth-helpers' ]; var updatePrompt = { type: 'confirm', name: 'answer', choices: [ { key: 'y', name: 'Yes', value: 'yes' }, { key: 'n', name: 'No', value: 'no' } ] }; var prompts = [ extend({ message: 'Would you like to enhance your ember-cli-opinionated setup?', packages: packages }, updatePrompt), // extend({ message: 'Organizing Your App Into Pods', packages: ['ember-cli-sass-pods'] }, updatePrompt), extend({ message: 'Analytics/Reports', packages: ['ember-e3'] }, updatePrompt), extend({ message: 'Testing', packages: ['ember-cli-mirage', 'ember-sinon-qunit'] }, updatePrompt), // extend({ message: 'Internationalization (i18n)', packages: ['ember-intl'] }, updatePrompt), extend({ message: 'Mobile Touch', packages: ['ember-gestures'] }, updatePrompt), extend({ message: 'Material Design', packages: ['ember-paper'] }, updatePrompt), extend({ message: 'Animations', packages: ['liquid-fire'] }, updatePrompt) ]; return this.promptUserForOpinions(packages, prompts); }
javascript
{ "resource": "" }
q35078
train
function( element ) { var childNodes = element.getChildren(); for ( var i = 0, count = childNodes.count() ; i < count ; i++ ) { var child = childNodes.getItem( i ); if ( child.type == CKEDITOR.NODE_ELEMENT && CKEDITOR.dtd.$block[ child.getName() ] ) return true; } return false; }
javascript
{ "resource": "" }
q35079
train
function( otherPath ) { var thisElements = this.elements; var otherElements = otherPath && otherPath.elements; if ( !otherElements || thisElements.length != otherElements.length ) return false; for ( var i = 0 ; i < thisElements.length ; i++ ) { if ( !thisElements[ i ].equals( otherElements[ i ] ) ) return false; } return true; }
javascript
{ "resource": "" }
q35080
validateInput
train
function validateInput(params, cb) { if (typeof params !== 'object') return new TypeError("params must be an object"); if (typeof cb !== 'function') return new TypeError("callback must be a function"); if (params.origin === "") return new Error("params.origin is required"); if (params.destination === "") return new Error("params.destination is required"); if (params.key === "") return new Error("params.key is required"); }
javascript
{ "resource": "" }
q35081
outputHelp
train
function outputHelp() { console.log( '\nUsage: git-hooks [options]\n\n' + 'A tool to manage project Git hooks\n\n' + 'Options:\n\n' + Object.keys(options) .map(function (key) { return ' --' + key + '\t' + options[key] + '\n'; }) .join('') ); }
javascript
{ "resource": "" }
q35082
train
function (err, m) { if (m) { model = m; } else { err = new Error("Invalid linked model."); } n(err, m); }
javascript
{ "resource": "" }
q35083
normalizeInput
train
function normalizeInput(input) { var ret; if (input instanceof Uint8Array) { ret = input; } else if (input instanceof Buffer) { ret = new Uint8Array(input); } else if (typeof (input) === 'string') { ret = new Uint8Array(Buffer.from(input, 'utf8')); } else { throw new Error(ERROR_MSG_INPUT); } return ret; }
javascript
{ "resource": "" }
q35084
B2B_GET32
train
function B2B_GET32(arr, i) { return (arr[i] ^ (arr[i + 1] << 8) ^ (arr[i + 2] << 16) ^ (arr[i + 3] << 24)); }
javascript
{ "resource": "" }
q35085
B2B_G
train
function B2B_G(a, b, c, d, ix, iy) { var x0 = m[ix]; var x1 = m[ix + 1]; var y0 = m[iy]; var y1 = m[iy + 1]; ADD64AA(v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s ADD64AC(v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits var xor0 = v[d] ^ v[a]; var xor1 = v[d + 1] ^ v[a + 1]; v[d] = xor1; v[d + 1] = xor0; ADD64AA(v, c, d); // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits xor0 = v[b] ^ v[c]; xor1 = v[b + 1] ^ v[c + 1]; v[b] = (xor0 >>> 24) ^ (xor1 << 8); v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8); ADD64AA(v, a, b); ADD64AC(v, a, y0, y1); // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits xor0 = v[d] ^ v[a]; xor1 = v[d + 1] ^ v[a + 1]; v[d] = (xor0 >>> 16) ^ (xor1 << 16); v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16); ADD64AA(v, c, d); // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits xor0 = v[b] ^ v[c]; xor1 = v[b + 1] ^ v[c + 1]; v[b] = (xor1 >>> 31) ^ (xor0 << 1); v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1); }
javascript
{ "resource": "" }
q35086
blake2bInit
train
function blake2bInit(outlen, key) { if (outlen === 0 || outlen > 64) { throw new Error('Illegal output length, expected 0 < length <= 64'); } if (key && key.length > 64) { throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64'); } // state, 'param block' var ctx = { b: new Uint8Array(128), h: new Uint32Array(16), t: 0, c: 0, outlen: outlen // output length in bytes }; // initialize hash state for (var i = 0; i < 16; i++) { ctx.h[i] = BLAKE2B_IV32[i]; } var keylen = key ? key.length : 0; ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen; // key the hash, if applicable if (key) { blake2bUpdate(ctx, key); // at the end ctx.c = 128; } return ctx; }
javascript
{ "resource": "" }
q35087
blake2bFinal
train
function blake2bFinal(ctx) { ctx.t += ctx.c; // mark last block offset while (ctx.c < 128) { // fill up with zeros ctx.b[ctx.c++] = 0; } blake2bCompress(ctx, true); // final block flag = 1 // little endian convert and store var out = new Uint8Array(ctx.outlen); for (var i = 0; i < ctx.outlen; i++) { out[i] = ctx.h[i >> 2] >> (8 * (i & 3)); } return out; }
javascript
{ "resource": "" }
q35088
generateIdFromFilePath
train
function generateIdFromFilePath(filePath) { var arr = filePath.split("/"), len = arr.length, last = arr[len - 1], secondLast = arr[len - 2], thirdLast = arr[len - 3]; var isPluginFile = utils.contains(filePath, "/plugins/"); return isPluginFile ? thirdLast + "/" + last : thirdLast + "/" + secondLast + "/" + last; }
javascript
{ "resource": "" }
q35089
initThemeFilesWatch
train
function initThemeFilesWatch(app) { utils.tick(function () { var viewsPath = utils.getViewsPath(); var dbAction = new DBActions.DBActions(app.set("db"), {modelName: "Theme"}); dbAction.get("getAll", null, function (err, themes) { if (err) throw err; themes.forEach(function (theme) { cacheAndWatchTheme(app, theme); }); }) }); }
javascript
{ "resource": "" }
q35090
trimCell
train
function trimCell( cell ) { var bogus = cell.getBogus(); bogus && bogus.remove(); cell.trim(); }
javascript
{ "resource": "" }
q35091
getHandler
train
function getHandler(app, schema, data) { function handleSave(err, results, next) { if (!err) { delete DependenciesMap[schema]; SavedSchemas.push(schema); _l('schema saved: ' + schema); } next(err, results); } // Default handler function var ret = function (next) { data = _.isObject(data) ? _.values(data) : data; DBActions.getSimpleInstance(app, schema).multipleSave(data, function (err, results) { handleSave(err, results, next); }); }; // Data handler provided in plugin var ret1 = SchemaDataHandler[schema] && function (next) { SchemaDataHandler[schema](app, data)(function (err, results) { handleSave(err, results, next); }); }; return ret1 || ret; }
javascript
{ "resource": "" }
q35092
train
function (next) { data = _.isObject(data) ? _.values(data) : data; DBActions.getSimpleInstance(app, schema).multipleSave(data, function (err, results) { handleSave(err, results, next); }); }
javascript
{ "resource": "" }
q35093
dependenciesExists
train
function dependenciesExists(schema) { var deps = DependenciesMap[schema]; var f = false; deps.forEach(function (d) { f = SavedSchemas.indexOf(d) > -1 }); return f; }
javascript
{ "resource": "" }
q35094
saveSchemas
train
function saveSchemas(app) { var keys = Object.keys(DependenciesMap); if (keys.length == 0) { _l('Default data saved...'); event.emit(COMPLETED_EVENT); return; } HandlerArray = []; var errFlag = true; keys.forEach(function (k) { dependenciesExists(k) && HandlerArray.push(getHandler(app, k, PluginsData[k])); }); async.series(HandlerArray, function (err, end) { if (err) throw err; saveSchemas(app); }); }
javascript
{ "resource": "" }
q35095
init
train
function init(app) { var keys = Object.keys(DependenciesMap); var allDeps = _.uniq(_.flatten(_.values(DependenciesMap))); allDeps.forEach(function (d) { if (!_.contains(keys, d)) { throw new Error("Unresolved dependency: " + d) } }); keys.forEach(function (k) { var dep = DependenciesMap[k]; if (_.contains(dep, k)) { throw new Error('Circular dependency: key: ' + k); } if (dep.length == 0) { HandlerArray.push(getHandler(app, k, PluginsData[k])); } }); async.series(HandlerArray, function (err, end) { if (err) throw err; saveSchemas(app); }); }
javascript
{ "resource": "" }
q35096
train
function( className ) { var c = this.$.className; if ( c ) { var regex = new RegExp( '(?:^|\\s)' + className + '(?:\\s|$)', '' ); if ( !regex.test( c ) ) c += ' ' + className; } this.$.className = c || className; }
javascript
{ "resource": "" }
q35097
train
function( className ) { var c = this.getAttribute( 'class' ); if ( c ) { var regex = new RegExp( '(?:^|\\s+)' + className + '(?=\\s|$)', 'i' ); if ( regex.test( c ) ) { c = c.replace( regex, '' ).replace( /^\s+/, '' ); if ( c ) this.setAttribute( 'class', c ); else this.removeAttribute( 'class' ); } } }
javascript
{ "resource": "" }
q35098
train
function( text ) { CKEDITOR.dom.element.prototype.setText = ( this.$.innerText != undefined ) ? function ( text ) { return this.$.innerText = text; } : function ( text ) { return this.$.textContent = text; }; return this.setText( text ); }
javascript
{ "resource": "" }
q35099
train
function( evaluator ) { var first = this.$.firstChild, retval = first && new CKEDITOR.dom.node( first ); if ( retval && evaluator && !evaluator( retval ) ) retval = retval.getNext( evaluator ); return retval; }
javascript
{ "resource": "" }