_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q25900 | inclination | train | function inclination( vector ) {
return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
} | javascript | {
"resource": ""
} |
q25901 | _mergeListInfo | train | function _mergeListInfo(list) {
var arr = [];
var info = {};
for(var i=0,len=list.length; i<len; i++) {
arr.push('<li data-value="'+list[i].value+'">' + list[i].name + '</li>');
info[i] = list[i].list ? _mergeListInfo(list[i].list) : {length: 0};
}
info.length = i;
info.content = arr.join('');
return info;
} | javascript | {
"resource": ""
} |
q25902 | Redis | train | function Redis(nsp){
Adapter.call(this, nsp);
this.uid = uid;
this.prefix = prefix;
this.requestsTimeout = requestsTimeout;
this.channel = prefix + '#' + nsp.name + '#';
this.requestChannel = prefix + '-request#' + this.nsp.name + '#';
this.responseChannel = prefix + '-response#' + this.nsp.name + '#';
this.requests = {};
this.customHook = function(data, cb){ cb(null); }
if (String.prototype.startsWith) {
this.channelMatches = function (messageChannel, subscribedChannel) {
return messageChannel.startsWith(subscribedChannel);
}
} else { // Fallback to other impl for older Node.js
this.channelMatches = function (messageChannel, subscribedChannel) {
return messageChannel.substr(0, subscribedChannel.length) === subscribedChannel;
}
}
this.pubClient = pub;
this.subClient = sub;
var self = this;
sub.psubscribe(this.channel + '*', function(err){
if (err) self.emit('error', err);
});
sub.on('pmessageBuffer', this.onmessage.bind(this));
sub.subscribe([this.requestChannel, this.responseChannel], function(err){
if (err) self.emit('error', err);
});
sub.on('messageBuffer', this.onrequest.bind(this));
function onError(err) {
self.emit('error', err);
}
pub.on('error', onError);
sub.on('error', onError);
} | javascript | {
"resource": ""
} |
q25903 | Dummy | train | function Dummy() {
"use strict";
this.colorize = function colorize(text, styleName, pad) {
return text;
};
this.format = function format(text, style, pad){
return text;
};
} | javascript | {
"resource": ""
} |
q25904 | generateClassName | train | function generateClassName(classname) {
"use strict";
classname = (classname || "").replace(phantom.casperPath, "").trim();
var script = classname || phantom.casperScript || "";
if (script.indexOf(fs.workingDirectory) === 0) {
script = script.substring(fs.workingDirectory.length + 1);
}
if (script.indexOf('/') === 0) {
script = script.substring(1, script.length);
}
if (~script.indexOf('.')) {
script = script.substring(0, script.lastIndexOf('.'));
}
// If we have trimmed our string down to nothing, default to script name
if (!script && phantom.casperScript) {
script = phantom.casperScript;
}
return script || "unknown";
} | javascript | {
"resource": ""
} |
q25905 | printHelp | train | function printHelp() {
/* global slimer */
var engine = phantom.casperEngine === 'slimerjs' ? slimer : phantom;
var version = [engine.version.major, engine.version.minor, engine.version.patch].join('.');
return __terminate([
'CasperJS version ' + phantom.casperVersion.toString() +
' at ' + phantom.casperPath + ', using ' + phantom.casperEngine + ' version ' + version,
fs.read(fs.pathJoin(phantom.casperPath, 'bin', 'usage.txt'))
].join('\n'));
} | javascript | {
"resource": ""
} |
q25906 | check | train | function check() {
if (links[currentLink] && currentLink < upTo) {
this.echo('--- Link ' + currentLink + ' ---');
start.call(this, links[currentLink]);
addLinks.call(this, links[currentLink]);
currentLink++;
this.run(check);
} else {
this.echo("All done.");
this.exit();
}
} | javascript | {
"resource": ""
} |
q25907 | castArgument | train | function castArgument(arg) {
"use strict";
if (arg.match(/^-?\d+$/)) {
return parseInt(arg, 10);
} else if (arg.match(/^-?\d+\.\d+$/)) {
return parseFloat(arg);
} else if (arg.match(/^(true|false)$/i)) {
return arg.trim().toLowerCase() === "true" ? true : false;
} else {
return arg;
}
} | javascript | {
"resource": ""
} |
q25908 | betterTypeOf | train | function betterTypeOf(input) {
"use strict";
switch (input) {
case undefined:
return 'undefined';
case null:
return 'null';
default:
try {
var type = Object.prototype.toString.call(input).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
if (type === 'object' &&
phantom.casperEngine !== "phantomjs" &&
'__type' in input) {
type = input.__type;
}
// gecko returns window instead of domwindow
else if (type === 'window') {
return 'domwindow';
}
return type;
} catch (e) {
return typeof input;
}
}
} | javascript | {
"resource": ""
} |
q25909 | betterInstanceOf | train | function betterInstanceOf(input, constructor) {
"use strict";
/*eslint eqeqeq:0 */
if (typeof input == 'undefined' || input == null) {
return false;
}
var inputToTest = input;
while (inputToTest != null) {
if (inputToTest == constructor.prototype) {
return true;
}
if (typeof inputToTest == 'xml') {
return constructor.prototype == document.prototype;
}
if (typeof inputToTest == 'undefined') {
return false;
}
inputToTest = inputToTest.__proto__;
}
return equals(input.constructor.name, constructor.name);
} | javascript | {
"resource": ""
} |
q25910 | cleanUrl | train | function cleanUrl(url) {
"use strict";
if (url.toLowerCase().indexOf('http') !== 0) {
return url;
}
var a = document.createElement('a');
a.href = url;
return a.href;
} | javascript | {
"resource": ""
} |
q25911 | computeModifier | train | function computeModifier(modifierString, modifiers) {
"use strict";
var modifier = 0,
checkKey = function(key) {
if (key in modifiers) return;
throw new CasperError(format('%s is not a supported key modifier', key));
};
if (!modifierString) return modifier;
var keys = modifierString.split('+');
keys.forEach(checkKey);
return keys.reduce(function(acc, key) {
return acc | modifiers[key];
}, modifier);
} | javascript | {
"resource": ""
} |
q25912 | equals | train | function equals(v1, v2) {
"use strict";
if (isFunction(v1)) {
return v1.toString() === v2.toString();
}
// with Gecko, instanceof is not enough to test object
if (v1 instanceof Object || isObject(v1)) {
if (!(v2 instanceof Object || isObject(v2)) ||
Object.keys(v1).length !== Object.keys(v2).length) {
return false;
}
for (var k in v1) {
if (!equals(v1[k], v2[k])) {
return false;
}
}
return true;
}
return v1 === v2;
} | javascript | {
"resource": ""
} |
q25913 | fillBlanks | train | function fillBlanks(text, pad) {
"use strict";
pad = pad || 80;
if (text.length < pad) {
text += new Array(pad - text.length + 1).join(' ');
}
return text;
} | javascript | {
"resource": ""
} |
q25914 | getPropertyPath | train | function getPropertyPath(obj, path) {
"use strict";
if (!isObject(obj) || !isString(path)) {
return undefined;
}
var value = obj;
path.split('.').forEach(function(property) {
if (typeof value === "object" && property in value) {
value = value[property];
} else {
value = undefined;
}
});
return value;
} | javascript | {
"resource": ""
} |
q25915 | indent | train | function indent(string, nchars, prefix) {
"use strict";
return string.split('\n').map(function(line) {
return (prefix || '') + new Array(nchars).join(' ') + line;
}).join('\n');
} | javascript | {
"resource": ""
} |
q25916 | isClipRect | train | function isClipRect(value) {
"use strict";
return isType(value, "cliprect") || (
isObject(value) &&
isNumber(value.top) && isNumber(value.left) &&
isNumber(value.width) && isNumber(value.height)
);
} | javascript | {
"resource": ""
} |
q25917 | isType | train | function isType(what, typeName) {
"use strict";
if (typeof typeName !== "string" || !typeName) {
throw new CasperError("You must pass isType() a typeName string");
}
return betterTypeOf(what).toLowerCase() === typeName.toLowerCase();
} | javascript | {
"resource": ""
} |
q25918 | isValidSelector | train | function isValidSelector(value) {
"use strict";
if (isString(value)) {
try {
// phantomjs env has a working document object, let's use it
document.querySelector(value);
} catch(e) {
if ('name' in e && (e.name === 'SYNTAX_ERR' || e.name === 'SyntaxError')) {
return false;
}
}
return true;
} else if (isObject(value)) {
if (!value.hasOwnProperty('type')) {
return false;
}
if (!value.hasOwnProperty('path')) {
return false;
}
if (['css', 'xpath'].indexOf(value.type) === -1) {
return false;
}
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q25919 | mergeObjectsInGecko | train | function mergeObjectsInGecko(origin, add, opts) {
"use strict";
var options = opts || {},
keepReferences = options.keepReferences;
for (var p in add) {
if (isPlainObject(add[p])) {
if (isPlainObject(origin[p])) {
origin[p] = mergeObjects(origin[p], add[p]);
} else {
origin[p] = keepReferences ? add[p] : clone(add[p]);
}
} else {
// if a property is only a getter, we could have a Javascript error
// in strict mode "TypeError: setting a property that has only a getter"
// when setting the value to the new object (gecko 25+).
// To avoid it, let's define the property on the new object, do not set
// directly the value
var prop = Object.getOwnPropertyDescriptor(add, p);
if (prop.get && !prop.set) {
Object.defineProperty(origin, p, prop);
}
else {
origin[p] = add[p];
}
}
}
return origin;
} | javascript | {
"resource": ""
} |
q25920 | serialize | train | function serialize(value, indent) {
"use strict";
if (isArray(value)) {
value = value.map(function _map(prop) {
return isFunction(prop) ? prop.toString().replace(/\s{2,}/, '') : prop;
});
}
return JSON.stringify(value, null, indent);
} | javascript | {
"resource": ""
} |
q25921 | unique | train | function unique(array) {
"use strict";
var o = {},
r = [];
for (var i = 0, len = array.length; i !== len; i++) {
var d = array[i];
if (typeof o[d] === "undefined") {
o[d] = 1;
r[r.length] = d;
}
}
return r;
} | javascript | {
"resource": ""
} |
q25922 | versionToString | train | function versionToString(version) {
if (isObject(version)) {
try {
return [version.major, version.minor, version.patch].join('.');
} catch (e) {}
}
return version;
} | javascript | {
"resource": ""
} |
q25923 | matchEngine | train | function matchEngine(matchSpec) {
if (Array !== matchSpec.constructor) {
matchSpec = [matchSpec];
}
var idx;
var len = matchSpec.length;
var engineName = phantom.casperEngine;
var engineVersion = phantom.version;
for (idx = 0; idx < len; ++idx) {
var match = matchSpec[idx];
var version = match.version;
var min = version && version.min;
var max = version && version.max;
if ('*' === min) {
min = null;
}
if ('*' === max) {
max = null;
}
if (match.name === engineName &&
(!min || gteVersion(engineVersion, min)) &&
(!max || !ltVersion(max, engineVersion))
) {
return match;
}
}
return false;
} | javascript | {
"resource": ""
} |
q25924 | schedule | train | function schedule(expression, func, options) {
let task = createTask(expression, func, options);
storage.save(task);
return task;
} | javascript | {
"resource": ""
} |
q25925 | getImageNaturalSizes | train | function getImageNaturalSizes(image, callback) {
var newImage = document.createElement('img');
// Modern browsers (except Safari)
if (image.naturalWidth && !IS_SAFARI) {
callback(image.naturalWidth, image.naturalHeight);
return newImage;
}
var body = document.body || document.documentElement;
newImage.onload = function () {
callback(newImage.width, newImage.height);
if (!IS_SAFARI) {
body.removeChild(newImage);
}
};
newImage.src = image.src;
// iOS Safari will convert the image automatically
// with its orientation once append it into DOM
if (!IS_SAFARI) {
newImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';
body.appendChild(newImage);
}
return newImage;
} | javascript | {
"resource": ""
} |
q25926 | onViewed | train | function onViewed() {
var imageData = _this.imageData;
title.textContent = alt + ' (' + imageData.naturalWidth + ' \xD7 ' + imageData.naturalHeight + ')';
} | javascript | {
"resource": ""
} |
q25927 | prev | train | function prev() {
var loop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var index = this.index - 1;
if (index < 0) {
index = loop ? this.length - 1 : 0;
}
this.view(index);
return this;
} | javascript | {
"resource": ""
} |
q25928 | next | train | function next() {
var loop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var maxIndex = this.length - 1;
var index = this.index + 1;
if (index > maxIndex) {
index = loop ? 0 : maxIndex;
}
this.view(index);
return this;
} | javascript | {
"resource": ""
} |
q25929 | move | train | function move(offsetX, offsetY) {
var imageData = this.imageData;
this.moveTo(isUndefined(offsetX) ? offsetX : imageData.left + Number(offsetX), isUndefined(offsetY) ? offsetY : imageData.top + Number(offsetY));
return this;
} | javascript | {
"resource": ""
} |
q25930 | moveTo | train | function moveTo(x) {
var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;
var imageData = this.imageData;
x = Number(x);
y = Number(y);
if (this.viewed && !this.played && this.options.movable) {
var changed = false;
if (isNumber(x)) {
imageData.left = x;
changed = true;
}
if (isNumber(y)) {
imageData.top = y;
changed = true;
}
if (changed) {
this.renderImage();
}
}
return this;
} | javascript | {
"resource": ""
} |
q25931 | zoom | train | function zoom(ratio) {
var hasTooltip = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var _originalEvent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var imageData = this.imageData;
ratio = Number(ratio);
if (ratio < 0) {
ratio = 1 / (1 - ratio);
} else {
ratio = 1 + ratio;
}
this.zoomTo(imageData.width * ratio / imageData.naturalWidth, hasTooltip, _originalEvent);
return this;
} | javascript | {
"resource": ""
} |
q25932 | zoomTo | train | function zoomTo(ratio) {
var hasTooltip = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var _originalEvent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var _zoomable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var options = this.options,
pointers = this.pointers,
imageData = this.imageData;
ratio = Math.max(0, ratio);
if (isNumber(ratio) && this.viewed && !this.played && (_zoomable || options.zoomable)) {
if (!_zoomable) {
var minZoomRatio = Math.max(0.01, options.minZoomRatio);
var maxZoomRatio = Math.min(100, options.maxZoomRatio);
ratio = Math.min(Math.max(ratio, minZoomRatio), maxZoomRatio);
}
if (_originalEvent && ratio > 0.95 && ratio < 1.05) {
ratio = 1;
}
var newWidth = imageData.naturalWidth * ratio;
var newHeight = imageData.naturalHeight * ratio;
if (_originalEvent) {
var offset = getOffset(this.viewer);
var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {
pageX: _originalEvent.pageX,
pageY: _originalEvent.pageY
};
// Zoom from the triggering point of the event
imageData.left -= (newWidth - imageData.width) * ((center.pageX - offset.left - imageData.left) / imageData.width);
imageData.top -= (newHeight - imageData.height) * ((center.pageY - offset.top - imageData.top) / imageData.height);
} else {
// Zoom from the center of the image
imageData.left -= (newWidth - imageData.width) / 2;
imageData.top -= (newHeight - imageData.height) / 2;
}
imageData.width = newWidth;
imageData.height = newHeight;
imageData.ratio = ratio;
this.renderImage();
if (hasTooltip) {
this.tooltip();
}
}
return this;
} | javascript | {
"resource": ""
} |
q25933 | rotateTo | train | function rotateTo(degree) {
var imageData = this.imageData;
degree = Number(degree);
if (isNumber(degree) && this.viewed && !this.played && this.options.rotatable) {
imageData.rotate = degree;
this.renderImage();
}
return this;
} | javascript | {
"resource": ""
} |
q25934 | scale | train | function scale(scaleX) {
var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;
var imageData = this.imageData;
scaleX = Number(scaleX);
scaleY = Number(scaleY);
if (this.viewed && !this.played && this.options.scalable) {
var changed = false;
if (isNumber(scaleX)) {
imageData.scaleX = scaleX;
changed = true;
}
if (isNumber(scaleY)) {
imageData.scaleY = scaleY;
changed = true;
}
if (changed) {
this.renderImage();
}
}
return this;
} | javascript | {
"resource": ""
} |
q25935 | play | train | function play() {
var _this2 = this;
var fullscreen = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!this.isShown || this.played) {
return this;
}
var options = this.options,
player = this.player;
var onLoad = this.loadImage.bind(this);
var list = [];
var total = 0;
var index = 0;
this.played = true;
this.onLoadWhenPlay = onLoad;
if (fullscreen) {
this.requestFullscreen();
}
addClass(player, CLASS_SHOW);
forEach(this.items, function (item, i) {
var img = item.querySelector('img');
var image = document.createElement('img');
image.src = getData(img, 'originalUrl');
image.alt = img.getAttribute('alt');
total += 1;
addClass(image, CLASS_FADE);
toggleClass(image, CLASS_TRANSITION, options.transition);
if (hasClass(item, CLASS_ACTIVE)) {
addClass(image, CLASS_IN);
index = i;
}
list.push(image);
addListener(image, EVENT_LOAD, onLoad, {
once: true
});
player.appendChild(image);
});
if (isNumber(options.interval) && options.interval > 0) {
var play = function play() {
_this2.playing = setTimeout(function () {
removeClass(list[index], CLASS_IN);
index += 1;
index = index < total ? index : 0;
addClass(list[index], CLASS_IN);
play();
}, options.interval);
};
if (total > 1) {
play();
}
}
return this;
} | javascript | {
"resource": ""
} |
q25936 | tooltip | train | function tooltip() {
var _this6 = this;
var options = this.options,
tooltipBox = this.tooltipBox,
imageData = this.imageData;
if (!this.viewed || this.played || !options.tooltip) {
return this;
}
tooltipBox.textContent = Math.round(imageData.ratio * 100) + '%';
if (!this.tooltipping) {
if (options.transition) {
if (this.fading) {
dispatchEvent(tooltipBox, EVENT_TRANSITION_END);
}
addClass(tooltipBox, CLASS_SHOW);
addClass(tooltipBox, CLASS_FADE);
addClass(tooltipBox, CLASS_TRANSITION);
// Force reflow to enable CSS3 transition
// eslint-disable-next-line
tooltipBox.offsetWidth;
addClass(tooltipBox, CLASS_IN);
} else {
addClass(tooltipBox, CLASS_SHOW);
}
} else {
clearTimeout(this.tooltipping);
}
this.tooltipping = setTimeout(function () {
if (options.transition) {
addListener(tooltipBox, EVENT_TRANSITION_END, function () {
removeClass(tooltipBox, CLASS_SHOW);
removeClass(tooltipBox, CLASS_FADE);
removeClass(tooltipBox, CLASS_TRANSITION);
_this6.fading = false;
}, {
once: true
});
removeClass(tooltipBox, CLASS_IN);
_this6.fading = true;
} else {
removeClass(tooltipBox, CLASS_SHOW);
}
_this6.tooltipping = false;
}, 1000);
return this;
} | javascript | {
"resource": ""
} |
q25937 | update | train | function update() {
var element = this.element,
options = this.options,
isImg = this.isImg;
// Destroy viewer if the target image was deleted
if (isImg && !element.parentNode) {
return this.destroy();
}
var images = [];
forEach(isImg ? [element] : element.querySelectorAll('img'), function (image) {
if (options.filter) {
if (options.filter(image)) {
images.push(image);
}
} else {
images.push(image);
}
});
if (!images.length) {
return this;
}
this.images = images;
this.length = images.length;
if (this.ready) {
var indexes = [];
forEach(this.items, function (item, i) {
var img = item.querySelector('img');
var image = images[i];
if (image) {
if (image.src !== img.src) {
indexes.push(i);
}
} else {
indexes.push(i);
}
});
setStyle(this.list, {
width: 'auto'
});
this.initList();
if (this.isShown) {
if (this.length) {
if (this.viewed) {
var index = indexes.indexOf(this.index);
if (index >= 0) {
this.viewed = false;
this.view(Math.max(this.index - (index + 1), 0));
} else {
addClass(this.items[this.index], CLASS_ACTIVE);
}
}
} else {
this.image = null;
this.viewed = false;
this.index = 0;
this.imageData = null;
this.canvas.innerHTML = '';
this.title.innerHTML = '';
}
}
} else {
this.build();
}
return this;
} | javascript | {
"resource": ""
} |
q25938 | destroy | train | function destroy() {
var element = this.element,
options = this.options;
if (!getData(element, NAMESPACE)) {
return this;
}
this.destroyed = true;
if (this.ready) {
if (this.played) {
this.stop();
}
if (options.inline) {
if (this.fulled) {
this.exit();
}
this.unbind();
} else if (this.isShown) {
if (this.viewing) {
if (this.imageRendering) {
this.imageRendering.abort();
} else if (this.imageInitializing) {
this.imageInitializing.abort();
}
}
if (this.hiding) {
this.transitioning.abort();
}
this.hidden();
} else if (this.showing) {
this.transitioning.abort();
this.hidden();
}
this.ready = false;
this.viewer.parentNode.removeChild(this.viewer);
} else if (options.inline) {
if (this.delaying) {
this.delaying.abort();
} else if (this.initializing) {
this.initializing.abort();
}
}
if (!options.inline) {
removeListener(element, EVENT_CLICK, this.onStart);
}
removeData(element, NAMESPACE);
return this;
} | javascript | {
"resource": ""
} |
q25939 | Viewer | train | function Viewer(element) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Viewer);
if (!element || element.nodeType !== 1) {
throw new Error('The first argument is required and must be an element.');
}
this.element = element;
this.options = assign({}, DEFAULTS, isPlainObject(options) && options);
this.action = false;
this.fading = false;
this.fulled = false;
this.hiding = false;
this.index = 0;
this.isImg = false;
this.length = 0;
this.played = false;
this.playing = false;
this.pointers = {};
this.ready = false;
this.showing = false;
this.timeout = false;
this.tooltipping = false;
this.viewed = false;
this.viewing = false;
this.isShown = false;
this.wheeling = false;
this.init();
} | javascript | {
"resource": ""
} |
q25940 | read | train | function read(element) {
// normalized style
var style = {
alignContent: 'stretch',
alignItems: 'stretch',
alignSelf: 'auto',
borderBottomStyle: 'none',
borderBottomWidth: 0,
borderLeftStyle: 'none',
borderLeftWidth: 0,
borderRightStyle: 'none',
borderRightWidth: 0,
borderTopStyle: 'none',
borderTopWidth: 0,
boxSizing: 'content-box',
display: 'inline',
flexBasis: 'auto',
flexDirection: 'row',
flexGrow: 0,
flexShrink: 1,
flexWrap: 'nowrap',
justifyContent: 'flex-start',
height: 'auto',
marginTop: 0,
marginRight: 0,
marginLeft: 0,
marginBottom: 0,
paddingTop: 0,
paddingRight: 0,
paddingLeft: 0,
paddingBottom: 0,
maxHeight: 'none',
maxWidth: 'none',
minHeight: 0,
minWidth: 0,
order: 0,
position: 'static',
width: 'auto'
};
// whether element is an element
var isElement = element instanceof Element;
if (isElement) {
// whether element has data-style attribute
var hasDataStyleAttr = element.hasAttribute('data-style');
// inline style from data-style or style
var inlineStyle = hasDataStyleAttr ? element.getAttribute('data-style') : element.getAttribute('style') || '';
if (!hasDataStyleAttr) {
// copy style to data-style
element.setAttribute('data-style', inlineStyle);
}
// append computed style to style
var computedStyle = window.getComputedStyle && getComputedStyle(element) || {};
appendComputedStyle(style, computedStyle);
// append current style to style
var currentStyle = element.currentStyle || {};
appendCurrentStyle(style, currentStyle);
// append inline style to style
appendInlineStyle(style, inlineStyle);
// for each camel-case property
for (var prop in style) {
style[prop] = getComputedLength(style, prop, element);
}
// offset measurements
var boundingClientRect = element.getBoundingClientRect();
style.offsetHeight = boundingClientRect.height || element.offsetHeight;
style.offsetWidth = boundingClientRect.width || element.offsetWidth;
}
var details = {
element: element,
style: style
};
return details;
} | javascript | {
"resource": ""
} |
q25941 | fitPreviewToContent | train | function fitPreviewToContent() {
var iframeDoc = preview.contentDocument || preview.contentWindow.document;
setPreviewHeight(iframeDoc.body.offsetHeight);
} | javascript | {
"resource": ""
} |
q25942 | postEmbedHeightToViewer | train | function postEmbedHeightToViewer() {
var newHeight = document.getElementById('tabinterface').clientHeight;
if (newHeight < MIN_IFRAME_HEIGHT) {
console.log('embed height too small, reset height to 100px');
newHeight = MIN_IFRAME_HEIGHT;
}
// Tell the viewer about the new size
window.parent.postMessage({
sentinel: 'amp',
type: 'embed-size',
height: newHeight
}, '*');
} | javascript | {
"resource": ""
} |
q25943 | offlineImage | train | function offlineImage(name, width, height) {
return
`<?xml version="1.0"?>
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg" version="1.1">
<g fill="none" fill-rule="evenodd"><path fill="#F8BBD0" d="M0 0h${width}v${height}H0z"/></g>
<text text-anchor="middle" x="${Math.floor(width / 2)}" y="${Math.floor(height / 2)}">image offline (${name})</text>
<style><![CDATA[
text{
font: 48px Roboto,Verdana, Helvetica, Arial, sans-serif;
}
]]></style>
</svg>`;
} | javascript | {
"resource": ""
} |
q25944 | onMessageReceivedSubscriptionState | train | function onMessageReceivedSubscriptionState() {
let retrievedPushSubscription = null;
self.registration.pushManager.getSubscription()
.then(pushSubscription => {
retrievedPushSubscription = pushSubscription;
if (!pushSubscription) {
return null;
} else {
return self.registration.pushManager.permissionState(
pushSubscription.options
);
}
}).then(permissionStateOrNull => {
if (permissionStateOrNull == null) {
broadcastReply(WorkerMessengerCommand.AMP_SUBSCRIPTION_STATE, false);
} else {
const isSubscribed = !!retrievedPushSubscription &&
permissionStateOrNull === 'granted';
broadcastReply(WorkerMessengerCommand.AMP_SUBSCRIPTION_STATE,
isSubscribed);
}
});
} | javascript | {
"resource": ""
} |
q25945 | persistSubscriptionLocally | train | function persistSubscriptionLocally(subscription) {
let subscriptionJSON = JSON.stringify(subscription);
idb.open('web-push-db', 1).then(db => {
let tx = db.transaction(['web-push-subcription'], 'readwrite');
tx.objectStore('web-push-subcription').put({
id: 1,
data: subscriptionJSON
});
return tx.complete;
});
} | javascript | {
"resource": ""
} |
q25946 | urlB64ToUint8Array | train | function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = self.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
} | javascript | {
"resource": ""
} |
q25947 | generateEmbeds | train | function generateEmbeds(config) {
glob(config.src + '/**/*.html', {}, (err, files) => {
files.forEach(file => generateEmbed(config, file));
});
} | javascript | {
"resource": ""
} |
q25948 | generateEmbed | train | function generateEmbed(config, file) {
const targetPath = path.join(config.destDir, path.relative(config.src, file));
const document = parseDocument(file);
const sampleSections = document.sections.filter(
s => s.inBody && !s.isEmptyCodeSection()
);
sampleSections.forEach((section, index) => {
highlight(section.codeSnippet()).then(code => {
const tag = section.doc ? slug(section.doc.toLowerCase()) : index;
const context = {
sample: {
file: path.basename(targetPath),
preview: addFlag(targetPath, tag, 'preview'),
embed: addFlag(targetPath, tag, 'embed'),
template: addFlag(targetPath, tag, 'template'),
body: section.code,
code: code,
},
config: config,
document: document,
};
generate(context.sample.preview, templates.preview, context, /* minify */ true);
generate(context.sample.embed, templates.embed, context, /* minify */ true);
generateTemplate(context);
});
});
} | javascript | {
"resource": ""
} |
q25949 | highlight | train | function highlight(code) {
return new Promise((resolve, reject) => {
pygmentize({ lang: 'html', format: 'html' }, code, function (err, result) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(result.toString());
};
});
});
} | javascript | {
"resource": ""
} |
q25950 | generate | train | function generate(file, template, context, minifyResult) {
let string = template.render(context, {
'styles.css': templates.styles,
'embed.js': templates.embedJs
});
if (minifyResult) {
string = minify(string, {
caseSensitive: true,
collapseWhitespace: true,
html5: true,
minifyCSS: true,
minifyJS: true,
removeComments: true,
removeAttributeQuotes: true
});
};
writeFile(path.join(context.config.destRoot, file), string);
} | javascript | {
"resource": ""
} |
q25951 | addFlag | train | function addFlag() {
const filename = arguments[0];
const postfix = [].slice.call(arguments, 1).join('.');
return filename.replace('.html', '.' + postfix + '.html');
} | javascript | {
"resource": ""
} |
q25952 | generateTemplate | train | function generateTemplate(context) {
let _page;
let _phantom;
phantom.create([], { logLevel: 'error' }).then(function (ph) {
_phantom = ph;
ph.createPage()
.then(page => {
_page = page;
const url = path.join(context.config.destRoot, context.sample.embed);
return _page.property('viewportSize', {width: 1024, height: 768})
.then(() => _page.open(url) );
})
.then(status => {
return _page.evaluate(function() {
const element = document.querySelector('#source-panel');
const height = element.getBoundingClientRect().top + element.offsetHeight;
return height;
});
})
.then(height => {
context.sample.height = height;
generate(context.sample.template, templates.template, context);
})
.then(() => {
_page.close();
_phantom.exit();
})
.catch(err => console.log(err));
});
} | javascript | {
"resource": ""
} |
q25953 | UTF8Decoder | train | function UTF8Decoder(options) {
var fatal = options.fatal;
var /** @type {number} */ utf8_code_point = 0,
/** @type {number} */ utf8_bytes_needed = 0,
/** @type {number} */ utf8_bytes_seen = 0,
/** @type {number} */ utf8_lower_boundary = 0;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte) {
if (utf8_bytes_needed !== 0) {
return decoderError(fatal);
}
return EOF_code_point;
}
byte_pointer.offset(1);
if (utf8_bytes_needed === 0) {
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (inRange(bite, 0xC2, 0xDF)) {
utf8_bytes_needed = 1;
utf8_lower_boundary = 0x80;
utf8_code_point = bite - 0xC0;
} else if (inRange(bite, 0xE0, 0xEF)) {
utf8_bytes_needed = 2;
utf8_lower_boundary = 0x800;
utf8_code_point = bite - 0xE0;
} else if (inRange(bite, 0xF0, 0xF4)) {
utf8_bytes_needed = 3;
utf8_lower_boundary = 0x10000;
utf8_code_point = bite - 0xF0;
} else {
return decoderError(fatal);
}
utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
return null;
}
if (!inRange(bite, 0x80, 0xBF)) {
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
byte_pointer.offset(-1);
return decoderError(fatal);
}
utf8_bytes_seen += 1;
utf8_code_point = utf8_code_point + (bite - 0x80) *
Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
if (utf8_bytes_seen !== utf8_bytes_needed) {
return null;
}
var code_point = utf8_code_point;
var lower_boundary = utf8_lower_boundary;
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
if (inRange(code_point, lower_boundary, 0x10FFFF) &&
!inRange(code_point, 0xD800, 0xDFFF)) {
return code_point;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25954 | GBKDecoder | train | function GBKDecoder(gb18030, options) {
var fatal = options.fatal;
var /** @type {number} */ gbk_first = 0x00,
/** @type {number} */ gbk_second = 0x00,
/** @type {number} */ gbk_third = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && gbk_first === 0x00 &&
gbk_second === 0x00 && gbk_third === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte &&
(gbk_first !== 0x00 || gbk_second !== 0x00 || gbk_third !== 0x00)) {
gbk_first = 0x00;
gbk_second = 0x00;
gbk_third = 0x00;
decoderError(fatal);
}
byte_pointer.offset(1);
var code_point;
if (gbk_third !== 0x00) {
code_point = null;
if (inRange(bite, 0x30, 0x39)) {
code_point = indexGB18030CodePointFor(
(((gbk_first - 0x81) * 10 + (gbk_second - 0x30)) * 126 +
(gbk_third - 0x81)) * 10 + bite - 0x30);
}
gbk_first = 0x00;
gbk_second = 0x00;
gbk_third = 0x00;
if (code_point === null) {
byte_pointer.offset(-3);
return decoderError(fatal);
}
return code_point;
}
if (gbk_second !== 0x00) {
if (inRange(bite, 0x81, 0xFE)) {
gbk_third = bite;
return null;
}
byte_pointer.offset(-2);
gbk_first = 0x00;
gbk_second = 0x00;
return decoderError(fatal);
}
if (gbk_first !== 0x00) {
if (inRange(bite, 0x30, 0x39) && gb18030) {
gbk_second = bite;
return null;
}
var lead = gbk_first;
var pointer = null;
gbk_first = 0x00;
var offset = bite < 0x7F ? 0x40 : 0x41;
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) {
pointer = (lead - 0x81) * 190 + (bite - offset);
}
code_point = pointer === null ? null :
indexCodePointFor(pointer, indexes['gbk']);
if (pointer === null) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (bite === 0x80) {
return 0x20AC;
}
if (inRange(bite, 0x81, 0xFE)) {
gbk_first = bite;
return null;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25955 | HZGB2312Decoder | train | function HZGB2312Decoder(options) {
var fatal = options.fatal;
var /** @type {boolean} */ hzgb2312 = false,
/** @type {number} */ hzgb2312_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && hzgb2312_lead === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte && hzgb2312_lead !== 0x00) {
hzgb2312_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (hzgb2312_lead === 0x7E) {
hzgb2312_lead = 0x00;
if (bite === 0x7B) {
hzgb2312 = true;
return null;
}
if (bite === 0x7D) {
hzgb2312 = false;
return null;
}
if (bite === 0x7E) {
return 0x007E;
}
if (bite === 0x0A) {
return null;
}
byte_pointer.offset(-1);
return decoderError(fatal);
}
if (hzgb2312_lead !== 0x00) {
var lead = hzgb2312_lead;
hzgb2312_lead = 0x00;
var code_point = null;
if (inRange(bite, 0x21, 0x7E)) {
code_point = indexCodePointFor((lead - 1) * 190 +
(bite + 0x3F), indexes['gbk']);
}
if (bite === 0x0A) {
hzgb2312 = false;
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (bite === 0x7E) {
hzgb2312_lead = 0x7E;
return null;
}
if (hzgb2312) {
if (inRange(bite, 0x20, 0x7F)) {
hzgb2312_lead = bite;
return null;
}
if (bite === 0x0A) {
hzgb2312 = false;
}
return decoderError(fatal);
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25956 | Big5Decoder | train | function Big5Decoder(options) {
var fatal = options.fatal;
var /** @type {number} */ big5_lead = 0x00,
/** @type {?number} */ big5_pending = null;
/**
* @param {ByteInputStream} byte_pointer The byte steram to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
// NOTE: Hack to support emitting two code points
if (big5_pending !== null) {
var pending = big5_pending;
big5_pending = null;
return pending;
}
var bite = byte_pointer.get();
if (bite === EOF_byte && big5_lead === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte && big5_lead !== 0x00) {
big5_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (big5_lead !== 0x00) {
var lead = big5_lead;
var pointer = null;
big5_lead = 0x00;
var offset = bite < 0x7F ? 0x40 : 0x62;
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) {
pointer = (lead - 0x81) * 157 + (bite - offset);
}
if (pointer === 1133) {
big5_pending = 0x0304;
return 0x00CA;
}
if (pointer === 1135) {
big5_pending = 0x030C;
return 0x00CA;
}
if (pointer === 1164) {
big5_pending = 0x0304;
return 0x00EA;
}
if (pointer === 1166) {
big5_pending = 0x030C;
return 0x00EA;
}
var code_point = (pointer === null) ? null :
indexCodePointFor(pointer, indexes['big5']);
if (pointer === null) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (inRange(bite, 0x81, 0xFE)) {
big5_lead = bite;
return null;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25957 | EUCJPDecoder | train | function EUCJPDecoder(options) {
var fatal = options.fatal;
var /** @type {number} */ eucjp_first = 0x00,
/** @type {number} */ eucjp_second = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte) {
if (eucjp_first === 0x00 && eucjp_second === 0x00) {
return EOF_code_point;
}
eucjp_first = 0x00;
eucjp_second = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
var lead, code_point;
if (eucjp_second !== 0x00) {
lead = eucjp_second;
eucjp_second = 0x00;
code_point = null;
if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1,
indexes['jis0212']);
}
if (!inRange(bite, 0xA1, 0xFE)) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (eucjp_first === 0x8E && inRange(bite, 0xA1, 0xDF)) {
eucjp_first = 0x00;
return 0xFF61 + bite - 0xA1;
}
if (eucjp_first === 0x8F && inRange(bite, 0xA1, 0xFE)) {
eucjp_first = 0x00;
eucjp_second = bite;
return null;
}
if (eucjp_first !== 0x00) {
lead = eucjp_first;
eucjp_first = 0x00;
code_point = null;
if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1,
indexes['jis0208']);
}
if (!inRange(bite, 0xA1, 0xFE)) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (bite === 0x8E || bite === 0x8F || (inRange(bite, 0xA1, 0xFE))) {
eucjp_first = bite;
return null;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25958 | ShiftJISDecoder | train | function ShiftJISDecoder(options) {
var fatal = options.fatal;
var /** @type {number} */ shiftjis_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && shiftjis_lead === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte && shiftjis_lead !== 0x00) {
shiftjis_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (shiftjis_lead !== 0x00) {
var lead = shiftjis_lead;
shiftjis_lead = 0x00;
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) {
var offset = (bite < 0x7F) ? 0x40 : 0x41;
var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1;
var code_point = indexCodePointFor((lead - lead_offset) * 188 +
bite - offset, indexes['jis0208']);
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
byte_pointer.offset(-1);
return decoderError(fatal);
}
if (inRange(bite, 0x00, 0x80)) {
return bite;
}
if (inRange(bite, 0xA1, 0xDF)) {
return 0xFF61 + bite - 0xA1;
}
if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) {
shiftjis_lead = bite;
return null;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25959 | EUCKRDecoder | train | function EUCKRDecoder(options) {
var fatal = options.fatal;
var /** @type {number} */ euckr_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && euckr_lead === 0) {
return EOF_code_point;
}
if (bite === EOF_byte && euckr_lead !== 0) {
euckr_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (euckr_lead !== 0x00) {
var lead = euckr_lead;
var pointer = null;
euckr_lead = 0x00;
if (inRange(lead, 0x81, 0xC6)) {
var temp = (26 + 26 + 126) * (lead - 0x81);
if (inRange(bite, 0x41, 0x5A)) {
pointer = temp + bite - 0x41;
} else if (inRange(bite, 0x61, 0x7A)) {
pointer = temp + 26 + bite - 0x61;
} else if (inRange(bite, 0x81, 0xFE)) {
pointer = temp + 26 + 26 + bite - 0x81;
}
}
if (inRange(lead, 0xC7, 0xFD) && inRange(bite, 0xA1, 0xFE)) {
pointer = (26 + 26 + 126) * (0xC7 - 0x81) + (lead - 0xC7) * 94 +
(bite - 0xA1);
}
var code_point = (pointer === null) ? null :
indexCodePointFor(pointer, indexes['euc-kr']);
if (pointer === null) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (inRange(bite, 0x81, 0xFD)) {
euckr_lead = bite;
return null;
}
return decoderError(fatal);
};
} | javascript | {
"resource": ""
} |
q25960 | UTF16Decoder | train | function UTF16Decoder(utf16_be, options) {
var fatal = options.fatal;
var /** @type {?number} */ utf16_lead_byte = null,
/** @type {?number} */ utf16_lead_surrogate = null;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && utf16_lead_byte === null &&
utf16_lead_surrogate === null) {
return EOF_code_point;
}
if (bite === EOF_byte && (utf16_lead_byte !== null ||
utf16_lead_surrogate !== null)) {
return decoderError(fatal);
}
byte_pointer.offset(1);
if (utf16_lead_byte === null) {
utf16_lead_byte = bite;
return null;
}
var code_point;
if (utf16_be) {
code_point = (utf16_lead_byte << 8) + bite;
} else {
code_point = (bite << 8) + utf16_lead_byte;
}
utf16_lead_byte = null;
if (utf16_lead_surrogate !== null) {
var lead_surrogate = utf16_lead_surrogate;
utf16_lead_surrogate = null;
if (inRange(code_point, 0xDC00, 0xDFFF)) {
return 0x10000 + (lead_surrogate - 0xD800) * 0x400 +
(code_point - 0xDC00);
}
byte_pointer.offset(-2);
return decoderError(fatal);
}
if (inRange(code_point, 0xD800, 0xDBFF)) {
utf16_lead_surrogate = code_point;
return null;
}
if (inRange(code_point, 0xDC00, 0xDFFF)) {
return decoderError(fatal);
}
return code_point;
};
} | javascript | {
"resource": ""
} |
q25961 | train | function () {
var scopes = fs.readdirSync('./test_scopes').filter(function (filename) {
return filename[0] !== '.';
});
var config = {
options: {
color: false,
interactive: false
}
};
// Create a sub config for each test scope
for (var idx in scopes) {
var scope = scopes[idx];
config['test_scopes_' + scope] = {
options: {
cwd: 'test_scopes/' + scope,
production: false
}
};
}
return config;
} | javascript | {
"resource": ""
} | |
q25962 | train | function () {
angular.forEach(translateAttr, function (translationId, attributeName) {
if (!translationId) {
return;
}
previousAttributes[attributeName] = true;
// if translation id starts with '.' and translateNamespace given, prepend namespace
if (scope.translateNamespace && translationId.charAt(0) === '.') {
translationId = scope.translateNamespace + translationId;
}
$translate(translationId, translateValues, attr.translateInterpolation, undefined, scope.translateLanguage, translateSanitizeStrategy)
.then(function (translation) {
element.attr(attributeName, translation);
}, function (translationId) {
element.attr(attributeName, translationId);
});
});
// Removing unused attributes that were previously used
angular.forEach(previousAttributes, function (flag, attributeName) {
if (!translateAttr[attributeName]) {
element.removeAttr(attributeName);
delete previousAttributes[attributeName];
}
});
} | javascript | {
"resource": ""
} | |
q25963 | train | function () {
return $http(
angular.extend({
method : 'GET',
url : self.parseUrl(self.urlTemplate || urlTemplate, lang)
},
$httpOptions)
);
} | javascript | {
"resource": ""
} | |
q25964 | train | function() {
ws = new SockJS(location.pathname.split("index")[0] + 'socket');
ws.onopen = function() {
console.log("CONNECTED");
if (!inIframe) {
document.getElementById("footer").innerHTML = "<font color='#494'>"+ibmfoot+"</font>";
}
ws.send(JSON.stringify({action:"connected"}));
onoffline();
};
ws.onclose = function() {
console.log("DISCONNECTED");
if (!inIframe) {
document.getElementById("footer").innerHTML = "<font color='#900'>"+ibmfoot+"</font>";
}
setTimeout(function() { connect(); }, 2500);
};
ws.onmessage = function(e) {
var data = JSON.parse(e.data);
//console.log("DATA" typeof data,data);
if (Array.isArray(data)) {
//console.log("ARRAY");
// map.closePopup();
// var bnds= L.latLngBounds([0,0]);
for (var prop in data) {
if (data[prop].command) { doCommand(data[prop].command); delete data[prop].command; }
if (data[prop].hasOwnProperty("name")) {
setMarker(data[prop]);
// bnds.extend(markers[data[prop].name].getLatLng());
}
else { console.log("SKIP A",data[prop]); }
}
// map.fitBounds(bnds.pad(0.25));
}
else {
if (data.command) { doCommand(data.command); delete data.command; }
if (data.hasOwnProperty("name")) { setMarker(data); }
else if (data.hasOwnProperty("type")) { doGeojson(data); }
else {
console.log("SKIP",data);
// if (typeof data === "string") { doDialog(data); }
// else { console.log("SKIP",data); }
}
}
};
} | javascript | {
"resource": ""
} | |
q25965 | doTidyUp | train | function doTidyUp(l) {
var d = parseInt(Date.now()/1000);
for (var m in markers) {
if ((l && (l == markers[m].lay)) || typeof markers[m].ts != "undefined") {
if ((l && (l == markers[m].lay)) || (markers[m].hasOwnProperty("ts") && (Number(markers[m].ts) < d) && (markers[m].lay !== "_drawing"))) {
//console.log("STALE :",m);
layers[markers[m].lay].removeLayer(markers[m]);
if (typeof polygons[m] != "undefined") {
layers[markers[m].lay].removeLayer(polygons[m]);
delete polygons[m];
}
if (typeof polygons[m+"_"] != "undefined") {
layers[polygons[m+"_"].lay].removeLayer(polygons[m+"_"]);
delete polygons[m+"_"];
}
delete markers[m];
}
}
}
if (l) {
if (layers[l]) { map.removeLayer(layers[l]); layercontrol.removeLayer(layers[l]); delete layers[l]; }
if (overlays[l]) { map.removeLayer(overlays[l]); layercontrol.removeLayer(overlays[l]); delete overlays[l]; }
}
} | javascript | {
"resource": ""
} |
q25966 | doSearch | train | function doSearch() {
var value = document.getElementById('search').value;
marks = [];
marksIndex = 0;
for (var key in markers) {
if ( (~(key.toLowerCase()).indexOf(value.toLowerCase())) && (mb.contains(markers[key].getLatLng()))) {
marks.push(markers[key]);
}
if (markers[key].icon === value) {
marks.push(markers[key]);
}
}
moveToMarks();
if (marks.length === 0) {
// If no markers found let's try a geolookup...
var protocol = location.protocol;
if (protocol == "file:") { protocol = "https:"; }
var searchUrl = protocol + "//nominatim.openstreetmap.org/search?format=json&limit=1&q=";
fetch(searchUrl + value) // Call the fetch function passing the url of the API as a parameter
.then(function(resp) { return resp.json(); })
.then(function(data) {
if (data.length > 0) {
var bb = data[0].boundingbox;
map.fitBounds([ [bb[0],bb[2]], [bb[1],bb[3]] ]);
map.panTo([data[0].lat, data[0].lon]);
}
else {
document.getElementById('searchResult').innerHTML = " <font color='#ff0'>Not Found</font>";
}
})
.catch(function(err) {
if (err.toString() === "TypeError: Failed to fetch") {
document.getElementById('searchResult').innerHTML = " <font color='#ff0'>Not Found</font>";
}
});
}
else {
if (lockit) {
document.getElementById('searchResult').innerHTML = " <font color='#ff0'>Found "+marks.length+" results within bounds.</font>";
} else {
document.getElementById('searchResult').innerHTML = " <font color='#ff0'>Found "+marks.length+" results.</font>";
}
}
} | javascript | {
"resource": ""
} |
q25967 | moveToMarks | train | function moveToMarks() {
if (marks.length > marksIndex) {
var m = marks[marksIndex];
map.setView(m.getLatLng(), map.getZoom());
m.openPopup();
marksIndex++;
setTimeout(moveToMarks, 2500);
}
} | javascript | {
"resource": ""
} |
q25968 | clearSearch | train | function clearSearch() {
var value = document.getElementById('search').value;
marks = [];
marksIndex = 0;
for (var key in markers) {
if ( (~(key.toLowerCase()).indexOf(value.toLowerCase())) && (mb.contains(markers[key].getLatLng()))) {
marks.push(markers[key]);
}
}
removeMarks();
if (lockit) {
document.getElementById('searchResult').innerHTML = "";
}
else {
document.getElementById('searchResult').innerHTML = "";
}
} | javascript | {
"resource": ""
} |
q25969 | setMarker | train | function setMarker(data) {
var rightmenu = function(m) {
// customise right click context menu
var rightcontext = "";
if (polygons[data.name] == undefined) {
rightcontext = "<button id='delbutton' onclick='delMarker(\""+data.name+"\",true);'>Delete</button>";
}
else if (data.editable) {
rightcontext = "<button onclick='editPoly(\""+data.name+"\",true);'>Edit</button><button onclick='delMarker(\""+data.name+"\",true);'>Delete</button>";
}
if ((data.contextmenu !== undefined) && (typeof data.contextmenu === "string")) {
rightcontext = data.contextmenu.replace(/\$name/g,data.name);
delete data.contextmenu;
}
if (rightcontext.length > 0) {
var rightmenuMarker = L.popup({offset:[0,-12]}).setContent("<b>"+data.name+"</b><br/>"+rightcontext);
if (hiderightclick !== true) {
m.on('contextmenu', function(e) {
L.DomEvent.stopPropagation(e);
rightmenuMarker.setLatLng(e.latlng);
map.openPopup(rightmenuMarker);
});
}
}
return m;
}
//console.log("DATA" typeof data, data);
if (data.deleted) { // remove markers we are told to
delMarker(data.name);
return;
}
var ll;
var lli = null;
var opt = {};
opt.color = data.color || "#910000";
opt.fillColor = data.fillColor || "#910000";
opt.stroke = (data.hasOwnProperty("stroke")) ? data.stroke : true;
opt.weight = data.weight || 2;
opt.opacity = data.opacity || 1;
opt.fillOpacity = data.fillOpacity || 0.2;
opt.clickable = (data.hasOwnProperty("clickable")) ? data.clickable : false;
opt.fill = (data.hasOwnProperty("fill")) ? data.fill : true;
if (data.hasOwnProperty("dashArray")) { opt.dashArray = data.dashArray; }
// Replace building
if (data.hasOwnProperty("building")) {
if ((data.building === "") && layers.hasOwnProperty("buildings")) {
map.removeLayer(layers["buildings"]);
layercontrol._update();
layers["buildings"] = overlays["buildings"].set("");
return;
}
//layers["buildings"] = new OSMBuildings(map).set(data.building);
layers["buildings"] = overlays["buildings"].set(data.building);
map.addLayer(layers["buildings"]);
return;
}
var lay = data.layer || "unknown";
if (!data.hasOwnProperty("action") || data.action.indexOf("layer") === -1) {
if (typeof layers[lay] == "undefined") { // add layer if if doesn't exist
if (clusterAt > 0) {
layers[lay] = new L.MarkerClusterGroup({
maxClusterRadius:50,
spiderfyDistanceMultiplier:1.8,
disableClusteringAtZoom:clusterAt
//zoomToBoundsOnClick:false
});
}
else {
layers[lay] = new L.LayerGroup();
}
overlays[lay] = layers[lay];
if (showLayerMenu !== false) {
layercontrol.addOverlay(layers[lay],lay);
}
map.addLayer(overlays[lay]);
//console.log("ADDED LAYER",lay,layers);
}
if (!allData.hasOwnProperty(data.name)) { allData[data.name] = {}; }
delete data.action;
Object.keys(data).forEach(key => {
if (data[key] == null) { delete allData[data.name][key]; }
else { allData[data.name][key] = data[key]; }
});
data = Object.assign({},allData[data.name]);
}
delete data.action;
if (typeof markers[data.name] != "undefined") {
if (markers[data.name].lay !== data.layer) {
delMarker(data.name);
}
else {
try {layers[lay].removeLayer(markers[data.name]); }
catch(e) { console.log("OOPS"); }
}
}
if (typeof polygons[data.name] != "undefined") { layers[lay].removeLayer(polygons[data.name]); }
if (data.hasOwnProperty("line") && Array.isArray(data.line)) {
delete opt.fill;
if (!data.hasOwnProperty("weight")) { opt.weight = 3; } //Standard settings different for lines
if (!data.hasOwnProperty("opacity")) { opt.opacity = 0.8; }
var polyln = L.polyline(data.line, opt);
polygons[data.name] = polyln;
}
else if (data.hasOwnProperty("area") && Array.isArray(data.area)) {
var polyarea;
if (data.area.length === 2) { polyarea = L.rectangle(data.area, opt); }
else { polyarea = L.polygon(data.area, opt); }
polygons[data.name] = polyarea;
}
else if (data.hasOwnProperty("sdlat") && data.hasOwnProperty("sdlon")) {
if (!data.hasOwnProperty("iconColor")) { opt.color = "blue"; } //different standard Color Settings
if (!data.hasOwnProperty("fillColor")) { opt.fillColor = "blue"; }
var ellipse = L.ellipse(new L.LatLng((data.lat*1), (data.lon*1)), [200000*data.sdlon*Math.cos(data.lat*Math.PI/180), 200000*data.sdlat], 0, opt);
polygons[data.name] = ellipse;
}
else if (data.hasOwnProperty("radius")) {
if (data.hasOwnProperty("lat") && data.hasOwnProperty("lon")) {
var polycirc;
if (Array.isArray(data.radius)) {
polycirc = L.ellipse(new L.LatLng((data.lat*1), (data.lon*1)), [data.radius[0]*Math.cos(data.lat*Math.PI/180), data.radius[1]], data.tilt || 0, opt);
}
else {
polycirc = L.circle(new L.LatLng((data.lat*1), (data.lon*1)), data.radius*1, opt);
}
polygons[data.name] = polycirc;
}
}
if (polygons[data.name] !== undefined) {
polygons[data.name].lay = lay;
if (opt.clickable) {
var words = "<b>"+data.name+"</b>";
if (data.popup) { var words = words + "<br/>" + data.popup; }
polygons[data.name].bindPopup(words, {autoClose:false, closeButton:true, closeOnClick:false, minWidth:200});
}
polygons[data.name] = rightmenu(polygons[data.name]);
layers[lay].addLayer(polygons[data.name]);
}
else {
if (typeof data.coordinates == "object") { ll = new L.LatLng(data.coordinates[1],data.coordinates[0]); }
else if (data.hasOwnProperty("position") && data.position.hasOwnProperty("lat") && data.position.hasOwnProperty("lon")) {
data.lat = data.position.lat*1;
data.lon = data.position.lon*1;
data.alt = data.position.alt;
if (parseFloat(data.position.alt) == data.position.alt) { data.alt = data.position.alt + " m"; }
delete data.position;
ll = new L.LatLng((data.lat*1), (data.lon*1));
}
else if (data.hasOwnProperty("lat") && data.hasOwnProperty("lon")) { ll = new L.LatLng((data.lat*1), (data.lon*1)); }
else if (data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude")) { ll = new L.LatLng((data.latitude*1), (data.longitude*1)); }
else { console.log("No location:",data); return; }
// Adding new L.LatLng object (lli) when optional intensity value is defined. Only for use in heatmap layer
if (typeof data.coordinates == "object") { lli = new L.LatLng(data.coordinates[2],data.coordinates[1],data.coordinates[0]); }
else if (data.hasOwnProperty("lat") && data.hasOwnProperty("lon") && data.hasOwnProperty("intensity")) { lli = new L.LatLng((data.lat*1), (data.lon*1), (data.intensity*1)); }
else if (data.hasOwnProperty("latitude") && data.hasOwnProperty("longitude") && data.hasOwnProperty("intensity")) { lli = new L.LatLng((data.latitude*1), (data.longitude*1), (data.intensity*1)); }
else { lli = ll }
// Create the icons... handle plane, car, ship, wind, earthquake as specials
var marker, myMarker;
var icon, q;
var words="";
var labelOffset = [12,0];
var drag = false;
if (data.draggable === true) { drag = true; }
//console.log("ICON",data.icon);
if (data.hasOwnProperty("icon")) {
if (data.icon === "ship") {
marker = L.boatMarker(ll, {
title: data.name,
color: (data.iconColor || "blue")
});
marker.setHeading(parseFloat(data.hdg || data.bearing || "0"));
q = 'https://www.bing.com/images/search?q='+data.icon+'%20%2B"'+encodeURIComponent(data.name)+'"';
words += '<a href=\''+q+'\' target="_thingpic">Pictures</a><br>';
}
else if (data.icon === "plane") {
data.iconColor = data.iconColor || "black";
if (data.hasOwnProperty("squawk")) { data.iconColor = "red"; }
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="310px" height="310px" viewBox="0 0 310 310">';
icon += '<path d="M134.875,19.74c0.04-22.771,34.363-22.771,34.34,0.642v95.563L303,196.354v35.306l-133.144-43.821v71.424l30.813,24.072v27.923l-47.501-14.764l-47.501,14.764v-27.923l30.491-24.072v-71.424L3,231.66v-35.306l131.875-80.409V19.74z" fill="'+data.iconColor+'"/></svg>';
var svgplane = "data:image/svg+xml;base64," + btoa(icon);
var dir = parseFloat(data.hdg || data.bearing || "0");
myMarker = L.divIcon({
className:"planeicon",
iconAnchor: [16, 16],
html:'<img src="'+svgplane+'" style="width:32px; height:32px; -webkit-transform:rotate('+dir+'deg); -moz-transform:rotate('+dir+'deg);"/>'
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
//q = 'https://www.bing.com/images/search?q='+data.icon+'%20'+encodeURIComponent(data.name);
//words += '<a href=\''+q+'\' target="_thingpic">Pictures</a><br>';
}
else if (data.icon === "helicopter") {
data.iconColor = data.iconColor || "black";
if (data.hasOwnProperty("squawk")) { data.iconColor = "red"; }
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="314" height="314" viewBox="0 0 314.5 314.5">';
icon += '<path d="M268.8 3c-3.1-3.1-8.3-2.9-11.7 0.5L204.9 55.7C198.5 23.3 180.8 0 159.9 0c-21.9 0-40.3 25.5-45.7 60.2L57.4 3.5c-3.4-3.4-8.6-3.6-11.7-0.5 -3.1 3.1-2.9 8.4 0.5 11.7l66.3 66.3c0 0.2 0 0.4 0 0.6 0 20.9 4.6 39.9 12.1 54.4l-78.4 78.4c-3.4 3.4-3.6 8.6-0.5 11.7 3.1 3.1 8.3 2.9 11.7-0.5l76.1-76.1c3.2 3.7 6.7 6.7 10.4 8.9v105.8l-47.7 32.2v18l50.2-22.3h26.9l50.2 22.3v-18L175.8 264.2v-105.8c2.7-1.7 5.4-3.8 7.8-6.2l73.4 73.4c3.4 3.4 8.6 3.6 11.7 0.5 3.1-3.1 2.9-8.3-0.5-11.7l-74.9-74.9c8.6-14.8 14-35.2 14-57.8 0-1.9-0.1-3.8-0.2-5.8l61.2-61.2C271.7 11.3 271.9 6.1 268.8 3z" fill="'+data.iconColor+'"/></svg>';
var svgheli = "data:image/svg+xml;base64," + btoa(icon);
var dir = parseFloat(data.hdg || data.bearing || "0");
myMarker = L.divIcon({
className:"heliicon",
iconAnchor: [16, 16],
html:'<img src="'+svgheli+'" style="width:32px; height:32px; -webkit-transform:rotate('+dir+'deg); -moz-transform:rotate('+dir+'deg);"/>'
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if (data.icon === "uav") {
data.iconColor = data.iconColor || "black";
if (data.hasOwnProperty("squawk")) { data.iconColor = "red"; }
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">';
icon+= '<path d="M62 82h-8V64h36c0-5-4-9-9-9H54v-8c0-3 4-5 4-11.1 0-4.4-3.6-8-8-8-4.4 0-8 3.6-8 8 0 5.1 4 8.1 4 11.1V55h-27c-5 0-9 4-9 9h36v18H38c-2.4 0-5 2.3-5 5L50 92l17-5C67 84.3 64.4 82 62 82z" fill="'+data.iconColor+'"/></svg>';
var svguav = "data:image/svg+xml;base64," + btoa(icon);
var dir = parseFloat(data.hdg || data.bearing || "0");
myMarker = L.divIcon({
className:"uavicon",
iconAnchor: [16, 16],
html:'<img src="'+svguav+'" style="width:32px; height:32px; -webkit-transform:rotate('+dir+'deg); -moz-transform:rotate('+dir+'deg);"/>',
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if (data.icon === "car") {
data.iconColor = data.iconColor || "black";
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="47px" height="47px" viewBox="0 0 47 47">';
icon += '<path d="M29.395,0H17.636c-3.117,0-5.643,3.467-5.643,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759 c3.116,0,5.644-2.527,5.644-5.644V6.584C35.037,3.467,32.511,0,29.395,0z M34.05,14.188v11.665l-2.729,0.351v-4.806L34.05,14.188z M32.618,10.773c-1.016,3.9-2.219,8.51-2.219,8.51H16.631l-2.222-8.51C14.41,10.773,23.293,7.755,32.618,10.773z M15.741,21.713 v4.492l-2.73-0.349V14.502L15.741,21.713z M13.011,37.938V27.579l2.73,0.343v8.196L13.011,37.938z M14.568,40.882l2.218-3.336 h13.771l2.219,3.336H14.568z M31.321,35.805v-7.872l2.729-0.355v10.048L31.321,35.805z" fill="'+data.iconColor+'"/></svg>';
var svgcar = "data:image/svg+xml;base64," + btoa(icon);
var dir = parseFloat(data.hdg || data.bearing || "0");
myMarker = L.divIcon({
className:"caricon",
iconAnchor: [16, 16],
html:'<img src="'+svgcar+'" style="width:32px; height:32px; -webkit-transform:rotate('+dir+'deg); -moz-transform:rotate('+dir+'deg);"/>',
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if (data.icon === "arrow") {
data.iconColor = data.iconColor || "black";
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32px" height="32px" viewBox="0 0 32 32">';
icon += '<path d="m16.2 0.6l-10.9 31 10.7-11.1 10.5 11.1 -10.3-31z" fill="'+data.iconColor+'"/></svg>';
var svgarrow = "data:image/svg+xml;base64," + btoa(icon);
var dir = parseFloat(data.hdg || data.bearing || "0");
myMarker = L.divIcon({
className:"arrowicon",
iconAnchor: [16, 16],
html:"'<img src='"+svgarrow+"' style='width:32px; height:32px; -webkit-transform:translate(0px,-16px) rotate("+dir+"deg); -moz-transform:translate(0px,-16px) rotate("+dir+"deg);'/>",
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if (data.icon === "wind") {
data.iconColor = data.iconColor || "black";
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32px" height="32px" viewBox="0 0 32 32">';
icon += '<path d="M16.7 31.7l7-6.9c0.4-0.4 0.4-1 0-1.4 -0.4-0.4-1-0.4-1.4 0l-5.3 5.2V17.3l6.7-6.6c0.2-0.2 0.3-0.5 0.3-0.7v-9c0-0.9-1.1-1.3-1.7-0.7l-6.3 6.2L9.7 0.3C9.1-0.3 8 0.1 8 1.1v8.8c0 0.3 0.1 0.6 0.3 0.8l6.7 6.6v11.3l-5.3-5.2c-0.4-0.4-1-0.4-1.4 0 -0.4 0.4-0.4 1 0 1.4l7 6.9c0.2 0.2 0.5 0.3 0.7 0.3C16.2 32 16.5 31.9 16.7 31.7zM10 9.6V3.4l5 4.9v6.2L10 9.6zM17 8.3l5-4.9v6.2l-5 4.9V8.3z" fill="'+data.iconColor+'"/></svg>';
var svgwind = "data:image/svg+xml;base64," + btoa(icon);
var dir = parseFloat(data.hdg || data.bearing || "0");
myMarker = L.divIcon({
className:"windicon",
iconAnchor: [16, 16],
html:'<img src="'+svgwind+'" style="width:32px; height:32px; -webkit-transform:rotate('+dir+'deg); -moz-transform:rotate('+dir+'deg);"/>',
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if (data.icon === "satellite") {
data.iconColor = data.iconColor || "black";
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">';
icon += '<polygon points="38.17 39.4 45.24 32.33 43.34 27.92 24.21 8.78 14.59 18.4 33.72 37.53" fill="'+data.iconColor+'"/>';
icon += '<path d="M69.22 44.57L54.38 29.73c-1.1-1.1-2.91-1.1-4.01 0L35.53 44.57c-1.1 1.1-1.1 2.91 0 4.01l14.84 14.84c1.1 1.1 2.91 1.1 4.01 0l14.84-14.84C70.32 47.47 70.32 45.67 69.22 44.57z" fill="'+data.iconColor+'"/>';
icon += '<polygon points="71.04 55.61 66.58 53.75 59.52 60.82 61.42 65.23 80.55 84.36 90.17 74.75" fill="'+data.iconColor+'"/>';
icon += '<path d="M28.08 55.26l-6.05 0.59C23.11 68.13 32.78 77.94 45 79.22l0.59-6.05C36.26 72.15 28.89 64.66 28.08 55.26z" fill="'+data.iconColor+'"/>';
icon += '<path d="M15.88 56.54L9.83 57.13c1.67 18.06 16.03 32.43 34.08 34.09l0.59-6.04C29.34 83.76 17.29 71.71 15.88 56.54z" fill="'+data.iconColor+'"/>';
icon += '</svg>';
var svgsat = "data:image/svg+xml;base64," + btoa(icon);
myMarker = L.divIcon({
className:"satelliteicon",
iconAnchor: [16, 16],
html:'<img src="'+svgsat+'" style="width:32px; height:32px;"/>',
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if ((data.icon === "iss") || (data.icon === "ISS")) {
data.iconColor = data.iconColor || "black";
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 48 48">';
icon += '<path id="iss" d="m4.55 30.97l6.85-12.68 0.59 0.32 -6.85 12.68 4.27 2.3 6.85-12.68 0.49 0.27 -0.81 1.5c-0.26 0.48-0.07 1.1 0.44 1.37l5.09 2.75c0.5 0.27 1.12 0.1 1.38-0.39l0.81-1.5 0.72 0.39 -1.49 2.75c-0.41 0.76-0.38 1.58 0.08 1.82l4.61 2.49c0.45 0.24 1.15-0.18 1.56-0.94l1.49-2.75 0.69 0.37 -6.85 12.68 4.26 2.3 6.85-12.68 0.59 0.32 -6.85 12.69 4.26 2.3 14.46-26.78 -4.26-2.3 -6.88 12.74 -0.59-0.32 6.88-12.74 -4.26-2.3 -6.88 12.74 -0.69-0.37 1.49-2.75c0.41-0.76 ';
icon += '0.38-1.58-0.08-1.82l-1.4-0.75 0.5-0.92c1.02 0.17 2.09-0.32 2.62-1.3 0.67-1.23 0.22-2.76-0.99-3.42 -1.21-0.65-2.74-0.19-3.4 1.05 -0.53 0.98-0.35 2.14 0.35 2.9l-0.5 0.92 -1.8-0.97c-0.45-0.24-1.15 0.17-1.57 0.94l-1.49 2.75 -0.72-0.39 0.81-1.5c0.26-0.48 0.07-1.1-0.44-1.36l-5.09-2.75c-0.5-0.27-1.12-0.1-1.38 0.39l-0.81 1.5 -0.49-0.27 6.88-12.74 -4.26-2.3 -6.88 12.74 -0.59-0.32 6.88-12.74 -4.26-2.3 -14.46 26.78 4.26 2.3zm14.26-11.72c0.2-0.37 0.68-0.51 1.06-0.3l3.93 ';
icon += '2.12c0.39 0.21 0.54 0.68 0.34 1.05l-1.81 3.35c-0.2 0.37-0.68 0.51-1.06 0.3l-3.93-2.12c-0.38-0.21-0.53-0.68-0.33-1.05l1.81-3.35zm12.01-1.46c0.45-0.83 1.47-1.14 2.28-0.7 0.81 0.44 1.11 1.46 0.66 2.29 -0.44 0.83-1.47 1.14-2.28 0.7 -0.81-0.44-1.11-1.46-0.66-2.29zm-3.78 4.26c0.35-0.66 0.93-1.04 1.28-0.85l3.57 1.93c0.35 0.19 0.35 0.88-0.01 1.53l-3.19 5.91c-0.35 0.66-0.93 1.04-1.28 0.85l-3.56-1.92c-0.35-0.19-0.35-0.88 0.01-1.53l3.19-5.91zm0.19 7.49c-0.26 0.49-0.87 ';
icon += '0.67-1.36 0.41 -0.49-0.26-0.67-0.87-0.41-1.36 0.27-0.49 0.87-0.67 1.36-0.4 0.49 0.26 0.67 0.87 0.41 1.36zm-7.46-6.31c-0.26 0.49-0.87 0.67-1.36 0.41s-0.67-0.87-0.41-1.36c0.27-0.49 0.87-0.67 1.36-0.4s0.67 0.87 0.41 1.36zm2.32 1.25c-0.26 0.49-0.87 0.67-1.36 0.41 -0.49-0.26-0.67-0.87-0.41-1.36 0.27-0.49 0.87-0.67 1.36-0.41 0.49 0.26 0.67 0.87 0.41 1.36z" fill="'+data.iconColor+'"/>';
icon += '</svg>';
var svgiss = "data:image/svg+xml;base64," + btoa(icon);
myMarker = L.divIcon({
className:"issicon",
iconAnchor: [25, 25],
html:'<img src="'+svgiss+'" style="width:50px; height:50px;"/>',
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
}
else if (data.icon === "locate") {
data.iconColor = data.iconColor || "cyan";
icon = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="468px" height="468px" viewBox="0 0 468 468">';
icon += '<polygon points="32 32 104 32 104 0 0 0 0 104 32 104" fill="'+data.iconColor+'"/>';
icon += '<polygon points="468 0 364 0 364 32 436 32 436 104 468 104" fill="'+data.iconColor+'"/>';
icon += '<polygon points="0 468 104 468 104 436 32 436 32 364 0 364" fill="'+data.iconColor+'"/>';
icon += '<polygon points="436 436 364 436 364 468 468 468 468 364 436 364" fill="'+data.iconColor+'"/>';
//icon += '<circle cx="234" cy="234" r="22" fill="'+data.iconColor+'"/>';
icon += '</svg>';
var svglocate = "data:image/svg+xml;base64," + btoa(icon);
myMarker = L.divIcon({
className:"locateicon",
iconAnchor: [16, 16],
html:'<img src="'+svglocate+'" style="width:32px; height:32px;"/>',
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
labelOffset = [12,-4];
}
else if (data.icon === "friend") {
marker = L.marker(ll, { icon: L.divIcon({ className: 'circle f', iconSize: [20, 12] }), title: data.name, draggable:drag });
}
else if (data.icon === "hostile") {
marker = L.marker(ll, { icon: L.divIcon({ className: 'circle h', iconSize: [16, 16] }), title: data.name, draggable:drag });
}
else if (data.icon === "neutral") {
marker = L.marker(ll, { icon: L.divIcon({ className: 'circle n', iconSize: [16, 16] }), title: data.name, draggable:drag });
}
else if (data.icon === "unknown") {
marker = L.marker(ll, { icon: L.divIcon({ className: 'circle', iconSize: [16, 16] }), title: data.name, draggable:drag });
}
else if (data.icon === "danger") {
marker = L.marker(ll, { icon: L.divIcon({ className: 'up-triangle' }), title: data.name, draggable:drag });
}
else if (data.icon === "earthquake") {
marker = L.marker(ll, { icon: L.divIcon({ className: 'circle e', iconSize: [data.mag*5, data.mag*5] }), title: data.name, draggable:drag });
}
else if (data.icon.match(/^:.*:$/g)) {
var em = emojify(data.icon);
var col = data.iconColor || "#910000";
myMarker = L.divIcon({
className:"emicon",
html: '<center><span style="font-size:2em; color:'+col+'">'+em+'</span></center>',
iconSize: [32, 32]
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
labelOffset = [12,-4];
}
else if (data.icon.match(/^https?:.*$/)) {
myMarker = L.icon({
iconUrl: data.icon,
iconSize: [32, 32],
iconAnchor: [16, 16],
popupAnchor: [0, -16]
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
labelOffset = [12,-4];
}
else if (data.icon.substr(0,3) === "fa-") {
var col = data.iconColor || "#910000";
var imod = "";
if (data.icon.indexOf(" ") === -1) { imod = "fa-2x "; }
myMarker = L.divIcon({
className:"faicon",
html: '<center><i class="fa fa-fw '+imod+data.icon+'" style="color:'+col+'"></i></center>',
iconSize: [32, 32],
popupAnchor: [0, -16]
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
labelOffset = [8,-8];
}
else if (data.icon.substr(0,3) === "wi-") {
var col = data.iconColor || "#910000";
var imod = "";
if (data.icon.indexOf(" ") === -1) { imod = "wi-2x "; }
myMarker = L.divIcon({
className:"wiicon",
html: '<center><i class="wi wi-fw '+imod+data.icon+'" style="color:'+col+'"></i></center>',
iconSize: [32, 32],
popupAnchor: [0, -16]
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
labelOffset = [16,-16];
}
else {
myMarker = L.VectorMarkers.icon({
icon: data.icon || "circle",
markerColor: (data.iconColor || "#910000"),
prefix: 'fa',
iconColor: 'white'
});
marker = L.marker(ll, {title:data.name, icon:myMarker, draggable:drag});
labelOffset = [6,-6];
}
}
if (data.hasOwnProperty("SIDC")) {
// "SIDC":"SFGPU------E***","name":"1.C2 komp","fullname":"1.C2 komp/FTS/INSS"
myMarker = new ms.Symbol( data.SIDC.toUpperCase(), { uniqueDesignation:data.name });
// Now that we have a symbol we can ask for the echelon and set the symbol size
var opts = data.options || {};
opts.size = opts.size || iconSz[myMarker.getProperties().echelon] || 30;
opts.size = opts.size * (opts.scale || 1);
myMarker = myMarker.setOptions(opts);
var myicon = L.icon({
iconUrl: myMarker.toDataURL(),
iconAnchor: [myMarker.getAnchor().x, myMarker.getAnchor().y],
className: "natoicon",
});
marker = L.marker(ll, { title:data.name, icon:myicon, draggable:drag });
}
marker.name = data.name;
// var createLabelIcon = function(labelText) {
// return L.marker(new L.LatLng(51.05, -1.35), {icon:L.divIcon({ html:labelText })});
// }
// send new position at end of move event if point is draggable
if (data.draggable === true) {
if (data.icon) { marker.icon = data.icon; }
if (data.iconColor) { marker.iconColor = data.iconColor; }
if (data.SIDC) { marker.SIDC = data.SIDC.toUpperCase(); }
marker.on('dragend', function (e) {
var l = marker.getLatLng().toString().replace('LatLng(','lat, lon : ').replace(')','')
marker.setPopupContent(marker.getPopup().getContent().split("lat, lon")[0] + l);
ws.send(JSON.stringify({action:"move",name:marker.name,layer:marker.lay,icon:marker.icon,iconColor:marker.iconColor,SIDC:marker.SIDC,draggable:true,lat:parseFloat(marker.getLatLng().lat.toFixed(6)),lon:parseFloat(marker.getLatLng().lng.toFixed(6))}));
});
}
// remove icon from list of properties, then add all others to popup
if (data.hasOwnProperty("SIDC") && data.hasOwnProperty("options")) { delete data.options; }
if (data.hasOwnProperty("icon")) { delete data.icon; }
if (data.hasOwnProperty("iconColor")) { delete data.iconColor; }
if (data.hasOwnProperty("photourl")) {
words += "<img src=\"" + data.photourl + "\" style=\"width:100%; margin-top:10px;\">";
delete data.photourl;
}
if (data.hasOwnProperty("photoUrl")) {
words += "<img src=\"" + data.photoUrl + "\" style=\"width:100%; margin-top:10px;\">";
delete data.photoUrl;
}
if (data.hasOwnProperty("videoUrl")) {
words += '<video controls muted autoplay width="320"><source src="'+data.videoUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
delete data.videoUrl;
}
if (data.hasOwnProperty("ttl")) { // save expiry time for this marker
if (data.ttl != 0) {
marker.ts = parseInt(Date.now()/1000) + Number(data.ttl);
}
delete data.ttl;
}
else if (maxage != 0) {
marker.ts = parseInt(Date.now()/1000) + Number(maxage);
}
if (data.hasOwnProperty("weblink")) {
if (typeof data.weblink === "string") {
words += "<b><a href='"+ data.weblink + "' target='_new'>more information...</a></b><br/>";
} else {
var tgt = data.weblink.target || "_new";
words += "<b><a href='"+ data.weblink.url + "' target='"+ tgt + "'>" + data.weblink.name + "</a></b><br/>";
}
delete data.weblink;
}
var p;
if (data.hasOwnProperty("popped") && (data.popped === true)) {
p = true;
delete data.popped;
}
if (data.hasOwnProperty("popped") && (data.popped === false)) {
marker.closePopup();
p = false;
delete data.popped;
}
// If .label then use that rather than name tooltip
if (data.label) {
if (typeof data.label === "boolean" && data.label === true) {
marker.bindTooltip(data.name, { permanent:true, direction:"right", offset:labelOffset });
}
else if (typeof data.label === "string" && data.label.length > 0) {
marker.bindTooltip(data.label, { permanent:true, direction:"right", offset:labelOffset });
}
delete marker.options.title;
delete data.label;
}
// otherwise check for .tooltip then use that rather than name tooltip
else if (data.tooltip) {
if (typeof data.tooltip === "string" && data.tooltip.length > 0) {
marker.bindTooltip(data.tooltip, { direction:"bottom", offset:[0,4] });
delete marker.options.title;
delete data.tooltip;
}
}
marker = rightmenu(marker);
// Add any remaining properties to the info box
var llc = data.lineColor;
delete data.lat;
delete data.lon;
if (data.layer) { delete data.layer; }
if (data.lineColor) { delete data.lineColor; }
if (data.color) { delete data.color; }
if (data.weight) { delete data.weight; }
if (data.tracklength) { delete data.tracklength; }
if (data.dashArray) { delete data.dashArray; }
if (data.fill) { delete data.fill; }
if (data.draggable) { delete data.draggable; }
for (var i in data) {
if ((i != "name") && (i != "length")) {
if (typeof data[i] === "object") {
words += i +" : "+JSON.stringify(data[i])+"<br/>";
} else {
words += i +" : "+data[i]+"<br/>";
}
}
}
if (data.popup) { words = data.popup; }
else { words = words + marker.getLatLng().toString().replace('LatLng(','lat, lon : ').replace(')',''); }
words = "<b>"+data.name+"</b><br/>" + words; //"<button style=\"border-radius:4px; float:right; background-color:lightgrey;\" onclick='popped=false;popmark.closePopup();'>X</button><br/>" + words;
marker.bindPopup(words, {autoClose:false, closeButton:true, closeOnClick:false, minWidth:200});
marker._popup.dname = data.name;
marker.lay = lay; // and the layer it is on
marker.on('click', function(e) {
ws.send(JSON.stringify({action:"click",name:marker.name,layer:marker.lay,icon:marker.icon,iconColor:marker.iconColor,SIDC:marker.SIDC,draggable:true,lat:parseFloat(marker.getLatLng().lat.toFixed(6)),lon:parseFloat(marker.getLatLng().lng.toFixed(6))}));
});
if ((data.addtoheatmap !== "false") || (!data.hasOwnProperty("addtoheatmap"))) { // Added to give ability to control if points from active layer contribute to heatmap
if (heatAll || map.hasLayer(layers[lay])) { heat.addLatLng(lli); }
}
markers[data.name] = marker;
layers[lay].addLayer(marker);
if ((data.hdg != null) && (data.bearing == null)) { data.bearing = data.hdg; delete data.hdg; }
if (data.bearing != null) { // if there is a heading
if (data.speed != null) { data.length = parseFloat(data.speed || "0") * 50; } // and a speed
if (data.length != null) {
if (polygons[data.name] != null) { map.removeLayer(polygons[data.name]); }
var x = ll.lng * 1; // X coordinate
var y = ll.lat * 1; // Y coordinate
var ll1 = ll;
var angle = parseFloat(data.bearing);
var lengthAsDegrees = parseFloat(data.length || "0") / 110540; // metres in a degree..ish
var polygon = null;
if (data.accuracy != null) {
data.accuracy = Number(data.accuracy);
var y2 = y + Math.sin((90-angle+data.accuracy)/180*Math.PI)*lengthAsDegrees*Math.cos(y/180*Math.PI);
var x2 = x + Math.cos((90-angle+data.accuracy)/180*Math.PI)*lengthAsDegrees;
var ll2 = new L.LatLng(y2,x2);
var y3 = y + Math.sin((90-angle-data.accuracy)/180*Math.PI)*lengthAsDegrees*Math.cos(y/180*Math.PI);
var x3 = x + Math.cos((90-angle-data.accuracy)/180*Math.PI)*lengthAsDegrees;
var ll3 = new L.LatLng(y3,x3);
polygon = L.polygon([ ll1, ll2, ll3 ], {weight:2, color:llc||'#f30', fillOpacity:0.06, clickable:false});
} else {
var ya = y + Math.sin((90-angle)/180*Math.PI)*lengthAsDegrees*Math.cos(y/180*Math.PI);
var xa = x + Math.cos((90-angle)/180*Math.PI)*lengthAsDegrees;
var lla = new L.LatLng(ya,xa);
polygon = L.polygon([ ll1, lla ], {weight:2, color:llc||'#f30', clickable:false});
}
if (typeof layers[lay].getVisibleParent === 'function') {
var vis = layers[lay].getVisibleParent(marker);
if ((polygon !== null) && (vis !== null) && (!vis.hasOwnProperty("lay"))) {
polygon.setStyle({opacity:0});
}
}
polygons[data.name] = polygon;
polygons[data.name].lay = lay;
layers[lay].addLayer(polygon);
}
}
if (panit) { map.setView(ll,map.getZoom()); }
if (p === true) { marker.openPopup(); }
}
} | javascript | {
"resource": ""
} |
q25970 | doGeojson | train | function doGeojson(g) {
console.log("GEOJSON",g);
if (!basemaps["geojson"]) {
var opt = { style: function(feature) {
var st = { stroke:true, color:"#910000", weight:2, fill:true, fillColor:"#910000", fillOpacity:0.3 };
if (feature.hasOwnProperty("properties")) {
console.log("GPROPS", feature.properties)
}
if (feature.hasOwnProperty("style")) {
console.log("GSTYLE", feature.style)
}
return st;
}
}
opt.onEachFeature = function (f,l) {
if (f.properties) { l.bindPopup('<pre>'+JSON.stringify(f.properties,null,' ').replace(/[\{\}"]/g,'')+'</pre>'); }
}
overlays["geojson"] = L.geoJson(g,opt);
layercontrol.addOverlay(overlays["geojson"],"geojson");
}
overlays["geojson"].addData(g);
} | javascript | {
"resource": ""
} |
q25971 | train | function(newState){
// when called with no args, it's a getter
if (arguments.length === 0) {
return this._currentState.stateName;
}
// activate by name
if(typeof newState == 'string'){
this._activateStateNamed(newState);
// activate by index
} else if (typeof newState == 'number'){
this._activateState(this._states[newState]);
}
return this;
} | javascript | {
"resource": ""
} | |
q25972 | State | train | function State(template, easyButton){
this.title = template.title;
this.stateName = template.stateName ? template.stateName : 'unnamed-state';
// build the wrapper
this.icon = L.DomUtil.create('span', '');
L.DomUtil.addClass(this.icon, 'button-state state-' + this.stateName.replace(/(^\s*|\s*$)/g,''));
this.icon.innerHTML = buildIcon(template.icon);
this.onClick = L.Util.bind(template.onClick?template.onClick:function(){}, easyButton);
} | javascript | {
"resource": ""
} |
q25973 | webpackImporter | train | function webpackImporter(resourcePath, resolve, addNormalizedDependency) {
function dirContextFrom(fileContext) {
return path.dirname(
// The first file is 'stdin' when we're using the data option
fileContext === 'stdin' ? resourcePath : fileContext
);
}
// eslint-disable-next-line no-shadow
function startResolving(dir, importsToResolve) {
return importsToResolve.length === 0
? Promise.reject()
: resolve(dir, importsToResolve[0]).then(
(resolvedFile) => {
// Add the resolvedFilename as dependency. Although we're also using stats.includedFiles, this might come
// in handy when an error occurs. In this case, we don't get stats.includedFiles from node-sass.
addNormalizedDependency(resolvedFile);
return {
// By removing the CSS file extension, we trigger node-sass to include the CSS file instead of just linking it.
file: resolvedFile.replace(matchCss, ''),
};
},
() => startResolving(dir, tail(importsToResolve))
);
}
return (url, prev, done) => {
startResolving(dirContextFrom(prev), importsToResolve(url))
// Catch all resolving errors, return the original file and pass responsibility back to other custom importers
.catch(() => {
return {
file: url,
};
})
.then(done);
};
} | javascript | {
"resource": ""
} |
q25974 | proxyCustomImporters | train | function proxyCustomImporters(importer, resourcePath) {
return [].concat(importer).map(
// eslint-disable-next-line no-shadow
(importer) =>
function customImporter() {
return importer.apply(
this,
// eslint-disable-next-line prefer-rest-params
Array.from(arguments).map((arg, i) =>
i === 1 && arg === 'stdin' ? resourcePath : arg
)
);
}
);
} | javascript | {
"resource": ""
} |
q25975 | normalizeOptions | train | function normalizeOptions(loaderContext, content, webpackImporter) {
const options = cloneDeep(utils.getOptions(loaderContext)) || {};
const { resourcePath } = loaderContext;
// allow opt.functions to be configured WRT loaderContext
if (typeof options.functions === 'function') {
options.functions = options.functions(loaderContext);
}
let { data } = options;
if (typeof options.data === 'function') {
data = options.data(loaderContext);
}
options.data = data ? data + os.EOL + content : content;
// opt.outputStyle
if (!options.outputStyle && loaderContext.minimize) {
options.outputStyle = 'compressed';
}
// opt.sourceMap
// Not using the `this.sourceMap` flag because css source maps are different
// @see https://github.com/webpack/css-loader/pull/40
if (options.sourceMap) {
// Deliberately overriding the sourceMap option here.
// node-sass won't produce source maps if the data option is used and options.sourceMap is not a string.
// In case it is a string, options.sourceMap should be a path where the source map is written.
// But since we're using the data option, the source map will not actually be written, but
// all paths in sourceMap.sources will be relative to that path.
// Pretty complicated... :(
options.sourceMap = path.join(process.cwd(), '/sass.map');
if ('sourceMapRoot' in options === false) {
options.sourceMapRoot = process.cwd();
}
if ('omitSourceMapUrl' in options === false) {
// The source map url doesn't make sense because we don't know the output path
// The css-loader will handle that for us
options.omitSourceMapUrl = true;
}
if ('sourceMapContents' in options === false) {
// If sourceMapContents option is not set, set it to true otherwise maps will be empty/null
// when exported by webpack-extract-text-plugin.
options.sourceMapContents = true;
}
}
// indentedSyntax is a boolean flag.
const ext = path.extname(resourcePath);
// If we are compiling sass and indentedSyntax isn't set, automatically set it.
if (
ext &&
ext.toLowerCase() === '.sass' &&
'indentedSyntax' in options === false
) {
options.indentedSyntax = true;
} else {
options.indentedSyntax = Boolean(options.indentedSyntax);
}
// Allow passing custom importers to `node-sass`. Accepts `Function` or an array of `Function`s.
options.importer = options.importer
? proxyCustomImporters(options.importer, resourcePath)
: [];
options.importer.push(webpackImporter);
// `node-sass` uses `includePaths` to resolve `@import` paths. Append the currently processed file.
options.includePaths = options.includePaths || [];
options.includePaths.push(path.dirname(resourcePath));
return options;
} | javascript | {
"resource": ""
} |
q25976 | importsToResolve | train | function importsToResolve(url) {
const request = utils.urlToRequest(url);
// Keep in mind: ext can also be something like '.datepicker' when the true extension is omitted and the filename contains a dot.
// @see https://github.com/webpack-contrib/sass-loader/issues/167
const ext = path.extname(request);
if (matchModuleImport.test(url)) {
return [request, url];
}
// libsass' import algorithm works like this:
// In case there is a file extension...
// - If the file is a CSS-file, do not include it all, but just link it via @import url().
// - The exact file name must match (no auto-resolving of '_'-modules).
if (ext === '.css') {
return [];
}
if (ext === '.scss' || ext === '.sass') {
return [request, url];
}
// In case there is no file extension...
// - Prefer modules starting with '_'.
// - File extension precedence: .scss, .sass, .css.
const basename = path.basename(request);
if (basename.charAt(0) === '_') {
return [`${request}.scss`, `${request}.sass`, `${request}.css`, url];
}
const dirname = path.dirname(request);
return [
`${dirname}/_${basename}.scss`,
`${dirname}/_${basename}.sass`,
`${dirname}/_${basename}.css`,
`${request}.scss`,
`${request}.sass`,
`${request}.css`,
url,
];
} | javascript | {
"resource": ""
} |
q25977 | sassLoader | train | function sassLoader(content) {
const callback = this.async();
const isSync = typeof callback !== 'function';
const self = this;
const { resourcePath } = this;
function addNormalizedDependency(file) {
// node-sass returns POSIX paths
self.dependency(path.normalize(file));
}
if (isSync) {
throw new Error(
'Synchronous compilation is not supported anymore. See https://github.com/webpack-contrib/sass-loader/issues/333'
);
}
let resolve = pify(this.resolve);
// Supported since v4.27.0
if (this.getResolve) {
resolve = this.getResolve({
mainFields: ['sass', 'main'],
extensions: ['.scss', '.sass', '.css'],
});
}
const options = normalizeOptions(
this,
content,
webpackImporter(resourcePath, resolve, addNormalizedDependency)
);
// Skip empty files, otherwise it will stop webpack, see issue #21
if (options.data.trim() === '') {
callback(null, '');
return;
}
const render = getRenderFuncFromSassImpl(
// eslint-disable-next-line import/no-extraneous-dependencies, global-require
options.implementation || getDefaultSassImpl()
);
render(options, (err, result) => {
if (err) {
formatSassError(err, this.resourcePath);
if (err.file) {
this.dependency(err.file);
}
callback(err);
return;
}
if (result.map && result.map !== '{}') {
// eslint-disable-next-line no-param-reassign
result.map = JSON.parse(result.map);
// result.map.file is an optional property that provides the output filename.
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
// eslint-disable-next-line no-param-reassign
delete result.map.file;
// One of the sources is 'stdin' according to dart-sass/node-sass because we've used the data input.
// Now let's override that value with the correct relative path.
// Since we specified options.sourceMap = path.join(process.cwd(), "/sass.map"); in normalizeOptions,
// we know that this path is relative to process.cwd(). This is how node-sass works.
// eslint-disable-next-line no-param-reassign
const stdinIndex = result.map.sources.findIndex(
(source) => source.indexOf('stdin') !== -1
);
if (stdinIndex !== -1) {
result.map.sources[stdinIndex] = path.relative(
process.cwd(),
resourcePath
);
}
// node-sass returns POSIX paths, that's why we need to transform them back to native paths.
// This fixes an error on windows where the source-map module cannot resolve the source maps.
// @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
// eslint-disable-next-line no-param-reassign
result.map.sourceRoot = path.normalize(result.map.sourceRoot);
// eslint-disable-next-line no-param-reassign
result.map.sources = result.map.sources.map(path.normalize);
} else {
// eslint-disable-next-line no-param-reassign
result.map = null;
}
result.stats.includedFiles.forEach(addNormalizedDependency);
callback(null, result.css.toString(), result.map);
});
} | javascript | {
"resource": ""
} |
q25978 | getRenderFuncFromSassImpl | train | function getRenderFuncFromSassImpl(module) {
const { info } = module;
const components = info.split('\t');
if (components.length < 2) {
throw new Error(`Unknown Sass implementation "${info}".`);
}
const [implementation, version] = components;
if (!semver.valid(version)) {
throw new Error(`Invalid Sass version "${version}".`);
}
if (implementation === 'dart-sass') {
if (!semver.satisfies(version, '^1.3.0')) {
throw new Error(
`Dart Sass version ${version} is incompatible with ^1.3.0.`
);
}
return module.render.bind(module);
} else if (implementation === 'node-sass') {
if (!semver.satisfies(version, '^4.0.0')) {
throw new Error(
`Node Sass version ${version} is incompatible with ^4.0.0.`
);
}
// There is an issue with node-sass when async custom importers are used
// See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
// We need to use a job queue to make sure that one thread is always available to the UV lib
if (nodeSassJobQueue === null) {
const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);
nodeSassJobQueue = async.queue(
module.render.bind(module),
threadPoolSize - 1
);
}
return nodeSassJobQueue.push.bind(nodeSassJobQueue);
}
throw new Error(`Unknown Sass implementation "${implementation}".`);
} | javascript | {
"resource": ""
} |
q25979 | token | train | function token(input) {
let token;
if (typeof input === "string") {
token = input;
} else if (Buffer.isBuffer(input)) {
token = input.toString("hex");
}
token = token.replace(/[^0-9a-f]/gi, "");
if (token.length === 0) {
throw new Error("Token has invalid length");
}
return token;
} | javascript | {
"resource": ""
} |
q25980 | Notification | train | function Notification (payload) {
this.encoding = "utf8";
this.payload = {};
this.compiled = false;
this.aps = {};
this.expiry = 0;
this.priority = 10;
if (payload) {
for(let key in payload) {
if (payload.hasOwnProperty(key)) {
this[key] = payload[key];
}
}
}
} | javascript | {
"resource": ""
} |
q25981 | invalidDoc | train | function invalidDoc(doc) {
if (doc.query) {
if (typeof doc.query.type != "string") return ".query.type must be a string";
if (doc.query.start && !isPosition(doc.query.start)) return ".query.start must be a position";
if (doc.query.end && !isPosition(doc.query.end)) return ".query.end must be a position";
}
if (doc.files) {
if (!Array.isArray(doc.files)) return "Files property must be an array";
for (var i = 0; i < doc.files.length; ++i) {
var file = doc.files[i];
if (typeof file != "object") return ".files[n] must be objects";
else if (typeof file.name != "string") return ".files[n].name must be a string";
else if (file.type == "delete") continue;
else if (typeof file.text != "string") return ".files[n].text must be a string";
else if (file.type == "part") {
if (!isPosition(file.offset) && typeof file.offsetLines != "number")
return ".files[n].offset must be a position";
} else if (file.type != "full") return ".files[n].type must be \"full\" or \"part\"";
}
}
} | javascript | {
"resource": ""
} |
q25982 | clean | train | function clean(obj) {
for (var prop in obj) if (obj[prop] == null) delete obj[prop];
return obj;
} | javascript | {
"resource": ""
} |
q25983 | compareCompletions | train | function compareCompletions(a, b) {
if (typeof a != "string") { a = a.name; b = b.name; }
var aUp = /^[A-Z]/.test(a), bUp = /^[A-Z]/.test(b);
if (aUp == bUp) return a < b ? -1 : a == b ? 0 : 1;
else return aUp ? 1 : -1;
} | javascript | {
"resource": ""
} |
q25984 | train | function() {
var
activeText = text.active || $module.data(metadata.storedText),
inactiveText = text.inactive || $module.data(metadata.storedText)
;
if( module.is.textEnabled() ) {
if( module.is.active() && activeText) {
module.verbose('Resetting active text', activeText);
module.update.text(activeText);
}
else if(inactiveText) {
module.verbose('Resetting inactive text', activeText);
module.update.text(inactiveText);
}
}
} | javascript | {
"resource": ""
} | |
q25985 | train | function(errors) {
var
html = '<ul class="list">'
;
$.each(errors, function(index, value) {
html += '<li>' + value + '</li>';
});
html += '</ul>';
return $(html);
} | javascript | {
"resource": ""
} | |
q25986 | train | function(value, regExp) {
if(regExp instanceof RegExp) {
return value.match(regExp);
}
var
regExpParts = regExp.match($.fn.form.settings.regExp.flags),
flags
;
// regular expression specified as /baz/gi (flags)
if(regExpParts) {
regExp = (regExpParts.length >= 2)
? regExpParts[1]
: regExp
;
flags = (regExpParts.length >= 3)
? regExpParts[2]
: ''
;
}
return value.match( new RegExp(regExp, flags) );
} | javascript | {
"resource": ""
} | |
q25987 | train | function(value, range) {
var
intRegExp = $.fn.form.settings.regExp.integer,
min,
max,
parts
;
if( !range || ['', '..'].indexOf(range) !== -1) {
// do nothing
}
else if(range.indexOf('..') == -1) {
if(intRegExp.test(range)) {
min = max = range - 0;
}
}
else {
parts = range.split('..', 2);
if(intRegExp.test(parts[0])) {
min = parts[0] - 0;
}
if(intRegExp.test(parts[1])) {
max = parts[1] - 0;
}
}
return (
intRegExp.test(value) &&
(min === undefined || value >= min) &&
(max === undefined || value <= max)
);
} | javascript | {
"resource": ""
} | |
q25988 | train | function(value, identifier) {
var
$form = $(this),
matchingValue
;
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? ( value.toString() == matchingValue.toString() )
: false
;
} | javascript | {
"resource": ""
} | |
q25989 | train | function(select) {
var
placeholder = select.placeholder || false,
values = select.values || {},
html = ''
;
html += '<i class="dropdown icon"></i>';
if(select.placeholder) {
html += '<div class="default text">' + placeholder + '</div>';
}
else {
html += '<div class="text"></div>';
}
html += '<div class="menu">';
$.each(select.values, function(index, option) {
html += (option.disabled)
? '<div class="disabled item" data-value="' + option.value + '">' + option.name + '</div>'
: '<div class="item" data-value="' + option.value + '">' + option.name + '</div>'
;
});
html += '</div>';
return html;
} | javascript | {
"resource": ""
} | |
q25990 | train | function(response, fields) {
var
values = response[fields.values] || {},
html = ''
;
$.each(values, function(index, option) {
var
maybeText = (option[fields.text])
? 'data-text="' + option[fields.text] + '"'
: '',
maybeDisabled = (option[fields.disabled])
? 'disabled '
: ''
;
html += '<div class="'+ maybeDisabled +'item" data-value="' + option[fields.value] + '"' + maybeText + '>';
html += option[fields.name];
html += '</div>';
});
return html;
} | javascript | {
"resource": ""
} | |
q25991 | train | function(source, id, url) {
module.debug('Changing video to ', source, id, url);
$module
.data(metadata.source, source)
.data(metadata.id, id)
;
if(url) {
$module.data(metadata.url, url);
}
else {
$module.removeData(metadata.url);
}
if(module.has.embed()) {
module.changeEmbed();
}
else {
module.create();
}
} | javascript | {
"resource": ""
} | |
q25992 | train | function() {
if(settings.throttle) {
clearTimeout(module.timer);
module.timer = setTimeout(function() {
$context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
}, settings.throttle);
}
else {
requestAnimationFrame(function() {
$context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
});
}
} | javascript | {
"resource": ""
} | |
q25993 | Session | train | function Session(options) {
options = options || {};
this.id = options.id || this._guid();
this.parent = options.parent || undefined;
this.authenticating = options.authenticating || false;
this.authenticated = options.authenticated || undefined;
this.user = options.user || 'guest';
this.host = options.host;
this.address = options.address || undefined;
this._isLocal = options.local || undefined;
this._delimiter = options.delimiter || String(os.hostname()).split('.')[0] + '~$';
this._modeDelimiter = undefined;
// Keeps history of how many times in a row `tab` was
// pressed on the keyboard.
this._tabCtr = 0;
this.cmdHistory = this.parent.cmdHistory;
// Special command mode vorpal is in at the moment,
// such as REPL. See mode documentation.
this._mode = undefined;
return this;
} | javascript | {
"resource": ""
} |
q25994 | Vorpal | train | function Vorpal() {
if (!(this instanceof Vorpal)) {
return new Vorpal();
}
// Program version
// Exposed through vorpal.version(str);
this._version = '';
// Program title
this._title = '';
// Program description
this._description = '';
// Program baner
this._banner = '';
// Command line history instance
this.cmdHistory = new this.CmdHistoryExtension();
// Registered `vorpal.command` commands and
// their options.
this.commands = [];
// Queue of IP requests, executed async, in sync.
this._queue = [];
// Current command being executed.
this._command = undefined;
// Expose UI.
this.ui = ui;
// Expose chalk as a convenience.
this.chalk = chalk;
// Expose lodash as a convenience.
this.lodash = _;
// Exposed through vorpal.delimiter(str).
this._delimiter = 'local@' + String(os.hostname()).split('.')[0] + '~$ ';
ui.setDelimiter(this._delimiter);
// Placeholder for vantage server. If vantage
// is used, this will be over-written.
this.server = {
sessions: []
};
// Whether all stdout is being hooked through a function.
this._hooked = false;
this._useDeprecatedAutocompletion = false;
// Expose common utilities, like padding.
this.util = VorpalUtil;
this.Session = Session;
// Active vorpal server session.
this.session = new this.Session({
local: true,
user: 'local',
parent: this,
delimiter: this._delimiter
});
// Allow unix-like key value pair normalization to be turned off by toggling this switch on.
this.isCommandArgKeyPairNormalized = true;
this._init();
return this;
} | javascript | {
"resource": ""
} |
q25995 | Command | train | function Command(name, parent) {
if (!(this instanceof Command)) {
return new Command();
}
this.commands = [];
this.options = [];
this._args = [];
this._aliases = [];
this._name = name;
this._relay = false;
this._hidden = false;
this._parent = parent;
this._mode = false;
this._catch = false;
this._help = undefined;
this._init = undefined;
this._after = undefined;
this._allowUnknownOptions = false;
} | javascript | {
"resource": ""
} |
q25996 | _camelcase | train | function _camelcase(flag) {
return flag.split('-').reduce(function (str, word) {
return str + word[0].toUpperCase() + word.slice(1);
});
} | javascript | {
"resource": ""
} |
q25997 | handleTabCounts | train | function handleTabCounts(str, freezeTabs) {
var result;
if (_.isArray(str)) {
this._tabCtr += 1;
if (this._tabCtr > 1) {
result = str.length === 0 ? undefined : str;
}
} else {
this._tabCtr = freezeTabs === true ? this._tabCtr + 1 : 0;
result = str;
}
return result;
} | javascript | {
"resource": ""
} |
q25998 | getMatch | train | function getMatch(ctx, data, options) {
// Look for a command match, eliminating and then
// re-introducing leading spaces.
var len = ctx.length;
var trimmed = ctx.replace(/^\s+/g, '');
var match = autocomplete.match(trimmed, data.slice(), options);
if (_.isArray(match)) {
return match;
}
var prefix = new Array(len - trimmed.length + 1).join(' ');
// If we get an autocomplete match on a command, finish it.
if (match) {
// Put the leading spaces back in.
match = prefix + match;
return match;
}
return undefined;
} | javascript | {
"resource": ""
} |
q25999 | assembleInput | train | function assembleInput(input) {
if (_.isArray(input.context)) {
return input.context;
}
var result = (input.prefix || '') + (input.context || '') + (input.suffix || '');
return strip(result);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.