_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q20800
train
function ($node) { var $lowerLevel = $node.closest('tr').siblings(); this.stopAjax($lowerLevel.last()); var $animatedNodes = $lowerLevel.last().find('.node').filter(this.isVisibleNode.bind(this)); var isVerticalDesc = $lowerLevel.last().is('.verticalNodes') ? true : false; if (!isVerticalDesc) { $animatedNodes.closest('table').closest('tr').prevAll('.lines').css('visibility', 'hidden'); } this.repaint($animatedNodes.get(0)); $animatedNodes.addClass('sliding slide-up').eq(0).one('transitionend', { 'animatedNodes': $animatedNodes, 'lowerLevel': $lowerLevel, 'isVerticalDesc': isVerticalDesc, 'node': $node }, this.hideChildrenEnd.bind(this)); }
javascript
{ "resource": "" }
q20801
train
function ($node) { var that = this; var $levels = $node.closest('tr').siblings(); var isVerticalDesc = $levels.is('.verticalNodes') ? true : false; var $animatedNodes = isVerticalDesc ? $levels.removeClass('hidden').find('.node').filter(this.isVisibleNode.bind(this)) : $levels.removeClass('hidden').eq(2).children().find('.node:first').filter(this.isVisibleNode.bind(this)); // the two following statements are used to enforce browser to repaint this.repaint($animatedNodes.get(0)); $animatedNodes.addClass('sliding').removeClass('slide-up').eq(0).one('transitionend', { 'node': $node, 'animatedNodes': $animatedNodes }, this.showChildrenEnd.bind(this)); }
javascript
{ "resource": "" }
q20802
train
function ($node, direction) { var that = this; var $nodeContainer = $node.closest('table').parent(); if ($nodeContainer.siblings().find('.spinner').length) { $node.closest('.orgchart').data('inAjax', false); } if (direction) { if (direction === 'left') { $nodeContainer.prevAll().find('.node').filter(this.isVisibleNode.bind(this)).addClass('sliding slide-right'); } else { $nodeContainer.nextAll().find('.node').filter(this.isVisibleNode.bind(this)).addClass('sliding slide-left'); } } else { $nodeContainer.prevAll().find('.node').filter(this.isVisibleNode.bind(this)).addClass('sliding slide-right'); $nodeContainer.nextAll().find('.node').filter(this.isVisibleNode.bind(this)).addClass('sliding slide-left'); } var $animatedNodes = $nodeContainer.siblings().find('.sliding'); var $lines = $animatedNodes.closest('.nodes').prevAll('.lines').css('visibility', 'hidden'); $animatedNodes.eq(0).one('transitionend', { 'node': $node, 'nodeContainer': $nodeContainer, 'direction': direction, 'animatedNodes': $animatedNodes, 'lines': $lines }, this.hideSiblingsEnd.bind(this)); }
javascript
{ "resource": "" }
q20803
train
function ($node, direction) { var that = this; // firstly, show the sibling td tags var $siblings = $(); if (direction) { if (direction === 'left') { $siblings = $node.closest('table').parent().prevAll().removeClass('hidden'); } else { $siblings = $node.closest('table').parent().nextAll().removeClass('hidden'); } } else { $siblings = $node.closest('table').parent().siblings().removeClass('hidden'); } // secondly, show the lines var $upperLevel = $node.closest('table').closest('tr').siblings(); if (direction) { $upperLevel.eq(2).children('.hidden').slice(0, $siblings.length * 2).removeClass('hidden'); } else { $upperLevel.eq(2).children('.hidden').removeClass('hidden'); } // thirdly, do some cleaning stuff if (!this.getNodeState($node, 'parent').visible) { $upperLevel.removeClass('hidden'); var parent = $upperLevel.find('.node')[0]; this.repaint(parent); $(parent).addClass('sliding').removeClass('slide-down').one('transitionend', this.showRelatedParentEnd); } // lastly, show the sibling nodes with animation var $visibleNodes = $siblings.find('.node').filter(this.isVisibleNode.bind(this)); this.repaint($visibleNodes.get(0)); $visibleNodes.addClass('sliding').removeClass('slide-left slide-right'); $visibleNodes.eq(0).one('transitionend', { 'node': $node, 'visibleNodes': $visibleNodes }, this.showSiblingsEnd.bind(this)); }
javascript
{ "resource": "" }
q20804
train
function ($edge) { var $chart = this.$chart; if (typeof $chart.data('inAjax') !== 'undefined' && $chart.data('inAjax') === true) { return false; } $edge.addClass('hidden'); $edge.parent().append('<i class="fa fa-circle-o-notch fa-spin spinner"></i>') .children().not('.spinner').css('opacity', 0.2); $chart.data('inAjax', true); $('.oc-export-btn' + (this.options.chartClass !== '' ? '.' + this.options.chartClass : '')).prop('disabled', true); return true; }
javascript
{ "resource": "" }
q20805
train
function ($edge) { var $node = $edge.parent(); $edge.removeClass('hidden'); $node.find('.spinner').remove(); $node.children().removeAttr('style'); this.$chart.data('inAjax', false); $('.oc-export-btn' + (this.options.chartClass !== '' ? '.' + this.options.chartClass : '')).prop('disabled', false); }
javascript
{ "resource": "" }
q20806
train
function (rel, url, $edge) { var that = this; var opts = this.options; $.ajax({ 'url': url, 'dataType': 'json' }) .done(function (data) { if (that.$chart.data('inAjax')) { if (rel === 'parent') { if (!$.isEmptyObject(data)) { that.addParent($edge.parent(), data); } } else if (rel === 'children') { if (data.children.length) { that.addChildren($edge.parent(), data[rel]); } } else { that.addSiblings($edge.parent(), data.siblings ? data.siblings : data); } } }) .fail(function () { console.log('Failed to get ' + rel + ' data'); }) .always(function () { that.endLoading($edge); }); }
javascript
{ "resource": "" }
q20807
train
function ($appendTo, data) { var that = this; var opts = this.options; var level = 0; if (data.level) { level = data.level; } else { level = data.level = $appendTo.parentsUntil('.orgchart', '.nodes').length + 1; } // Construct the node var childrenData = data.children; var hasChildren = childrenData ? childrenData.length : false; var $nodeWrapper; if (Object.keys(data).length > 2) { var $nodeDiv = this.createNode(data); if (opts.verticalLevel && level >= opts.verticalLevel) { $appendTo.append($nodeDiv); }else { $nodeWrapper = $('<table>'); $appendTo.append($nodeWrapper.append($('<tr/>').append($('<td' + (hasChildren ? ' colspan="' + childrenData.length * 2 + '"' : '') + '></td>').append($nodeDiv)))); } } // Construct the lower level(two "connectiong lines" rows and "inferior nodes" row) if (hasChildren) { var isHidden = (level + 1 > opts.visibleLevel || data.collapsed) ? ' hidden' : ''; var isVerticalLayer = (opts.verticalLevel && (level + 1) >= opts.verticalLevel) ? true : false; var $nodesLayer; if (isVerticalLayer) { $nodesLayer = $('<ul>'); if (isHidden && level + 1 > opts.verticalLevel) { $nodesLayer.addClass(isHidden); } if (level + 1 === opts.verticalLevel) { $appendTo.children('table').append('<tr class="verticalNodes' + isHidden + '"><td></td></tr>') .find('.verticalNodes').children().append($nodesLayer); } else { $appendTo.append($nodesLayer); } } else { var $upperLines = $('<tr class="lines' + isHidden + '"><td colspan="' + childrenData.length * 2 + '"><div class="downLine"></div></td></tr>'); var lowerLines = '<tr class="lines' + isHidden + '"><td class="rightLine"></td>'; for (var i=1; i<childrenData.length; i++) { lowerLines += '<td class="leftLine topLine"></td><td class="rightLine topLine"></td>'; } lowerLines += '<td class="leftLine"></td></tr>'; $nodesLayer = $('<tr class="nodes' + isHidden + '">'); if (Object.keys(data).length === 2) { $appendTo.append($upperLines).append(lowerLines).append($nodesLayer); } else { $nodeWrapper.append($upperLines).append(lowerLines).append($nodesLayer); } } // recurse through children nodes $.each(childrenData, function () { var $nodeCell = isVerticalLayer ? $('<li>') : $('<td colspan="2">'); $nodesLayer.append($nodeCell); this.level = level + 1; that.buildHierarchy($nodeCell, this); }); } }
javascript
{ "resource": "" }
q20808
train
function ($currentRoot, data) { data.relationship = data.relationship || '001'; var $table = $('<table>') .append($('<tr>').append($('<td colspan="2">').append(this.createNode(data)))) .append('<tr class="lines"><td colspan="2"><div class="downLine"></div></td></tr>') .append('<tr class="lines"><td class="rightLine"></td><td class="leftLine"></td></tr>'); this.$chart.prepend($table) .children('table:first').append('<tr class="nodes"><td colspan="2"></td></tr>') .children('tr:last').children().append(this.$chart.children('table').last()); }
javascript
{ "resource": "" }
q20809
train
function ($oneSibling, siblingCount, existingSibligCount) { var lines = ''; for (var i = 0; i < existingSibligCount; i++) { lines += '<td class="leftLine topLine"></td><td class="rightLine topLine"></td>'; } $oneSibling.parent().prevAll('tr:gt(0)').children().attr('colspan', siblingCount * 2) .end().next().children(':first').after(lines); }
javascript
{ "resource": "" }
q20810
train
function ($nodeChart, data) { var newSiblingCount = $.isArray(data) ? data.length : data.children.length; var existingSibligCount = $nodeChart.parent().is('td') ? $nodeChart.closest('tr').children().length : 1; var siblingCount = existingSibligCount + newSiblingCount; var insertPostion = (siblingCount > 1) ? Math.floor(siblingCount/2 - 1) : 0; // just build the sibling nodes for the specific node if ($nodeChart.parent().is('td')) { var $parent = $nodeChart.closest('tr').prevAll('tr:last'); $nodeChart.closest('tr').prevAll('tr:lt(2)').remove(); this.buildChildNode($nodeChart.parent().closest('table'), data); var $siblingTds = $nodeChart.parent().closest('table').children('tr:last').children('td'); if (existingSibligCount > 1) { this.complementLine($siblingTds.eq(0).before($nodeChart.closest('td').siblings().addBack().unwrap()), siblingCount, existingSibligCount); } else { this.complementLine($siblingTds.eq(insertPostion).after($nodeChart.closest('td').unwrap()), siblingCount, 1); } } else { // build the sibling nodes and parent node for the specific ndoe this.buildHierarchy($nodeChart.closest('.orgchart'), data); this.complementLine($nodeChart.next().children('tr:last').children().eq(insertPostion).after($('<td colspan="2">').append($nodeChart)), siblingCount, 1); } }
javascript
{ "resource": "" }
q20811
train
function(element, style) { Object.keys(style).forEach(function(key) { if (key in element.style) { element.style[key] = style[key]; } else if (prefix(key) in element.style) { element.style[prefix(key)] = style[key]; } else { util.warn('No such style property: ' + key); } }); return element; }
javascript
{ "resource": "" }
q20812
setup
train
function setup(opts) { if (GestureDetector.READY) { return; } // find what eventtypes we add listeners to Event.determineEventTypes(); // Register all gestures inside GestureDetector.gestures Utils.each(GestureDetector.gestures, function(gesture) { Detection.register(gesture); }); // Add touch events on the document Event.onTouch(GestureDetector.DOCUMENT, EVENT_MOVE, Detection.detect, opts); Event.onTouch(GestureDetector.DOCUMENT, EVENT_END, Detection.detect, opts); // GestureDetector is ready...! GestureDetector.READY = true; }
javascript
{ "resource": "" }
q20813
on
train
function on(element, type, handler, opt) { util.addEventListener(element, type, handler, opt, true); }
javascript
{ "resource": "" }
q20814
off
train
function off(element, type, handler, opt) { util.removeEventListener(element, type, handler, opt, true); }
javascript
{ "resource": "" }
q20815
inArray
train
function inArray(src, find, deep) { if (deep) { for (var i = 0, len = src.length; i < len; i++) { // Array.findIndex if (Object.keys(find).every(function(key) { return src[i][key] === find[key]; })) { return i; } } return -1; } if (src.indexOf) { return src.indexOf(find); } else { for (var i = 0, len = src.length; i < len; i++) { if (src[i] === find) { return i; } } return -1; } }
javascript
{ "resource": "" }
q20816
getDirection
train
function getDirection(touch1, touch2) { var x = Math.abs(touch1.clientX - touch2.clientX), y = Math.abs(touch1.clientY - touch2.clientY); if (x >= y) { return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN; }
javascript
{ "resource": "" }
q20817
getScale
train
function getScale(start, end) { // need two fingers... if (start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }
javascript
{ "resource": "" }
q20818
getRotation
train
function getRotation(start, end) { // need two fingers if (start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }
javascript
{ "resource": "" }
q20819
setPrefixedCss
train
function setPrefixedCss(element, prop, value, toggle) { var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms']; prop = Utils.toCamelCase(prop); for (var i = 0; i < prefixes.length; i++) { var p = prop; // prefixes if (prefixes[i]) { p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1); } // test the style if (p in element.style) { element.style[p] = (toggle === null || toggle) && value || ''; break; } } }
javascript
{ "resource": "" }
q20820
toggleBehavior
train
function toggleBehavior(element, props, toggle) { if (!props || !element || !element.style) { return; } // set the css properties Utils.each(props, function(value, prop) { Utils.setPrefixedCss(element, prop, value, toggle); }); var falseFn = toggle && function() { return false; }; // also the disable onselectstart if (props.userSelect == 'none') { element.onselectstart = falseFn; } // and disable ondragstart if (props.userDrag == 'none') { element.ondragstart = falseFn; } }
javascript
{ "resource": "" }
q20821
on
train
function on(element, type, handler, opt, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.on(element, type, handler, opt); hook && hook(type); }); }
javascript
{ "resource": "" }
q20822
doDetect
train
function doDetect(ev, eventType, element, handler) { var touchList = this.getTouchList(ev, eventType); var touchListLength = touchList.length; var triggerType = eventType; var triggerChange = touchList.trigger; // used by fakeMultitouch plugin var changedLength = touchListLength; // at each touchstart-like event we want also want to trigger a TOUCH event... if (eventType == EVENT_START) { triggerChange = EVENT_TOUCH; // ...the same for a touchend-like event } else if (eventType == EVENT_END) { triggerChange = EVENT_RELEASE; // keep track of how many touches have been removed changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1); } // after there are still touches on the screen, // we just want to trigger a MOVE event. so change the START or END to a MOVE // but only after detection has been started, the first time we actually want a START if (changedLength > 0 && this.started) { triggerType = EVENT_MOVE; } // detection has been started, we keep track of this, see above this.started = true; // generate some event data, some basic information var evData = this.collectEventData(element, triggerType, touchList, ev); // trigger the triggerType event before the change (TOUCH, RELEASE) events // but the END event should be at last if (eventType != EVENT_END) { handler.call(Detection, evData); } // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed if (triggerChange) { evData.changedLength = changedLength; evData.eventType = triggerChange; handler.call(Detection, evData); evData.eventType = triggerType; delete evData.changedLength; } // trigger the END event if (triggerType == EVENT_END) { handler.call(Detection, evData); // ...and we are done with the detection // so reset everything to start each detection totally fresh this.started = false; } return triggerType; }
javascript
{ "resource": "" }
q20823
getTouchList
train
function getTouchList(ev, eventType) { // get the fake pointerEvent touchlist if (GestureDetector.HAS_POINTEREVENTS) { return PointerEvent.getTouchList(); } // get the touchlist if (ev.touches) { if (eventType == EVENT_MOVE) { return ev.touches; } var identifiers = []; var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches)); var touchList = []; Utils.each(concat, function(touch) { if (Utils.inArray(identifiers, touch.identifier) === -1) { touchList.push(touch); } identifiers.push(touch.identifier); }); return touchList; } // make fake touchList from mouse position ev.identifier = 1; return [ev]; }
javascript
{ "resource": "" }
q20824
train
function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }
javascript
{ "resource": "" }
q20825
getTouchList
train
function getTouchList() { var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Utils.each(this.pointers, function(pointer) { touchlist.push(pointer); }); return touchlist; }
javascript
{ "resource": "" }
q20826
startDetect
train
function startDetect(inst, eventData) { // already busy with a GestureDetector.gesture detection on an element if (this.current) { return; } this.stopped = false; // holds current session this.current = { inst: inst, // reference to GestureDetectorInstance we're working for startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent: false, // last eventData lastCalcEvent: false, // last eventData for calculations. futureCalcEvent: false, // last eventData for calculations. lastCalcData: {}, // last lastCalcData name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }
javascript
{ "resource": "" }
q20827
getCalculatedData
train
function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) { var cur = this.current, recalc = false, calcEv = cur.lastCalcEvent, calcData = cur.lastCalcData; if (calcEv && ev.timeStamp - calcEv.timeStamp > GestureDetector.CALCULATE_INTERVAL) { center = calcEv.center; deltaTime = ev.timeStamp - calcEv.timeStamp; deltaX = ev.center.clientX - calcEv.center.clientX; deltaY = ev.center.clientY - calcEv.center.clientY; recalc = true; } if (ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { cur.futureCalcEvent = ev; } if (!cur.lastCalcEvent || recalc) { calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY); calcData.angle = Utils.getAngle(center, ev.center); calcData.direction = Utils.getDirection(center, ev.center); cur.lastCalcEvent = cur.futureCalcEvent || ev; cur.futureCalcEvent = ev; } ev.velocityX = calcData.velocity.x; ev.velocityY = calcData.velocity.y; ev.interimAngle = calcData.angle; ev.interimDirection = calcData.direction; }
javascript
{ "resource": "" }
q20828
extendEventData
train
function extendEventData(ev) { var cur = this.current, startEv = cur.startEvent, lastEv = cur.lastEvent || startEv; // update the start touchlist to calculate the scale/rotation if (ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { startEv.touches = []; Utils.each(ev.touches, function(touch) { startEv.touches.push({ clientX: touch.clientX, clientY: touch.clientY }); }); } var deltaTime = ev.timeStamp - startEv.timeStamp, deltaX = ev.center.clientX - startEv.center.clientX, deltaY = ev.center.clientY - startEv.center.clientY; this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY); Utils.extend(ev, { startEvent: startEv, deltaTime: deltaTime, deltaX: deltaX, deltaY: deltaY, distance: Utils.getDistance(startEv.center, ev.center), angle: Utils.getAngle(startEv.center, ev.center), direction: Utils.getDirection(startEv.center, ev.center), scale: Utils.getScale(startEv.touches, ev.touches), rotation: Utils.getRotation(startEv.touches, ev.touches) }); return ev; }
javascript
{ "resource": "" }
q20829
train
function(from, to, delay) { function step(params, duration, timing) { if (params.duration !== undefined) { duration = params.duration; } if (params.timing !== undefined) { timing = params.timing; } return { css: params.css || params, duration: duration, timing: timing }; } return this.saveStyle() .queue(step(from, 0, this.defaults.timing)) .wait(delay === undefined ? this.defaults.delay : delay) .queue(step(to, this.defaults.duration, this.defaults.timing)) .restoreStyle(); }
javascript
{ "resource": "" }
q20830
train
function(transition, options) { var queue = this.transitionQueue; if (transition && options) { options.css = transition; transition = new Animit.Transition(options); } if (!(transition instanceof Function || transition instanceof Animit.Transition)) { if (transition.css) { transition = new Animit.Transition(transition); } else { transition = new Animit.Transition({ css: transition }); } } if (transition instanceof Function) { queue.push(transition); } else if (transition instanceof Animit.Transition) { queue.push(transition.build()); } else { throw new Error('Invalid arguments'); } return this; }
javascript
{ "resource": "" }
q20831
train
function(attrs, modifiers) { var attrModifiers = attrs && typeof attrs.modifier === 'string' ? attrs.modifier.trim().split(/ +/) : []; modifiers = angular.isArray(modifiers) ? attrModifiers.concat(modifiers) : attrModifiers; /** * @return {String} template eg. 'ons-button--*', 'ons-button--*__item' * @return {String} */ return function(template) { return modifiers.map(function(modifier) { return template.replace('*', modifier); }).join(' '); }; }
javascript
{ "resource": "" }
q20832
train
function(view, element) { var methods = { hasModifier: function(needle) { var tokens = ModifierUtil.split(element.attr('modifier')); needle = typeof needle === 'string' ? needle.trim() : ''; return ModifierUtil.split(needle).some(function(needle) { return tokens.indexOf(needle) != -1; }); }, removeModifier: function(needle) { needle = typeof needle === 'string' ? needle.trim() : ''; var modifier = ModifierUtil.split(element.attr('modifier')).filter(function(token) { return token !== needle; }).join(' '); element.attr('modifier', modifier); }, addModifier: function(modifier) { element.attr('modifier', element.attr('modifier') + ' ' + modifier); }, setModifier: function(modifier) { element.attr('modifier', modifier); }, toggleModifier: function(modifier) { if (this.hasModifier(modifier)) { this.removeModifier(modifier); } else { this.addModifier(modifier); } } }; for (var method in methods) { if (methods.hasOwnProperty(method)) { view[method] = methods[method]; } } }
javascript
{ "resource": "" }
q20833
train
function(view, template, element) { var _tr = function(modifier) { return template.replace('*', modifier); }; var fns = { hasModifier: function(modifier) { return element.hasClass(_tr(modifier)); }, removeModifier: function(modifier) { element.removeClass(_tr(modifier)); }, addModifier: function(modifier) { element.addClass(_tr(modifier)); }, setModifier: function(modifier) { var classes = element.attr('class').split(/\s+/), patt = template.replace('*', '.'); for (var i = 0; i < classes.length; i++) { var cls = classes[i]; if (cls.match(patt)) { element.removeClass(cls); } } element.addClass(_tr(modifier)); }, toggleModifier: function(modifier) { var cls = _tr(modifier); if (element.hasClass(cls)) { element.removeClass(cls); } else { element.addClass(cls); } } }; var append = function(oldFn, newFn) { if (typeof oldFn !== 'undefined') { return function() { return oldFn.apply(null, arguments) || newFn.apply(null, arguments); }; } else { return newFn; } }; view.hasModifier = append(view.hasModifier, fns.hasModifier); view.removeModifier = append(view.removeModifier, fns.removeModifier); view.addModifier = append(view.addModifier, fns.addModifier); view.setModifier = append(view.setModifier, fns.setModifier); view.toggleModifier = append(view.toggleModifier, fns.toggleModifier); }
javascript
{ "resource": "" }
q20834
train
function(view) { view.hasModifier = view.removeModifier = view.addModifier = view.setModifier = view.toggleModifier = undefined; }
javascript
{ "resource": "" }
q20835
train
function(component, eventNames) { eventNames = eventNames.trim().split(/\s+/); for (var i = 0, l = eventNames.length; i < l; i++) { var eventName = eventNames[i]; this._registerEventHandler(component, eventName); } }
javascript
{ "resource": "" }
q20836
train
function(name, object) { var names = name.split(/\./); function set(container, names, object) { var name; for (var i = 0; i < names.length - 1; i++) { name = names[i]; if (container[name] === undefined || container[name] === null) { container[name] = {}; } container = container[name]; } container[names[names.length - 1]] = object; if (container[names[names.length - 1]] !== object) { throw new Error('Cannot set var="' + object._attrs.var + '" because it will overwrite a read-only variable.'); } } if (ons.componentBase) { set(ons.componentBase, names, object); } var getScope = function(el) { return angular.element(el).data('_scope'); }; var element = object._element[0]; // Current element might not have data('_scope') if (element.hasAttribute('ons-scope')) { set(getScope(element) || object._scope, names, object); element = null; return; } // Ancestors while (element.parentElement) { element = element.parentElement; if (element.hasAttribute('ons-scope')) { set(getScope(element), names, object); element = null; return; } } element = null; // If no ons-scope element was found, attach to $rootScope. set($rootScope, names, object); }
javascript
{ "resource": "" }
q20837
loadPage
train
function loadPage({page, parent, params = {}}, done) { internal.getPageHTMLAsync(page).then(html => { const pageElement = util.createElement(html); parent.appendChild(pageElement); done(pageElement); }); }
javascript
{ "resource": "" }
q20838
rgba
train
function rgba(red, green, blue, alpha){ switch (arguments.length) { case 1: utils.assertColor(red); return red.rgba; case 2: utils.assertColor(red); var color = red.rgba; utils.assertType(green, 'unit', 'alpha'); alpha = green.clone(); if ('%' == alpha.type) alpha.val /= 100; return new nodes.RGBA( color.r , color.g , color.b , alpha.val); default: utils.assertType(red, 'unit', 'red'); utils.assertType(green, 'unit', 'green'); utils.assertType(blue, 'unit', 'blue'); utils.assertType(alpha, 'unit', 'alpha'); var r = '%' == red.type ? Math.round(red.val * 2.55) : red.val , g = '%' == green.type ? Math.round(green.val * 2.55) : green.val , b = '%' == blue.type ? Math.round(blue.val * 2.55) : blue.val; alpha = alpha.clone(); if (alpha && '%' == alpha.type) alpha.val /= 100; return new nodes.RGBA( r , g , b , alpha.val); } }
javascript
{ "resource": "" }
q20839
basename
train
function basename(p, ext){ utils.assertString(p, 'path'); return path.basename(p.val, ext && ext.val); }
javascript
{ "resource": "" }
q20840
operate
train
function operate(op, left, right){ utils.assertType(op, 'string', 'op'); utils.assertPresent(left, 'left'); utils.assertPresent(right, 'right'); return left.operate(op.val, right); }
javascript
{ "resource": "" }
q20841
math
train
function math(n, fn){ utils.assertType(n, 'unit', 'n'); utils.assertString(fn, 'fn'); return new nodes.Unit(Math[fn.string](n.val), n.type); }
javascript
{ "resource": "" }
q20842
Lexer
train
function Lexer(str, options) { options = options || {}; this.stash = []; this.indentStack = []; this.indentRe = null; this.lineno = 1; this.column = 1; // HACK! function comment(str, val, offset, s) { var inComment = s.lastIndexOf('/*', offset) > s.lastIndexOf('*/', offset) , commentIdx = s.lastIndexOf('//', offset) , i = s.lastIndexOf('\n', offset) , double = 0 , single = 0; if (~commentIdx && commentIdx > i) { while (i != offset) { if ("'" == s[i]) single ? single-- : single++; if ('"' == s[i]) double ? double-- : double++; if ('/' == s[i] && '/' == s[i + 1]) { inComment = !single && !double; break; } ++i; } } return inComment ? str : ((val === ',' && /^[,\t\n]+$/.test(str)) ? str.replace(/\n/, '\r') : val + '\r'); }; // Remove UTF-8 BOM. if ('\uFEFF' == str.charAt(0)) str = str.slice(1); this.str = str .replace(/\s+$/, '\n') .replace(/\r\n?/g, '\n') .replace(/\\ *\n/g, '\r') .replace(/([,(:](?!\/\/[^ ])) *(?:\/\/[^\n]*|\/\*.*?\*\/)?\n\s*/g, comment) .replace(/\s*\n[ \t]*([,)])/g, comment); }
javascript
{ "resource": "" }
q20843
train
function(){ var tok , tmp = this.str , buf = []; while ('eos' != (tok = this.next()).type) { buf.push(tok.inspect()); } this.str = tmp; return buf.concat(tok.inspect()).join('\n'); }
javascript
{ "resource": "" }
q20844
train
function(n){ var fetch = n - this.stash.length; while (fetch-- > 0) this.stash.push(this.advance()); return this.stash[--n]; }
javascript
{ "resource": "" }
q20845
train
function(len){ var chunk = len[0]; len = chunk ? chunk.length : len; this.str = this.str.substr(len); if (chunk) { this.move(chunk); } else { this.column += len; } }
javascript
{ "resource": "" }
q20846
train
function(str){ var lines = str.match(/\n/g) , idx = str.lastIndexOf('\n'); if (lines) this.lineno += lines.length; this.column = ~idx ? str.length - idx : this.column + str.length; }
javascript
{ "resource": "" }
q20847
train
function() { var tok = this.stash[this.stash.length - 1] || this.prev; switch (tok && tok.type) { // #for case 'color': return 2 == tok.val.raw.length; // .or case '.': // [is] case '[': return true; } return false; }
javascript
{ "resource": "" }
q20848
train
function() { var column = this.column , line = this.lineno , tok = this.eos() || this.null() || this.sep() || this.keyword() || this.urlchars() || this.comment() || this.newline() || this.escaped() || this.important() || this.literal() || this.anonFunc() || this.atrule() || this.function() || this.brace() || this.paren() || this.color() || this.string() || this.unit() || this.namedop() || this.boolean() || this.unicode() || this.ident() || this.op() || (function () { var token = this.eol(); if (token) { column = token.column; line = token.lineno; } return token; }).call(this) || this.space() || this.selector(); tok.lineno = line; tok.column = column; return tok; }
javascript
{ "resource": "" }
q20849
train
function() { var captures , tok; if (captures = /^(not|and|or|is a|is defined|isnt|is not|is)(?!-)\b([ \t]*)/.exec(this.str)) { var op = captures[1]; this.skip(captures); if (this.isPartOfSelector()) { tok = new Token('ident', new nodes.Ident(captures[0])); } else { op = alias[op] || op; tok = new Token(op, op); } tok.space = captures[2]; return tok; } }
javascript
{ "resource": "" }
q20850
train
function() { var captures; if (captures = /^(true|false)\b([ \t]*)/.exec(this.str)) { var val = nodes.Boolean('true' == captures[1]); this.skip(captures); var tok = new Token('boolean', val); tok.space = captures[2]; return tok; } }
javascript
{ "resource": "" }
q20851
train
function() { var captures, re; // we have established the indentation regexp if (this.indentRe){ captures = this.indentRe.exec(this.str); // figure out if we are using tabs or spaces } else { // try tabs re = /^\n([\t]*)[ \t]*/; captures = re.exec(this.str); // nope, try spaces if (captures && !captures[1].length) { re = /^\n([ \t]*)/; captures = re.exec(this.str); } // established if (captures && captures[1].length) this.indentRe = re; } if (captures) { var tok , indents = captures[1].length; this.skip(captures); if (this.str[0] === ' ' || this.str[0] === '\t') { throw new errors.SyntaxError('Invalid indentation. You can use tabs or spaces to indent, but not both.'); } // Blank line if ('\n' == this.str[0]) return this.advance(); // Outdent if (this.indentStack.length && indents < this.indentStack[0]) { while (this.indentStack.length && this.indentStack[0] > indents) { this.stash.push(new Token('outdent')); this.indentStack.shift(); } tok = this.stash.pop(); // Indent } else if (indents && indents != this.indentStack[0]) { this.indentStack.unshift(indents); tok = new Token('indent'); // Newline } else { tok = new Token('newline'); } return tok; } }
javascript
{ "resource": "" }
q20852
lightness
train
function lightness(color, value){ if (value) { var hslaColor = color.hsla; return hsla( new nodes.Unit(hslaColor.h), new nodes.Unit(hslaColor.s), value, new nodes.Unit(hslaColor.a) ) } return component(color, new nodes.String('lightness')); }
javascript
{ "resource": "" }
q20853
ParseError
train
function ParseError(msg) { this.name = 'ParseError'; this.message = msg; if (Error.captureStackTrace) { Error.captureStackTrace(this, ParseError); } }
javascript
{ "resource": "" }
q20854
blend
train
function blend(top, bottom){ // TODO: different blend modes like overlay etc. utils.assertColor(top); top = top.rgba; bottom = bottom || new nodes.RGBA(255, 255, 255, 1); utils.assertColor(bottom); bottom = bottom.rgba; return new nodes.RGBA( top.r * top.a + bottom.r * (1 - top.a), top.g * top.a + bottom.g * (1 - top.a), top.b * top.a + bottom.b * (1 - top.a), top.a + bottom.a - top.a * bottom.a); }
javascript
{ "resource": "" }
q20855
hue
train
function hue(color, value){ if (value) { var hslaColor = color.hsla; return hsla( value, new nodes.Unit(hslaColor.s), new nodes.Unit(hslaColor.l), new nodes.Unit(hslaColor.a) ) } return component(color, new nodes.String('hue')); }
javascript
{ "resource": "" }
q20856
split
train
function split(delim, val){ utils.assertString(delim, 'delimiter'); utils.assertString(val, 'val'); var splitted = val.string.split(delim.string); var expr = new nodes.Expression(); var ItemNode = val instanceof nodes.Ident ? nodes.Ident : nodes.String; for (var i = 0, len = splitted.length; i < len; ++i) { expr.nodes.push(new ItemNode(splitted[i])); } return expr; }
javascript
{ "resource": "" }
q20857
replace
train
function replace(pattern, replacement, val){ utils.assertString(pattern, 'pattern'); utils.assertString(replacement, 'replacement'); utils.assertString(val, 'val'); pattern = new RegExp(pattern.string, 'g'); var res = val.string.replace(pattern, replacement.string); return val instanceof nodes.Ident ? new nodes.Ident(res) : new nodes.String(res); }
javascript
{ "resource": "" }
q20858
compile
train
function compile() { debug('read %s', cssPath); fs.readFile(stylusPath, 'utf8', function(err, str){ if (err) return error(err); var style = options.compile(str, stylusPath); var paths = style.options._imports = []; imports[stylusPath] = null; style.render(function(err, css){ if (err) return next(err); debug('render %s', stylusPath); imports[stylusPath] = paths; mkdir(dirname(cssPath), { mode: parseInt('0700', 8), recursive: true }, function(err){ if (err) return error(err); fs.writeFile(cssPath, css, 'utf8', next); }); }); }); }
javascript
{ "resource": "" }
q20859
compare
train
function compare(pathA, pathB) { pathA = pathA.split(sep); pathB = pathB.split('/'); if (!pathA[pathA.length - 1]) pathA.pop(); if (!pathB[0]) pathB.shift(); var overlap = []; while (pathA[pathA.length - 1] == pathB[0]) { overlap.push(pathA.pop()); pathB.shift(); } return overlap.join('/'); }
javascript
{ "resource": "" }
q20860
prefixClasses
train
function prefixClasses(prefix, block){ utils.assertString(prefix, 'prefix'); utils.assertType(block, 'block', 'block'); var _prefix = this.prefix; this.options.prefix = this.prefix = prefix.string; block = this.visit(block); this.options.prefix = this.prefix = _prefix; return block; }
javascript
{ "resource": "" }
q20861
use
train
function use(plugin, options){ utils.assertString(plugin, 'plugin'); if (options) { utils.assertType(options, 'object', 'options'); options = parseObject(options); } // lookup plugin = plugin.string; var found = utils.lookup(plugin, this.options.paths, this.options.filename); if (!found) throw new Error('failed to locate plugin file "' + plugin + '"'); // use var fn = require(path.resolve(found)); if ('function' != typeof fn) { throw new Error('plugin "' + plugin + '" does not export a function'); } this.renderer.use(fn(options || this.options)); }
javascript
{ "resource": "" }
q20862
parseObject
train
function parseObject(obj){ obj = obj.vals; for (var key in obj) { var nodes = obj[key].nodes[0].nodes; if (nodes && nodes.length) { obj[key] = []; for (var i = 0, len = nodes.length; i < len; ++i) { obj[key].push(convert(nodes[i])); } } else { obj[key] = convert(obj[key].first); } } return obj; function convert(node){ switch (node.nodeName) { case 'object': return parseObject(node); case 'boolean': return node.isTrue; case 'unit': return node.type ? node.toString() : +node.val; case 'string': case 'literal': return node.val; default: return node.toString(); } } }
javascript
{ "resource": "" }
q20863
Renderer
train
function Renderer(str, options) { options = options || {}; options.globals = options.globals || {}; options.functions = options.functions || {}; options.use = options.use || []; options.use = Array.isArray(options.use) ? options.use : [options.use]; options.imports = [join(__dirname, 'functions')].concat(options.imports || []); options.paths = options.paths || []; options.filename = options.filename || 'stylus'; options.Evaluator = options.Evaluator || Evaluator; this.options = options; this.str = str; this.events = events; }
javascript
{ "resource": "" }
q20864
tan
train
function tan(angle) { utils.assertType(angle, 'unit', 'angle'); var radians = angle.val; if (angle.type === 'deg') { radians *= Math.PI / 180; } var m = Math.pow(10, 9); var sin = Math.round(Math.sin(radians) * m) / m , cos = Math.round(Math.cos(radians) * m) / m , tan = Math.round(m * sin / cos ) / m; return new nodes.Unit(tan, ''); }
javascript
{ "resource": "" }
q20865
dirname
train
function dirname(p){ utils.assertString(p, 'path'); return path.dirname(p.val).replace(/\\/g, '/'); }
javascript
{ "resource": "" }
q20866
range
train
function range(start, stop, step){ utils.assertType(start, 'unit', 'start'); utils.assertType(stop, 'unit', 'stop'); if (step) { utils.assertType(step, 'unit', 'step'); if (0 == step.val) { throw new Error('ArgumentError: "step" argument must not be zero'); } } else { step = new nodes.Unit(1); } var list = new nodes.Expression; for (var i = start.val; i <= stop.val; i += step.val) { list.push(new nodes.Unit(i, start.type)); } return list; }
javascript
{ "resource": "" }
q20867
oldJson
train
function oldJson(json, local, namePrefix){ if (namePrefix) { utils.assertString(namePrefix, 'namePrefix'); namePrefix = namePrefix.val; } else { namePrefix = ''; } local = local ? local.toBoolean() : new nodes.Boolean(local); var scope = local.isTrue ? this.currentScope : this.global.scope; convert(json); return; function convert(obj, prefix){ prefix = prefix ? prefix + '-' : ''; for (var key in obj){ var val = obj[key]; var name = prefix + key; if ('object' == typeof val) { convert(val, name); } else { val = utils.coerce(val); if ('string' == val.nodeName) val = utils.parseString(val.string); scope.add({ name: namePrefix + name, val: val }); } } } }
javascript
{ "resource": "" }
q20868
component
train
function component(color, name) { utils.assertColor(color, 'color'); utils.assertString(name, 'name'); var name = name.string , unit = unitMap[name] , type = typeMap[name] , name = componentMap[name]; if (!name) throw new Error('invalid color component "' + name + '"'); return new nodes.Unit(color[type][name], unit); }
javascript
{ "resource": "" }
q20869
train
function(){ var block = this.parent = this.root; if (Parser.cache.has(this.hash)) { block = Parser.cache.get(this.hash); // normalize cached imports if ('block' == block.nodeName) block.constructor = nodes.Root; } else { while ('eos' != this.peek().type) { this.skipWhitespace(); if ('eos' == this.peek().type) break; var stmt = this.statement(); this.accept(';'); if (!stmt) this.error('unexpected token {peek}, not allowed at the root level'); block.push(stmt); } Parser.cache.set(this.hash, block); } return block; }
javascript
{ "resource": "" }
q20870
train
function(msg){ var type = this.peek().type , val = undefined == this.peek().val ? '' : ' ' + this.peek().toString(); if (val.trim() == type.trim()) val = ''; throw new errors.ParseError(msg.replace('{peek}', '"' + type + val + '"')); }
javascript
{ "resource": "" }
q20871
train
function() { var tok = this.stash.length ? this.stash.pop() : this.lexer.next() , line = tok.lineno , column = tok.column || 1; if (tok.val && tok.val.nodeName) { tok.val.lineno = line; tok.val.column = column; } nodes.lineno = line; nodes.column = column; debug.lexer('%s %s', tok.type, tok.val || ''); return tok; }
javascript
{ "resource": "" }
q20872
train
function(n) { var la = this.lookahead(n).type; switch (la) { case 'for': return this.bracketed; case '[': this.bracketed = true; return true; case ']': this.bracketed = false; return true; default: return ~selectorTokens.indexOf(la); } }
javascript
{ "resource": "" }
q20873
train
function(n){ var val = this.lookahead(n).val; return val && ~pseudoSelectors.indexOf(val.name); }
javascript
{ "resource": "" }
q20874
train
function(type){ var i = 1 , la; while (la = this.lookahead(i++)) { if (~['indent', 'outdent', 'newline', 'eos'].indexOf(la.type)) return; if (type == la.type) return true; } }
javascript
{ "resource": "" }
q20875
train
function() { if (this.isSelectorToken(1)) { if ('{' == this.peek().type) { // unclosed, must be a block if (!this.lineContains('}')) return; // check if ':' is within the braces. // though not required by Stylus, chances // are if someone is using {} they will // use CSS-style props, helping us with // the ambiguity in this case var i = 0 , la; while (la = this.lookahead(++i)) { if ('}' == la.type) { // Check empty block. if (i == 2 || (i == 3 && this.lookahead(i - 1).type == 'space')) return; break; } if (':' == la.type) return; } } return this.next(); } }
javascript
{ "resource": "" }
q20876
train
function(n) { var type = this.lookahead(n).type; if ('=' == type && this.bracketed) return true; return ('ident' == type || 'string' == type) && ']' == this.lookahead(n + 1).type && ('newline' == this.lookahead(n + 2).type || this.isSelectorToken(n + 2)) && !this.lineContains(':') && !this.lineContains('='); }
javascript
{ "resource": "" }
q20877
train
function() { var i = 2 , type; switch (this.lookahead(i).type) { case '{': case 'indent': case ',': return true; case 'newline': while ('unit' == this.lookahead(++i).type || 'newline' == this.lookahead(i).type) ; type = this.lookahead(i).type; return 'indent' == type || '{' == type; } }
javascript
{ "resource": "" }
q20878
train
function() { var stmt = this.stmt() , state = this.prevState , block , op; // special-case statements since it // is not an expression. We could // implement postfix conditionals at // the expression level, however they // would then fail to enclose properties if (this.allowPostfix) { this.allowPostfix = false; state = 'expression'; } switch (state) { case 'assignment': case 'expression': case 'function arguments': while (op = this.accept('if') || this.accept('unless') || this.accept('for')) { switch (op.type) { case 'if': case 'unless': stmt = new nodes.If(this.expression(), stmt); stmt.postfix = true; stmt.negate = 'unless' == op.type; this.accept(';'); break; case 'for': var key , val = this.id().name; if (this.accept(',')) key = this.id().name; this.expect('in'); var each = new nodes.Each(val, key, this.expression()); block = new nodes.Block(this.parent, each); block.push(stmt); each.block = block; stmt = each; } } } return stmt; }
javascript
{ "resource": "" }
q20879
train
function() { var tok = this.peek(), selector; switch (tok.type) { case 'keyframes': return this.keyframes(); case '-moz-document': return this.mozdocument(); case 'comment': case 'selector': case 'literal': case 'charset': case 'namespace': case 'import': case 'require': case 'extend': case 'media': case 'atrule': case 'ident': case 'scope': case 'supports': case 'unless': case 'function': case 'for': case 'if': return this[tok.type](); case 'return': return this.return(); case '{': return this.property(); default: // Contextual selectors if (this.stateAllowsSelector()) { switch (tok.type) { case 'color': case '~': case '>': case '<': case ':': case '&': case '&&': case '[': case '.': case '/': selector = this.selector(); selector.column = tok.column; selector.lineno = tok.lineno; return selector; // relative reference case '..': if ('/' == this.lookahead(2).type) return this.selector(); case '+': return 'function' == this.lookahead(2).type ? this.functionCall() : this.selector(); case '*': return this.property(); // keyframe blocks (10%, 20% { ... }) case 'unit': if (this.looksLikeKeyframe()) { selector = this.selector(); selector.column = tok.column; selector.lineno = tok.lineno; return selector; } case '-': if ('{' == this.lookahead(2).type) return this.property(); } } // Expression fallback var expr = this.expression(); if (expr.isEmpty) this.error('unexpected {peek}'); return expr; } }
javascript
{ "resource": "" }
q20880
train
function() { this.expect('unless'); this.state.push('conditional'); this.cond = true; var node = new nodes.If(this.expression(), true); this.cond = false; node.block = this.block(node, false); this.state.pop(); return node; }
javascript
{ "resource": "" }
q20881
train
function(){ var type = this.expect('atrule').val , node = new nodes.Atrule(type) , tok; this.skipSpacesAndComments(); node.segments = this.selectorParts(); this.skipSpacesAndComments(); tok = this.peek().type; if ('indent' == tok || '{' == tok || ('newline' == tok && '{' == this.lookahead(2).type)) { this.state.push('atrule'); node.block = this.block(node); this.state.pop(); } return node; }
javascript
{ "resource": "" }
q20882
train
function(){ var node = this.supportsNegation() || this.supportsOp(); if (!node) { this.cond = true; node = this.expression(); this.cond = false; } return node; }
javascript
{ "resource": "" }
q20883
train
function(){ if (this.accept('not')) { var node = new nodes.Expression; node.push(new nodes.Literal('not')); node.push(this.supportsFeature()); return node; } }
javascript
{ "resource": "" }
q20884
train
function() { var tok = this.expect('keyframes') , keyframes; this.skipSpacesAndComments(); keyframes = new nodes.Keyframes(this.selectorParts(), tok.val); keyframes.column = tok.column; this.skipSpacesAndComments(); // block this.state.push('atrule'); keyframes.block = this.block(keyframes); this.state.pop(); return keyframes; }
javascript
{ "resource": "" }
q20885
train
function() { var arr , group = new nodes.Group , scope = this.selectorScope , isRoot = 'root' == this.currentState() , selector; do { // Clobber newline after , this.accept('newline'); arr = this.selectorParts(); // Push the selector if (isRoot && scope) arr.unshift(new nodes.Literal(scope + ' ')); if (arr.length) { selector = new nodes.Selector(arr); selector.lineno = arr[0].lineno; selector.column = arr[0].column; group.push(selector); } } while (this.accept(',') || this.accept('newline')); if ('selector-parts' == this.currentState()) return group.nodes; this.state.push('selector'); group.block = this.block(group); this.state.pop(); return group; }
javascript
{ "resource": "" }
q20886
train
function() { var parens = 1 , i = 2 , tok; // Lookahead and determine if we are dealing // with a function call or definition. Here // we pair parens to prevent false negatives out: while (tok = this.lookahead(i++)) { switch (tok.type) { case 'function': case '(': ++parens; break; case ')': if (!--parens) break out; break; case 'eos': this.error('failed to find closing paren ")"'); } } // Definition or call switch (this.currentState()) { case 'expression': return this.functionCall(); default: return this.looksLikeFunctionDefinition(i) ? this.functionDefinition() : this.expression(); } }
javascript
{ "resource": "" }
q20887
train
function() { var tok , node , params = new nodes.Params; while (tok = this.accept('ident')) { this.accept('space'); params.push(node = tok.val); if (this.accept('...')) { node.rest = true; } else if (this.accept('=')) { node.val = this.expression(); } this.skipWhitespace(); this.accept(','); this.skipWhitespace(); } return params; }
javascript
{ "resource": "" }
q20888
train
function() { var node = this.unary(); if (this.accept('is defined')) { if (!node) this.error('illegal unary "is defined", missing left-hand operand'); node = new nodes.BinOp('is defined', node); } return node; }
javascript
{ "resource": "" }
q20889
adjust
train
function adjust(color, prop, amount){ utils.assertColor(color, 'color'); utils.assertString(prop, 'prop'); utils.assertType(amount, 'unit', 'amount'); var hsl = color.hsla.clone(); prop = { hue: 'h', saturation: 's', lightness: 'l' }[prop.string]; if (!prop) throw new Error('invalid adjustment property'); var val = amount.val; if ('%' == amount.type){ val = 'l' == prop && val > 0 ? (100 - hsl[prop]) * val / 100 : hsl[prop] * (val / 100); } hsl[prop] += val; return hsl.rgba; }
javascript
{ "resource": "" }
q20890
green
train
function green(color, value){ color = color.rgba; if (value) { return rgba( new nodes.Unit(color.r), value, new nodes.Unit(color.b), new nodes.Unit(color.a) ); } return new nodes.Unit(color.g, ''); }
javascript
{ "resource": "" }
q20891
transparentify
train
function transparentify(top, bottom, alpha){ utils.assertColor(top); top = top.rgba; // Handle default arguments bottom = bottom || new nodes.RGBA(255, 255, 255, 1); if (!alpha && bottom && !bottom.rgba) { alpha = bottom; bottom = new nodes.RGBA(255, 255, 255, 1); } utils.assertColor(bottom); bottom = bottom.rgba; var bestAlpha = ['r', 'g', 'b'].map(function(channel){ return (top[channel] - bottom[channel]) / ((0 < (top[channel] - bottom[channel]) ? 255 : 0) - bottom[channel]); }).sort(function(a, b){return b - a;})[0]; if (alpha) { utils.assertType(alpha, 'unit', 'alpha'); if ('%' == alpha.type) { bestAlpha = alpha.val / 100; } else if (!alpha.type) { bestAlpha = alpha = alpha.val; } } bestAlpha = Math.max(Math.min(bestAlpha, 1), 0); // Calculate the resulting color function processChannel(channel) { if (0 == bestAlpha) { return bottom[channel] } else { return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha } } return new nodes.RGBA( processChannel('r'), processChannel('g'), processChannel('b'), Math.round(bestAlpha * 100) / 100 ); }
javascript
{ "resource": "" }
q20892
processChannel
train
function processChannel(channel) { if (0 == bestAlpha) { return bottom[channel] } else { return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha } }
javascript
{ "resource": "" }
q20893
selectorExists
train
function selectorExists(sel) { utils.assertString(sel, 'selector'); if (!this.__selectorsMap__) { var Normalizer = require('../visitor/normalizer') , visitor = new Normalizer(this.root.clone()); visitor.visit(visitor.root); this.__selectorsMap__ = visitor.map; } return sel.string in this.__selectorsMap__; }
javascript
{ "resource": "" }
q20894
remove
train
function remove(object, key){ utils.assertType(object, 'object', 'object'); utils.assertString(key, 'key'); delete object.vals[key.string]; return object; }
javascript
{ "resource": "" }
q20895
CoercionError
train
function CoercionError(msg) { this.name = 'CoercionError' this.message = msg if (Error.captureStackTrace) { Error.captureStackTrace(this, CoercionError); } }
javascript
{ "resource": "" }
q20896
train
function(op, right){ switch (op) { case 'is a': if ('string' == right.first.nodeName) { return nodes.Boolean(this.nodeName == right.val); } else { throw new Error('"is a" expects a string, got ' + right.toString()); } case '==': return nodes.Boolean(this.hash == right.hash); case '!=': return nodes.Boolean(this.hash != right.hash); case '>=': return nodes.Boolean(this.hash >= right.hash); case '<=': return nodes.Boolean(this.hash <= right.hash); case '>': return nodes.Boolean(this.hash > right.hash); case '<': return nodes.Boolean(this.hash < right.hash); case '||': return this.toBoolean().isTrue ? this : right; case 'in': var vals = utils.unwrap(right).nodes , len = vals && vals.length , hash = this.hash; if (!vals) throw new Error('"in" given invalid right-hand operand, expecting an expression'); // 'prop' in obj if (1 == len && 'object' == vals[0].nodeName) { return nodes.Boolean(vals[0].has(this.hash)); } for (var i = 0; i < len; ++i) { if (hash == vals[i].hash) { return nodes.true; } } return nodes.false; case '&&': var a = this.toBoolean() , b = right.toBoolean(); return a.isTrue && b.isTrue ? right : a.isFalse ? this : right; default: if ('[]' == op) { var msg = 'cannot perform ' + this + '[' + right + ']'; } else { var msg = 'cannot perform' + ' ' + this + ' ' + op + ' ' + right; } throw new Error(msg); } }
javascript
{ "resource": "" }
q20897
Converter
train
function Converter(css) { var parse = require('css-parse'); this.css = css; this.root = parse(css, { position: false }); this.indents = 0; }
javascript
{ "resource": "" }
q20898
hsla
train
function hsla(hue, saturation, lightness, alpha){ switch (arguments.length) { case 1: utils.assertColor(hue); return hue.hsla; case 2: utils.assertColor(hue); var color = hue.hsla; utils.assertType(saturation, 'unit', 'alpha'); var alpha = saturation.clone(); if ('%' == alpha.type) alpha.val /= 100; return new nodes.HSLA( color.h , color.s , color.l , alpha.val); default: utils.assertType(hue, 'unit', 'hue'); utils.assertType(saturation, 'unit', 'saturation'); utils.assertType(lightness, 'unit', 'lightness'); utils.assertType(alpha, 'unit', 'alpha'); var alpha = alpha.clone(); if (alpha && '%' == alpha.type) alpha.val /= 100; return new nodes.HSLA( hue.val , saturation.val , lightness.val , alpha.val); } }
javascript
{ "resource": "" }
q20899
rgb
train
function rgb(red, green, blue){ switch (arguments.length) { case 1: utils.assertColor(red); var color = red.rgba; return new nodes.RGBA( color.r , color.g , color.b , 1); default: return rgba( red , green , blue , new nodes.Unit(1)); } }
javascript
{ "resource": "" }