_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q21700
|
train
|
function(arg) {
if (!arg) {
return this;
}
if (arg instanceof RegExp) {
return this.filter(function(relativePath, file) {
return file.options.dir && arg.test(relativePath);
});
}
// else, name is a new folder
var name = this.root + arg;
var newFolder = folderAdd.call(this, name);
// Allow chaining by returning a new object with this folder as the root
var ret = this.clone();
ret.root = newFolder.name;
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q21701
|
train
|
function (buffer) {
JSZip.utils.checkSupport("blob");
try {
// Blob constructor
return new Blob([buffer], { type: "application/zip" });
}
catch(e) {}
try {
// deprecated, browser only, old way
var builder = new (window.BlobBuilder || window.WebKitBlobBuilder ||
window.MozBlobBuilder || window.MSBlobBuilder)();
builder.append(buffer);
return builder.getBlob('application/zip');
}
catch(e) {}
// well, fuck ?!
throw new Error("Bug : can't construct the Blob.");
}
|
javascript
|
{
"resource": ""
}
|
|
q21702
|
train
|
function (str) {
var buffer = JSZip.utils.transformTo("arraybuffer", str);
return JSZip.utils.arrayBuffer2Blob(buffer);
}
|
javascript
|
{
"resource": ""
}
|
|
q21703
|
dictsort
|
train
|
function dictsort(val, caseSensitive, by) {
if (!lib.isObject(val)) {
throw new lib.TemplateError('dictsort filter: val must be an object');
}
let array = [];
// deliberately include properties from the object's prototype
for (let k in val) { // eslint-disable-line guard-for-in, no-restricted-syntax
array.push([k, val[k]]);
}
let si;
if (by === undefined || by === 'key') {
si = 0;
} else if (by === 'value') {
si = 1;
} else {
throw new lib.TemplateError(
'dictsort filter: You can only sort by either key or value');
}
array.sort((t1, t2) => {
var a = t1[si];
var b = t2[si];
if (!caseSensitive) {
if (lib.isString(a)) {
a = a.toUpperCase();
}
if (lib.isString(b)) {
b = b.toUpperCase();
}
}
return a > b ? 1 : (a === b ? 0 : -1); // eslint-disable-line no-nested-ternary
});
return array;
}
|
javascript
|
{
"resource": ""
}
|
q21704
|
doNewDocument
|
train
|
function doNewDocument() {
// close old document first
var doc = mindmapModel.getDocument();
doCloseDocument();
var presenter = new mindmaps.NewDocumentPresenter(eventBus,
mindmapModel, new mindmaps.NewDocumentView());
presenter.go();
}
|
javascript
|
{
"resource": ""
}
|
q21705
|
doSaveDocument
|
train
|
function doSaveDocument() {
var presenter = new mindmaps.SaveDocumentPresenter(eventBus,
mindmapModel, new mindmaps.SaveDocumentView(), autosaveController, filePicker);
presenter.go();
}
|
javascript
|
{
"resource": ""
}
|
q21706
|
doOpenDocument
|
train
|
function doOpenDocument() {
var presenter = new mindmaps.OpenDocumentPresenter(eventBus,
mindmapModel, new mindmaps.OpenDocumentView(), filePicker);
presenter.go();
}
|
javascript
|
{
"resource": ""
}
|
q21707
|
updateView
|
train
|
function updateView(node) {
var font = node.text.font;
view.setBoldCheckboxState(font.weight === "bold");
view.setItalicCheckboxState(font.style === "italic");
view.setUnderlineCheckboxState(font.decoration === "underline");
view.setLinethroughCheckboxState(font.decoration === "line-through");
view.setFontColorPickerColor(font.color);
view.setBranchColorPickerColor(node.branchColor);
}
|
javascript
|
{
"resource": ""
}
|
q21708
|
calculateDraggerSize
|
train
|
function calculateDraggerSize() {
var cw = $container.width() / scale;
var ch = $container.height() / scale;
// doc.x / container.x = canvas.x / dragger.x
var width = (cw * canvasSize.x) / docSize.x;
var height = (ch * canvasSize.y) / docSize.y;
// limit size to bounds of canvas
if (width > canvasSize.x) {
width = canvasSize.x;
}
if (height > canvasSize.y) {
height = canvasSize.y;
}
view.setDraggerSize(width, height);
}
|
javascript
|
{
"resource": ""
}
|
q21709
|
calculateCanvasSize
|
train
|
function calculateCanvasSize() {
var width = view.getCanvasWidth();
var _scale = docSize.x / width;
var height = docSize.y / _scale;
view.setCanvasHeight(height);
canvasSize.x = width;
canvasSize.y = height;
}
|
javascript
|
{
"resource": ""
}
|
q21710
|
calculateDraggerPosition
|
train
|
function calculateDraggerPosition() {
var sl = $container.scrollLeft() / scale;
var st = $container.scrollTop() / scale;
// sl / dox = dl / cw
// dl = sl * cw / dox
var left = sl * canvasSize.x / docSize.x;
var top = st * canvasSize.y / docSize.y;
view.setDraggerPosition(left, top);
}
|
javascript
|
{
"resource": ""
}
|
q21711
|
documentOpened
|
train
|
function documentOpened(doc) {
docSize = doc.dimensions;
mindmap = doc.mindmap;
calculateCanvasSize();
calculateDraggerPosition();
calculateDraggerSize();
calculateZoomLevel();
calculateSliderValue();
renderView();
view.showActiveContent();
// move dragger when container was scrolled
$container.bind("scroll.navigator-view", function() {
if (!viewDragging) {
calculateDraggerPosition();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q21712
|
renderView
|
train
|
function renderView() {
// draw canvas
var scale = docSize.x / canvasSize.x;
view.draw(mindmap, scale);
}
|
javascript
|
{
"resource": ""
}
|
q21713
|
extractScriptNames
|
train
|
function extractScriptNames() {
console.log("Extracting script file names from index.html");
var regexScriptName = /<script src="(.*?)"><\/script>/g;
var scriptSection = regexScriptSection.exec(indexFile)[1];
// extract script names
var names = [];
var match;
while ((match = regexScriptName.exec(scriptSection)) != null) {
var script = match[1];
names.push(script);
}
return names;
}
|
javascript
|
{
"resource": ""
}
|
q21714
|
minifyScripts
|
train
|
function minifyScripts(scriptNames) {
console.log("Minifying and concatting scripts.");
var UglifyJS = require("uglify-js");
var regexMinifed = /min.js$/;
var regexCopyright = /^\/\*![\s\S]*?\*\//m;
var buffer = [];
scriptNames.forEach(function(script) {
var scriptFile = fs.readFileSync(srcDir + script, "utf8");
var copyright = regexCopyright.exec(scriptFile);
if (copyright) {
buffer.push(copyright);
}
// check if file is already minified
if (!regexMinifed.test(script)) {
var result = UglifyJS.minify(scriptFile);
if (result.error) {
throw new Error(error);
}
scriptFile = result.code;
} else {
console.log("> Skipping: " + script + " is already minified.");
}
buffer.push(scriptFile + ";");
});
var combined = buffer.join("\n");
fs.writeFileSync(publishDir + scriptDir + scriptFilename, combined);
console.log("Combined all scripts into " + scriptFilename);
}
|
javascript
|
{
"resource": ""
}
|
q21715
|
copyFiles
|
train
|
function copyFiles(dir) {
var files = fs.readdirSync(srcDir + dir);
files.forEach(function(file) {
var currentDir = dir + file;
if (!regexExcludeFiles.test(currentDir)) {
var stats = fs.statSync(srcDir + currentDir);
if (stats.isDirectory()) {
if (!fs.existsSync(publishDir + currentDir)) {
fs.mkdirSync(publishDir + currentDir);
}
copyFiles(currentDir + "/");
} else if (stats.isFile()) {
var contents = fs.readFileSync(srcDir + currentDir);
fs.writeFileSync(publishDir + currentDir, contents);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q21716
|
makeDraggable
|
train
|
function makeDraggable() {
self.$getContainer().dragscrollable({
dragSelector : "#drawing-area, canvas.line-canvas",
acceptPropagatedEvent : false,
delegateMode : true,
preventDefault : true
});
}
|
javascript
|
{
"resource": ""
}
|
q21717
|
drawNodeCanvas
|
train
|
function drawNodeCanvas(node, color) {
var parent = node.getParent();
var depth = node.getDepth();
var offsetX = node.offset.x;
var offsetY = node.offset.y;
color = color || node.branchColor;
var $node = $getNode(node);
var $parent = $getNode(parent);
var $canvas = $getNodeCanvas(node);
drawLineCanvas($canvas, depth, offsetX, offsetY, $node, $parent, color);
}
|
javascript
|
{
"resource": ""
}
|
q21718
|
CaptionEditor
|
train
|
function CaptionEditor(view) {
var self = this;
var attached = false;
// text input for node edits.
var $editor = $("<textarea/>", {
id : "caption-editor",
"class" : "node-text-behaviour"
}).bind("keydown", "esc", function() {
self.stop();
}).bind("keydown", "return", function() {
commitText();
}).mousedown(function(e) {
// avoid premature canceling
e.stopPropagation();
}).blur(function() {
commitText();
}).bind(
"input",
function() {
var metrics = textMetrics.getTextMetrics(self.node,
view.zoomFactor, $editor.val());
$editor.css(metrics);
alignBranches();
});
function commitText() {
if (attached && self.commit) {
self.commit(self.node, $editor.val());
}
}
function alignBranches() {
// slightly defer execution for better performance on slow
// browsers
setTimeout(function() {
view.redrawNodeConnectors(self.node);
}, 1);
}
/**
* Attaches the textarea to the node and temporarily removes the
* original node caption.
*
* @param {mindmaps.Node} node
* @param {jQuery} $cancelArea
*/
this.edit = function(node, $cancelArea) {
if (attached) {
return;
}
this.node = node;
attached = true;
// TODO put text into span and hide()
this.$text = $getNodeCaption(node);
this.$cancelArea = $cancelArea;
this.text = this.$text.text();
this.$text.css({
width : "auto",
height : "auto"
}).empty().addClass("edit");
// jquery ui prevents blur() event from happening when dragging a
// draggable. need this
// workaround to detect click on other draggable
$cancelArea.bind("mousedown.editNodeCaption", function(e) {
commitText();
});
var metrics = textMetrics.getTextMetrics(self.node,
view.zoomFactor, this.text);
$editor.attr({
value : this.text
}).css(metrics).appendTo(this.$text).select();
};
/**
* Removes the editor from the node and restores its old text value.
*/
this.stop = function() {
if (attached) {
attached = false;
this.$text.removeClass("edit");
$editor.detach();
this.$cancelArea.unbind("mousedown.editNodeCaption");
view.setNodeText(this.node, this.text);
alignBranches();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q21719
|
setupHelpButton
|
train
|
function setupHelpButton() {
var command = commandRegistry.get(mindmaps.HelpCommand);
command.setHandler(showHelp);
var notifications = [];
function showHelp() {
// true if atleast one notifications is still on screen
var displaying = notifications.some(function(noti) {
return noti.isVisible();
});
// hide notifications if visible
if (displaying) {
notifications.forEach(function(noti) {
noti.close();
});
notifications.length = 0;
return;
}
// show notifications
var helpRoot = new mindmaps.Notification(
".node-caption.root",
{
position : "bottomLeft",
closeButton : true,
maxWidth : 350,
title : "This is your main idea",
content : "Double click an idea to edit its text. Move the mouse over "
+ "an idea and drag the red circle to create a new idea."
});
var helpNavigator = new mindmaps.Notification(
"#navigator",
{
position : "leftTop",
closeButton : true,
maxWidth : 350,
padding : 20,
title : "This is the navigator",
content : "Use this panel to get an overview of your map. "
+ "You can navigate around by dragging the red rectangle or change the zoom by clicking on the magnifier buttons."
});
var helpInspector = new mindmaps.Notification(
"#inspector",
{
position : "leftTop",
closeButton : true,
maxWidth : 350,
padding : 20,
title : "This is the inspector",
content : "Use these controls to change the appearance of your ideas. "
+ "Try clicking the icon in the upper right corner to minimize this panel."
});
var helpToolbar = new mindmaps.Notification(
"#toolbar .buttons-left",
{
position : "bottomLeft",
closeButton : true,
maxWidth : 350,
title : "This is your toolbar",
content : "Those buttons do what they say. You can use them or work with keyboard shortcuts. "
+ "Hover over the buttons for the key combinations."
});
notifications.push(helpRoot, helpNavigator, helpInspector,
helpToolbar);
}
}
|
javascript
|
{
"resource": ""
}
|
q21720
|
roundedRect
|
train
|
function roundedRect(ctx, x, y, width, height, radius) {
// from MDN docs
ctx.beginPath();
ctx.moveTo(x, y + radius);
ctx.lineTo(x, y + height - radius);
ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
ctx.lineTo(x + width - radius, y + height);
ctx.quadraticCurveTo(x + width, y + height, x + width, y + height
- radius);
ctx.lineTo(x + width, y + radius);
ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
ctx.lineTo(x + radius, y);
ctx.quadraticCurveTo(x, y, x, y + radius);
ctx.stroke();
ctx.fill();
}
|
javascript
|
{
"resource": ""
}
|
q21721
|
train
|
function(node) {
if (!node) {
node = mindmapModel.selectedNode;
}
// toggle node visibility
var action = new mindmaps.action.ToggleNodeFoldAction(node);
mindmapModel.executeAction(action);
}
|
javascript
|
{
"resource": ""
}
|
|
q21722
|
showMindMap
|
train
|
function showMindMap(doc) {
view.setZoomFactor(zoomController.DEFAULT_ZOOM);
var dimensions = doc.dimensions;
view.setDimensions(dimensions.x, dimensions.y);
var map = doc.mindmap;
view.drawMap(map);
view.center();
mindmapModel.selectNode(map.root);
}
|
javascript
|
{
"resource": ""
}
|
q21723
|
bind
|
train
|
function bind() {
// listen to global events
eventBus.subscribe(mindmaps.Event.DOCUMENT_OPENED, function(doc,
newDocument) {
showMindMap(doc);
// if (doc.isNew()) {
// // edit root node on start
// var root = doc.mindmap.root;
// view.editNodeCaption(root);
// }
});
eventBus.subscribe(mindmaps.Event.DOCUMENT_CLOSED, function(doc) {
view.clear();
});
eventBus.subscribe(mindmaps.Event.NODE_MOVED, function(node) {
view.positionNode(node);
});
eventBus.subscribe(mindmaps.Event.NODE_TEXT_CAPTION_CHANGED, function(
node) {
view.setNodeText(node, node.getCaption());
// redraw node in case height has changed
// TODO maybe only redraw if height has changed
view.redrawNodeConnectors(node);
});
eventBus.subscribe(mindmaps.Event.NODE_CREATED, function(node) {
view.createNode(node);
// edit node caption immediately if requested
if (node.shouldEditCaption) {
delete node.shouldEditCaption;
// open parent node when creating a new child and the other
// children are hidden
var parent = node.getParent();
if (parent.foldChildren) {
var action = new mindmaps.action.OpenNodeAction(parent);
mindmapModel.executeAction(action);
}
// select and go into edit mode on new node
mindmapModel.selectNode(node);
// attach creator manually, sometimes the mouseover listener wont fire
creator.attachToNode(node);
view.editNodeCaption(node);
}
});
eventBus.subscribe(mindmaps.Event.NODE_DELETED, function(node, parent) {
// select parent if we are deleting a selected node or a descendant
var selected = mindmapModel.selectedNode;
if (node === selected || node.isDescendant(selected)) {
// deselectCurrentNode();
mindmapModel.selectNode(parent);
}
// update view
view.deleteNode(node);
if (parent.isLeaf()) {
view.removeFoldButton(parent);
}
});
eventBus.subscribe(mindmaps.Event.NODE_SELECTED, selectNode);
eventBus.subscribe(mindmaps.Event.NODE_OPENED, function(node) {
view.openNode(node);
});
eventBus.subscribe(mindmaps.Event.NODE_CLOSED, function(node) {
view.closeNode(node);
});
eventBus.subscribe(mindmaps.Event.NODE_FONT_CHANGED, function(node) {
view.updateNode(node);
});
eventBus.subscribe(mindmaps.Event.NODE_FONT_COLOR_PREVIEW, function(node, color) {
view.updateFontColor(node, color);
});
eventBus.subscribe(mindmaps.Event.NODE_BRANCH_COLOR_CHANGED, function(
node) {
view.updateNode(node);
});
eventBus.subscribe(mindmaps.Event.NODE_BRANCH_COLOR_PREVIEW, function(node, color) {
view.updateBranchColor(node, color)
});
eventBus.subscribe(mindmaps.Event.ZOOM_CHANGED, function(zoomFactor) {
view.setZoomFactor(zoomFactor);
view.applyViewZoom();
view.scaleMap();
});
}
|
javascript
|
{
"resource": ""
}
|
q21724
|
getBinaryMapWithDepth
|
train
|
function getBinaryMapWithDepth(depth) {
var mm = new mindmaps.MindMap();
var root = mm.root;
function createTwoChildren(node, depth) {
if (depth === 0) {
return;
}
var left = mm.createNode();
left.text.caption = "Node " + left.id;
node.addChild(left);
createTwoChildren(left, depth - 1);
var right = mm.createNode();
right.text.caption = "Node " + right.id;
node.addChild(right);
createTwoChildren(right, depth - 1);
}
// depth 10: about 400kb, 800kb in chrome
// depth 12: about 1600kb
// depth 16: 25mb
var depth = depth || 10;
createTwoChildren(root, depth);
// generate positions for all nodes.
// tree grows balanced from left to right
root.offset = new mindmaps.Point(400, 400);
// var offset = Math.pow(2, depth-1) * 10;
var offset = 80;
var c = root.children.values();
setOffset(c[0], 0, -offset);
setOffset(c[1], 0, offset);
function setOffset(node, depth, offsetY) {
node.offset = new mindmaps.Point((depth + 1) * 50, offsetY);
if (node.isLeaf()) {
return;
}
var c = node.children.values();
var left = c[0];
setOffset(left, depth + 1, offsetY - offsetY / 2);
var right = c[1];
setOffset(right, depth + 1, offsetY + offsetY / 2);
}
// color nodes
c[0].branchColor = mindmaps.Util.randomColor();
c[0].forEachDescendant(function(node) {
node.branchColor = mindmaps.Util.randomColor();
});
c[1].branchColor = mindmaps.Util.randomColor();
c[1].forEachDescendant(function(node) {
node.branchColor = mindmaps.Util.randomColor();
});
return mm;
}
|
javascript
|
{
"resource": ""
}
|
q21725
|
prepareNodes
|
train
|
function prepareNodes(mindmap) {
// clone tree since we modify it
var root = mindmap.getRoot().clone();
function addProps(node) {
var lineWidth = mindmaps.CanvasDrawingUtil.getLineWidth(zoomFactor,
node.getDepth());
var metrics = mindmaps.TextMetrics.getTextMetrics(node, zoomFactor);
var props = {
lineWidth : lineWidth,
textMetrics : metrics,
width : function() {
if (node.isRoot()) {
return 0;
}
return metrics.width;
},
innerHeight : function() {
return metrics.height + padding;
},
outerHeight : function() {
return metrics.height + lineWidth + padding;
}
};
$.extend(node, props);
node.forEachChild(function(child) {
addProps(child);
});
}
addProps(root);
return root;
}
|
javascript
|
{
"resource": ""
}
|
q21726
|
getMindMapDimensions
|
train
|
function getMindMapDimensions(root) {
var pos = root.getPosition();
var left = 0, top = 0, right = 0, bottom = 0;
var padding = 50;
function checkDimensions(node) {
var pos = node.getPosition();
var tm = node.textMetrics;
if (pos.x < left) {
left = pos.x;
}
if (pos.x + tm.width > right) {
right = pos.x + tm.width;
}
if (pos.y < top) {
top = pos.y;
}
if (pos.y + node.outerHeight() > bottom) {
bottom = pos.y + node.outerHeight();
}
}
checkDimensions(root);
root.forEachDescendant(function(node) {
checkDimensions(node);
});
// find the longest offset to either side and use twice the length for
// canvas width
var horizontal = Math.max(Math.abs(right), Math.abs(left));
var vertical = Math.max(Math.abs(bottom), Math.abs(top));
return {
width : 2 * horizontal + padding,
height : 2 * vertical + padding
};
}
|
javascript
|
{
"resource": ""
}
|
q21727
|
drawLines
|
train
|
function drawLines(node, parent) {
ctx.save();
var x = node.offset.x;
var y = node.offset.y;
ctx.translate(x, y);
// branch
if (parent) {
drawBranch(node, parent);
}
// bottom border
if (!node.isRoot()) {
ctx.fillStyle = node.branchColor;
var tm = node.textMetrics;
ctx.fillRect(0, tm.height + padding, tm.width, node.lineWidth);
}
node.forEachChild(function(child) {
drawLines(child, node);
});
ctx.restore();
}
|
javascript
|
{
"resource": ""
}
|
q21728
|
train
|
function() {
if (this.handler) {
this.handler();
if (mindmaps.DEBUG) {
console.log("handler called for", this.id);
}
} else {
if (mindmaps.DEBUG) {
console.log("no handler found for", this.id);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q21729
|
UndoManager
|
train
|
function UndoManager(maxStackSize) {
this.maxStackSize = maxStackSize || 64;
var State = {
UNDO : "undo",
REDO : "redo"
};
var self = this;
var undoStack = new UndoManager.CircularStack(this.maxStackSize);
var redoStack = new UndoManager.CircularStack(this.maxStackSize);
var undoContext = false;
var currentAction = null;
var currentState = null;
var onStateChange = function() {
if (self.stateChanged) {
self.stateChanged();
}
};
var callAction = function(action) {
currentAction = action;
undoContext = true;
switch (currentState) {
case State.UNDO:
action.undo();
break;
case State.REDO:
action.redo();
break;
}
undoContext = false;
};
/**
* Register an undo operation. A call to .undo() will cause the undo
* function to be executed. If you omit the second argument and the undo
* function will cause the registration of another undo operation, then this
* operation will be used as the redo function.
*
* If you provide both arguments, a call to addUndo() during an undo() or
* redo() will have no effect.
*
*
* @param {Function} undoFunc The function that should undo the changes.
* @param {Function} [redoFunc] The function that should redo the undone
* changes.
*/
this.addUndo = function(undoFunc, redoFunc) {
if (undoContext) {
/**
* If we are currently undoing an action and don't have a redo
* function yet, store the undo function to the undo function, which
* is in turn the redo function.
*/
if (currentAction.redo == null && currentState == State.UNDO) {
currentAction.redo = undoFunc;
}
} else {
/**
* We are not undoing right now. Store the functions as an action.
*/
var action = {
undo : undoFunc,
redo : redoFunc
};
undoStack.push(action);
// clear redo stack
redoStack.clear();
onStateChange();
}
};
/**
* Undoes the last action.
*/
this.undo = function() {
if (this.canUndo()) {
currentState = State.UNDO;
var action = undoStack.pop();
callAction(action);
if (action.redo) {
redoStack.push(action);
}
onStateChange();
}
};
/**
* Redoes the last action.
*/
this.redo = function() {
if (this.canRedo()) {
currentState = State.REDO;
var action = redoStack.pop();
callAction(action);
if (action.undo) {
undoStack.push(action);
}
onStateChange();
}
};
/**
*
* @returns {Boolean} true if undo is possible, false otherwise.
*/
this.canUndo = function() {
return !undoStack.isEmpty();
};
/**
*
* @returns {Boolean} true if redo is possible, false otherwise.
*/
this.canRedo = function() {
return !redoStack.isEmpty();
};
/**
* Resets this instance of the undo manager.
*/
this.reset = function() {
undoStack.clear();
redoStack.clear();
undoContext = false;
currentAction = null;
currentState = null;
onStateChange();
};
/**
* Event that is fired when undo or redo state changes.
*
* @event
*/
this.stateChanged = function() {
};
}
|
javascript
|
{
"resource": ""
}
|
q21730
|
train
|
function(doc) {
try {
localStorage.setItem(prefix + doc.id, doc.serialize());
return true;
} catch (error) {
// QUOTA_EXCEEDED
console.error("Error while saving document to local storage",
error);
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q21731
|
train
|
function() {
var documents = [];
// search localstorage for saved documents
for ( var i = 0, max = localStorage.length; i < max; i++) {
var key = localStorage.key(i);
// value is a document if key confirms to prefix
if (key.indexOf(prefix) == 0) {
var doc = getDocumentByKey(key);
if (doc) {
documents.push(doc);
}
}
}
return documents;
}
|
javascript
|
{
"resource": ""
}
|
|
q21732
|
train
|
function() {
var ids = [];
// search localstorage for saved documents
for ( var i = 0, max = localStorage.length; i < max; i++) {
var key = localStorage.key(i);
// value is a document if key confirms to prefix
if (key.indexOf(prefix) == 0) {
ids.push(key.substring(prefix.length));
}
}
return ids;
}
|
javascript
|
{
"resource": ""
}
|
|
q21733
|
addUnloadHook
|
train
|
function addUnloadHook () {
window.onbeforeunload = function (e) {
var msg = "Are you sure? Any unsaved progress will be lost."
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
};
}
|
javascript
|
{
"resource": ""
}
|
q21734
|
setupConsole
|
train
|
function setupConsole() {
var noOp = function() {};
// provide console object and dummy functions if not built-in
var console = window.console || {};
['log', 'info', 'debug', 'warn', 'error'].forEach(function(prop) {
console[prop] = console[prop] || noOp;
});
// turn all console.xx calls into no-ops when in production mode except
// for errors, do an alert.
if (!mindmaps.DEBUG) {
console.debug = noOp;
console.info = noOp;
console.log = noOp;
console.warn = noOp;
console.error = function(s) {
window.alert("Error: " + s);
};
}
window.console = console;
}
|
javascript
|
{
"resource": ""
}
|
q21735
|
createHTML5Shims
|
train
|
function createHTML5Shims() {
// localstorage dummy (does nothing)
if (typeof window.localStorage == 'undefined') {
window.localStorage = {
getItem : function() {
return null;
},
setItem : function() {
},
clear : function() {
},
removeItem : function() {
},
length : 0,
key : function() {
return null;
}
};
}
}
|
javascript
|
{
"resource": ""
}
|
q21736
|
getReadmeText
|
train
|
function getReadmeText(pkg) {
const pkgDir = atPackagesDirectory().dir(pkg);
const generatedDoc = pkgDir.read('./docs/docs.md');
if (generatedDoc) pkgDir.write('Readme.md', generatedDoc);
const text = pkgDir.read(README);
if (text) return text;
else return ''; // don't return "undefined"
}
|
javascript
|
{
"resource": ""
}
|
q21737
|
getDocObject
|
train
|
function getDocObject(dir, info) {
const markdown = getReadmeText(dir);
const html = marked(markdown);
const cleanedHTML = prepareHTML(html, info);
return { pkg: dir, html: cleanedHTML };
}
|
javascript
|
{
"resource": ""
}
|
q21738
|
get
|
train
|
function get( obj ) {
var pending = 0
, res = {}
, callback
, done;
return function _( arg ) {
switch(typeof arg) {
case 'function':
callback = arg;
break;
case 'string':
++pending;
obj[ arg ](function( err, val ) {
if( done ) return;
if( err ) return done = true, callback(err);
res[ arg ] = val;
--pending || callback(null, res);
});
break;
}
return _;
};
}
|
javascript
|
{
"resource": ""
}
|
q21739
|
init
|
train
|
function init(state) {
var canvas = o('#loading canvas').get(0)
, ctx = canvas.getContext('2d');
loading = new LoadingIndicator;
loading.ctx = ctx;
loading.size(canvas.width);
pollStats(1000);
show(state)();
o('li.inactive a').click(show('inactive'));
o('li.complete a').click(show('complete'));
o('li.active a').click(show('active'));
o('li.failed a').click(show('failed'));
o('li.delayed a').click(show('delayed'));
o('#filter').change(function () {
filter = $(this).val();
});
o('#sort').change(function () {
sort = $(this).val();
o('#jobs .job').remove();
});
onpopstate = function (e) {
if (e.state) show(e.state.state)();
};
}
|
javascript
|
{
"resource": ""
}
|
q21740
|
showLoading
|
train
|
function showLoading() {
var n = 0;
o('#loading').show();
showLoading.timer = setInterval(function () {
loading.update(++n).draw(loading.ctx);
}, 50);
}
|
javascript
|
{
"resource": ""
}
|
q21741
|
infiniteScroll
|
train
|
function infiniteScroll() {
if (infiniteScroll.bound) return;
var body = o('body');
hideLoading();
infiniteScroll.bound = true;
o(window).scroll(function (e) {
var top = body.scrollTop()
, height = body.innerHeight()
, windowHeight = window.innerHeight
, pad = 30;
if (top + windowHeight + pad >= height) {
to += more;
infiniteScroll.bound = false;
showLoading();
o(window).unbind('scroll');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q21742
|
show
|
train
|
function show(state) {
return function () {
active = state;
if (pollForJobs.timer) {
clearTimeout(pollForJobs.timer);
delete pollForJobs.timer;
}
history.pushState({ state: state }, state, state);
o('#jobs .job').remove();
o('#menu li a').removeClass('active');
o('#menu li.' + state + ' a').addClass('active');
pollForJobs(state, 1000);
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q21743
|
pollForJobs
|
train
|
function pollForJobs(state, ms) {
o('h1').text(state);
refreshJobs(state, function () {
infiniteScroll();
if (!pollForJobs.timer) pollForJobs.timer = setTimeout(function () {
delete pollForJobs.timer;
pollForJobs(state, ms);
}, ms);
});
}
|
javascript
|
{
"resource": ""
}
|
q21744
|
refreshJobs
|
train
|
function refreshJobs(state, fn) {
// TODO: clean this crap up
var jobHeight = o('#jobs .job .block').outerHeight(true)
, top = o(window).scrollTop()
, height = window.innerHeight
, visibleFrom = Math.max(0, Math.floor(top / jobHeight))
, visibleTo = Math.floor((top + height) / jobHeight)
, url = './jobs/'
+ (filter ? filter + '/' : '')
+ state + '/0..' + to
+ '/' + sort;
// var color = ['blue', 'red', 'yellow', 'green', 'purple'][Math.random() * 5 | 0];
request(url, function (jobs) {
var len = jobs.length
, job
, el;
// remove jobs which have changed their state
o('#jobs .job').each(function (i, el) {
var el = $(el)
, id = (el.attr('id') || '').replace('job-', '')
, found = jobs.some(function (job) {
return job && id == job.id;
});
if (!found) el.remove();
});
for (var i = 0; i < len; ++i) {
if (!jobs[i]) continue;
// exists
if (o('#job-' + jobs[i].id).length) {
if (i < visibleFrom || i > visibleTo) continue;
el = o('#job-' + jobs[i].id);
// el.css('background-color', color);
job = el.get(0).job;
job.update(jobs[i])
.showProgress('active' == active)
.showErrorMessage('failed' == active)
.render();
// new
} else {
job = new Job(jobs[i]);
el = job.showProgress('active' == active)
.showErrorMessage('failed' == active)
.render(true);
el.get(0).job = job;
el.appendTo('#jobs');
}
}
fn();
});
}
|
javascript
|
{
"resource": ""
}
|
q21745
|
pollStats
|
train
|
function pollStats(ms) {
request('./stats', function (data) {
o('li.inactive .count').text(data.inactiveCount);
o('li.active .count').text(data.activeCount);
o('li.complete .count').text(data.completeCount);
o('li.failed .count').text(data.failedCount);
o('li.delayed .count').text(data.delayedCount);
setTimeout(function () {
pollStats(ms);
}, ms);
});
}
|
javascript
|
{
"resource": ""
}
|
q21746
|
create
|
train
|
function create() {
var name = [ 'tobi', 'loki', 'jane', 'manny' ][ Math.random() * 4 | 0 ];
var job = jobs.create( 'video conversion', {
title: 'converting ' + name + '\'s to avi', user: 1, frames: 200
} );
job.on( 'complete', function () {
console.log( " Job complete" );
} ).on( 'failed', function () {
console.log( " Job failed" );
} ).on( 'progress', function ( progress ) {
process.stdout.write( '\r job #' + job.id + ' ' + progress + '% complete' );
} );
job.save();
setTimeout( create, Math.random() * 2000 | 0 );
}
|
javascript
|
{
"resource": ""
}
|
q21747
|
compose
|
train
|
function compose() {
var fnList = arguments;
return function composed(initialArg) {
var ret = initialArg;
for (var i = 0; i < fnList.length; i++) {
var fn = fnList[i];
ret = fn.call(null, ret);
}
return ret;
};
}
|
javascript
|
{
"resource": ""
}
|
q21748
|
tweenDone
|
train
|
function tweenDone() {
if (self._replacedScene) {
self._removeSceneEventListeners(self._replacedScene);
oldSceneLayers = self._replacedScene.listLayers();
for (var i = 0; i < oldSceneLayers.length; i++) {
self._removeLayerFromStage(oldSceneLayers[i]);
}
self._replacedScene = null;
}
self._cancelCurrentTween = null;
done();
}
|
javascript
|
{
"resource": ""
}
|
q21749
|
rotateVector
|
train
|
function rotateVector(vec, z, x, y) {
if (z) {
vec3.rotateZ(vec, vec, origin, z);
}
if (x) {
vec3.rotateX(vec, vec, origin, x);
}
if (y) {
vec3.rotateY(vec, vec, origin, y);
}
}
|
javascript
|
{
"resource": ""
}
|
q21750
|
stopTouchAndScrollEventPropagation
|
train
|
function stopTouchAndScrollEventPropagation(element, eventList) {
var eventList = [ 'touchstart', 'touchmove', 'touchend', 'touchcancel',
'wheel', 'mousewheel' ];
for (var i = 0; i < eventList.length; i++) {
element.addEventListener(eventList[i], function(event) {
event.stopPropagation();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q21751
|
DeviceOrientationControlMethod
|
train
|
function DeviceOrientationControlMethod() {
this._dynamics = {
yaw: new Marzipano.Dynamics(),
pitch: new Marzipano.Dynamics()
};
this._deviceOrientationHandler = this._handleData.bind(this);
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', this._deviceOrientationHandler);
}
this._previous = {};
this._current = {};
this._tmp = {};
this._getPitchCallbacks = [];
}
|
javascript
|
{
"resource": ""
}
|
q21752
|
checkCssSupported
|
train
|
function checkCssSupported() {
// First, check if the 'perspective' CSS property or a vendor-prefixed
// variant is available.
var perspectiveProperty = prefixProperty('perspective');
var el = document.createElement('div');
var supported = typeof el.style[perspectiveProperty] !== 'undefined';
// Certain versions of Chrome disable 3D transforms even though the CSS
// property exists. In those cases, we use the following media query,
// which only succeeds if the feature is indeed enabled.
if (supported && perspectiveProperty === 'WebkitPerspective') {
var id = '__marzipano_test_css3d_support__';
var st = document.createElement('style');
st.textContent = '@media(-webkit-transform-3d){#' + id + '{height: 3px;})';
document.getElementsByTagName('head')[0].appendChild(st);
el.id = id;
document.body.appendChild(el);
// The offsetHeight seems to be different than 3 at some zoom levels on
// Chrome (and maybe other browsers). Test for > 0 instead.
supported = el.offsetHeight > 0;
st.parentNode.removeChild(st);
el.parentNode.removeChild(el);
}
return supported;
}
|
javascript
|
{
"resource": ""
}
|
q21753
|
applyToPixel
|
train
|
function applyToPixel(pixel, effect, result) {
vec4TransformMat4Transposed(result, pixel, effect.colorMatrix);
vec4.add(result, result, effect.colorOffset);
}
|
javascript
|
{
"resource": ""
}
|
q21754
|
TextureStore
|
train
|
function TextureStore(source, stage, opts) {
opts = defaults(opts || {}, defaultOptions);
this._source = source;
this._stage = stage;
// The current state.
this._state = State.IDLE;
// The number of startFrame calls yet to be matched by endFrame calls during
// the current frame.
this._delimCount = 0;
// The cache proper: map cached tiles to their respective textures/assets.
this._itemMap = new Map();
// The subset of cached tiles that are currently visible.
this._visible = new Set();
// The subset of cached tiles that were visible recently, but are not
// visible right now. Newly inserted tiles replace older ones.
this._previouslyVisible = new LruSet(opts.previouslyVisibleCacheSize);
// The subset of cached tiles that should never be evicted from the cache.
// A tile may be pinned more than once; map each tile into a reference count.
this._pinMap = new Map();
// Temporary variables.
this._newVisible = new Set();
this._noLongerVisible = [];
this._visibleAgain = [];
this._evicted = [];
}
|
javascript
|
{
"resource": ""
}
|
q21755
|
retry
|
train
|
function retry(fn) {
return function retried() {
var args = arguments.length ? Array.prototype.slice.call(arguments, 0, arguments.length - 1) : [];
var done = arguments.length ? arguments[arguments.length - 1] : noop;
var cfn = null;
var canceled = false;
function exec() {
var err = arguments[0];
if (!err || canceled) {
done.apply(null, arguments);
} else {
cfn = fn.apply(null, args);
}
}
args.push(exec);
exec(true);
return function cancel() {
canceled = true;
cfn.apply(null, arguments);
};
};
}
|
javascript
|
{
"resource": ""
}
|
q21756
|
ready
|
train
|
function ready() {
for (var i = 0; i < preloadTiles.length; i++) {
var state = layerAbove.textureStore().query(preloadTiles[i]);
if (!state.hasTexture) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q21757
|
setViewport
|
train
|
function setViewport(gl, layer, rect, viewportMatrix) {
if (rect.x === 0 && rect.width === 1 && rect.y === 0 && rect.height === 1) {
// Fast path for full rect.
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
mat4.identity(viewportMatrix);
return;
}
var offsetX = rect.x;
var clampedOffsetX = clamp(offsetX, 0, 1);
var leftExcess = clampedOffsetX - offsetX;
var maxClampedWidth = 1 - clampedOffsetX;
var clampedWidth = clamp(rect.width - leftExcess, 0, maxClampedWidth);
var rightExcess = rect.width - clampedWidth;
var offsetY = 1 - rect.height - rect.y;
var clampedOffsetY = clamp(offsetY, 0, 1);
var bottomExcess = clampedOffsetY - offsetY;
var maxClampedHeight = 1 - clampedOffsetY;
var clampedHeight = clamp(rect.height - bottomExcess, 0, maxClampedHeight);
var topExcess = rect.height - clampedHeight;
vec3.set(
scaleVector,
rect.width / clampedWidth,
rect.height / clampedHeight,
1);
vec3.set(
translateVector,
(rightExcess - leftExcess) / clampedWidth,
(topExcess - bottomExcess) / clampedHeight,
0);
mat4.identity(viewportMatrix);
mat4.translate(viewportMatrix, viewportMatrix, translateVector);
mat4.scale(viewportMatrix, viewportMatrix, scaleVector);
gl.viewport(gl.drawingBufferWidth * clampedOffsetX,
gl.drawingBufferHeight * clampedOffsetY,
gl.drawingBufferWidth * clampedWidth,
gl.drawingBufferHeight * clampedHeight);
}
|
javascript
|
{
"resource": ""
}
|
q21758
|
exec
|
train
|
function exec() {
// Extract error from arguments.
var err = arguments[0];
// Abort chain on error.
if (err) {
fn = cfn = null;
done.apply(null, arguments);
return;
}
// Terminate if there are no functions left in the chain.
if (!fnList.length) {
fn = cfn = null;
done.apply(null, arguments);
return;
}
// Advance to the next function in the chain.
fn = fnList.shift();
var _fn = fn;
// Extract arguments to pass into the next function.
var ret = Array.prototype.slice.call(arguments, 1);
// Call next function with previous return value and call back exec.
ret.push(exec);
var _cfn = fn.apply(null, ret); // fn(null, ret..., exec)
// Detect when fn has completed synchronously and do not clobber the
// internal state in that case. You're not expected to understand this.
if (_fn !== fn) {
return;
}
// Remember the cancel method for the currently executing function.
// Detect chaining on non-cancellable function.
if (typeof _cfn !== 'function') {
throw new Error('chain: chaining on non-cancellable function');
} else {
cfn = _cfn;
}
}
|
javascript
|
{
"resource": ""
}
|
q21759
|
inherits
|
train
|
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function() {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
|
javascript
|
{
"resource": ""
}
|
q21760
|
fileToCanvas
|
train
|
function fileToCanvas(file, done) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.onload = function() {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
done(null, canvas);
};
img.onerror = function(err) {
done(err);
};
img.src = URL.createObjectURL(file);
}
|
javascript
|
{
"resource": ""
}
|
q21761
|
importLayer
|
train
|
function importLayer(file) {
fileToCanvas(file, function(err, canvas) {
if (err) {
alert('Unable to load image file.');
return;
}
if (canvas.width > maxSize || canvas.height > maxSize) {
alert('Image is too large. The maximum supported size is ' +
maxSize + ' by ' + maxSize + ' pixels.');
return;
}
// Create layer.
var asset = new Marzipano.DynamicAsset(canvas);
var source = new Marzipano.SingleAssetSource(asset);
var geometry = new Marzipano.EquirectGeometry([{ width: canvas.width }]);
var layer = scene.createLayer({
source: source,
geometry: geometry
});
// Create a new effects object for the layer.
var effects = layerEffects(layer);
// Add layer into the view model.
layers.unshift({
name: file.name,
layer: layer,
effects: effects,
canvas: canvas
});
});
}
|
javascript
|
{
"resource": ""
}
|
q21762
|
discardLayer
|
train
|
function discardLayer(item) {
if (confirm('Remove this layer?')) {
scene.destroyLayer(item.layer);
layers.remove(item);
}
}
|
javascript
|
{
"resource": ""
}
|
q21763
|
disableControlsTemporarily
|
train
|
function disableControlsTemporarily() {
viewer.controls().disableMethod('touchView');
viewer.controls().disableMethod('pinch');
setTimeout(function() {
viewer.controls().enableMethod('touchView');
viewer.controls().enableMethod('pinch');
}, 200);
}
|
javascript
|
{
"resource": ""
}
|
q21764
|
zoomOnTap
|
train
|
function zoomOnTap(e) {
var coords = viewer.view().screenToCoordinates(e.center);
coords.fov = viewer.view().fov() * 0.8;
viewer.lookTo(coords, { transitionDuration: 300 });
}
|
javascript
|
{
"resource": ""
}
|
q21765
|
train
|
function(min, max) {
return function limitX(params) {
params.x = clamp(params.x, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21766
|
train
|
function(min, max) {
return function limitY(params) {
params.y = clamp(params.y, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21767
|
train
|
function(min, max) {
return function limitZoom(params) {
params.zoom = clamp(params.zoom, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21768
|
train
|
function(min, max) {
return function limitVisibleX(params) {
// Calculate the zoom value that makes the specified range fully visible.
var maxZoom = max - min;
// Clamp zoom to the maximum value.
if (params.zoom > maxZoom) {
params.zoom = maxZoom;
}
// Bound X such that the image is visible up to the range edges.
var minX = min + 0.5 * params.zoom;
var maxX = max - 0.5 * params.zoom;
params.x = clamp(params.x, minX, maxX);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21769
|
train
|
function(min, max) {
return function limitVisibleY(params) {
// Do nothing for a null viewport.
if (params.width <= 0 || params.height <= 0) {
return params;
}
// Calculate the X to Y conversion factor.
var viewportAspectRatio = params.width / params.height;
var factor = viewportAspectRatio / params.mediaAspectRatio;
// Calculate the zoom value that makes the specified range fully visible.
var maxZoom = (max - min) * factor;
// Clamp zoom to the maximum value.
if (params.zoom > maxZoom) {
params.zoom = maxZoom;
}
// Bound Y such that the image is visible up to the range edges.
var minY = min + 0.5 * params.zoom / factor;
var maxY = max - 0.5 * params.zoom / factor;
params.y = clamp(params.y, minY, maxY);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21770
|
train
|
function() {
return function limitLetterbox(params) {
if(params.width <= 0 || params.height <= 0) {
return params;
}
var viewportAspectRatio = params.width / params.height;
var fullWidthZoom = 1.0;
var fullHeightZoom = viewportAspectRatio / params.mediaAspectRatio;
// If the image is wider than the viewport, limit the horizontal zoom to
// the image width.
if (params.mediaAspectRatio >= viewportAspectRatio) {
params.zoom = Math.min(params.zoom, fullWidthZoom);
}
// If the image is narrower than the viewport, limit the vertical zoom to
// the image height.
if (params.mediaAspectRatio <= viewportAspectRatio) {
params.zoom = Math.min(params.zoom, fullHeightZoom);
}
// If the full image width is visible, limit x to the central point.
// Else, bound x such that image is visible up to the horizontal edges.
var minX, maxX;
if (params.zoom > fullWidthZoom) {
minX = maxX = 0.5;
} else {
minX = 0.0 + 0.5 * params.zoom / fullWidthZoom;
maxX = 1.0 - 0.5 * params.zoom / fullWidthZoom;
}
// If the full image height is visible, limit y to the central point.
// Else, bound y such that image is visible up to the vertical edges.
var minY, maxY;
if (params.zoom > fullHeightZoom) {
minY = maxY = 0.5;
} else {
minY = 0.0 + 0.5 * params.zoom / fullHeightZoom;
maxY = 1.0 - 0.5 * params.zoom / fullHeightZoom;
}
// Clamp x and y into the calculated bounds.
params.x = clamp(params.x, minX, maxX);
params.y = clamp(params.y, minY, maxY);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21771
|
async
|
train
|
function async(fn) {
return function asynced(done) {
var err, ret;
try {
ret = fn();
} catch (e) {
err = e;
} finally {
if (err) {
done(err);
} else {
done(null, ret);
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q21772
|
VideoAsset
|
train
|
function VideoAsset(videoElement) {
this._videoElement = null;
this._destroyed = false;
this._emitChange = this.emit.bind(this, 'change');
this._lastTimestamp = -1;
this._emptyCanvas = document.createElement('canvas');
this._emptyCanvas.width = 1;
this._emptyCanvas.height = 1;
this.setVideo(videoElement);
}
|
javascript
|
{
"resource": ""
}
|
q21773
|
train
|
function(min, max) {
return function limitYaw(params) {
params.yaw = clamp(params.yaw, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21774
|
train
|
function(min, max) {
return function limitPitch(params) {
params.pitch = clamp(params.pitch, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21775
|
train
|
function(min, max) {
return function limitRoll(params) {
params.roll = clamp(params.roll, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21776
|
train
|
function(min, max) {
return function limitHfov(params) {
var width = params.width;
var height = params.height;
if (width > 0 && height > 0) {
var vmin = convertFov.htov(min, width, height);
var vmax = convertFov.htov(max, width, height);
params.fov = clamp(params.fov, vmin, vmax);
}
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21777
|
train
|
function(min, max) {
return function limitVfov(params) {
params.fov = clamp(params.fov, min, max);
return params;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q21778
|
checkCssPointerEventsSupported
|
train
|
function checkCssPointerEventsSupported() {
// Check for existence of CSS property.
var style = document.createElement('a').style;
style.cssText = 'pointer-events:auto';
var hasCssProperty = style.pointerEvents === 'auto';
// The above result is spurious on emulation mode for IE 8-10.
var isOldIE = browser.msie && parseFloat(browser.version) < 11;
return hasCssProperty && !isOldIE;
}
|
javascript
|
{
"resource": ""
}
|
q21779
|
loadVideoInSync
|
train
|
function loadVideoInSync(url, syncElement, cb) {
cb = once(cb);
var element = document.createElement('video');
element.crossOrigin = 'anonymous';
element.autoplay = true;
element.loop = true;
// Prevent the video from going full screen on iOS.
element.playsInline = true;
element.webkitPlaysInline = true;
element.onerror = function(e) {
cb(e.target.error);
};
// The new video will be loaded at currentTime + 5s, to allow time for
// the video to be ready to play
var syncTime = 5000;
element.src = url;
// Checking readyState on an interval seems to be more reliable than using events
waitForReadyState(element, element.HAVE_CURRENT_DATA, 0.2, function() {
if(syncElement) {
if(syncElement.paused) {
// If the video is not playing, we can load the new one to the correct time
element.currentTime = syncElement.currentTime;
}
else {
//If it is playing, we will need to load to a time ahead of the current,
// to account for the time that the loading will take
element.currentTime = syncElement.currentTime + syncTime / 1000;
}
}
waitForReadyState(element, element.HAVE_ENOUGH_DATA, 0.2, function() {
if(!syncElement) {
// If there is no element to sync with we are done
cb(null, element);
}
else if(syncElement.paused) {
// If the element to sync with is paused, we are done
cb(null, element);
}
else {
if(element.currentTime <= syncElement.currentTime) {
// The loading took too long, start playing immediately
// We will be a bit out of sync
element.play();
cb(null, element);
}
else {
// If the loading was too fast, wait before playing
// We should be in sync
setTimeout(function() {
element.play();
cb(null, element);
}, (element.currentTime - syncElement.currentTime) * 1000);
}
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q21780
|
Layer
|
train
|
function Layer(source, geometry, view, textureStore, opts) {
opts = opts || {};
var self = this;
this._source = source;
this._geometry = geometry;
this._view = view;
this._textureStore = textureStore;
this._effects = opts.effects || {};
this._fixedLevelIndex = null;
this._viewChangeHandler = function() {
self.emit('viewChange', self.view());
};
this._view.addEventListener('change', this._viewChangeHandler);
this._textureStoreChangeHandler = function() {
self.emit('textureStoreChange', self.textureStore());
};
this._textureStore.addEventListener('textureLoad',
this._textureStoreChangeHandler);
this._textureStore.addEventListener('textureError',
this._textureStoreChangeHandler);
this._textureStore.addEventListener('textureInvalid',
this._textureStoreChangeHandler);
}
|
javascript
|
{
"resource": ""
}
|
q21781
|
Stage
|
train
|
function Stage(opts) {
this._progressive = !!(opts && opts.progressive);
// The list of layers in display order (background to foreground).
this._layers = [];
// The list of renderers; the i-th renderer is for the i-th layer.
this._renderers = [];
// The lists of tiles to load and render, populated during render().
this._tilesToLoad = [];
this._tilesToRender = [];
// Temporary tile lists.
this._tmpVisible = [];
this._tmpChildren = [];
// Cached stage dimensions.
// Start with zero, which inhibits rendering until setSize() is called.
this._width = 0;
this._height = 0;
// Temporary variable for rect.
this._tmpRect = {};
// Temporary variable for size.
this._tmpSize = {};
// Work queue for createTexture.
this._createTextureWorkQueue = new WorkQueue();
// Function to emit event when render parameters have changed.
this._emitRenderInvalid = this._emitRenderInvalid.bind(this);
// The renderer registry maps each geometry/view pair into the respective
// Renderer class.
this._rendererRegistry = new RendererRegistry();
}
|
javascript
|
{
"resource": ""
}
|
q21782
|
nextScene
|
train
|
function nextScene() {
switch (currentScene) {
case scene1: return (currentScene = scene2);
case scene2: return (currentScene = scene1);
default: return (currentScene = scene1);
}
}
|
javascript
|
{
"resource": ""
}
|
q21783
|
tryStart
|
train
|
function tryStart() {
if (started) {
return;
}
started = true;
var video = document.createElement('video');
video.src = '//www.marzipano.net/media/video/mercedes-f1-1280x640.mp4';
video.crossOrigin = 'anonymous';
video.autoplay = true;
video.loop = true;
// Prevent the video from going full screen on iOS.
video.playsInline = true;
video.webkitPlaysInline = true;
video.play();
waitForReadyState(video, video.HAVE_METADATA, 100, function() {
waitForReadyState(video, video.HAVE_ENOUGH_DATA, 100, function() {
asset.setVideo(video);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q21784
|
waitForReadyState
|
train
|
function waitForReadyState(element, readyState, interval, done) {
var timer = setInterval(function() {
if (element.readyState >= readyState) {
clearInterval(timer);
done(null, true);
}
}, interval);
}
|
javascript
|
{
"resource": ""
}
|
q21785
|
clearOwnProperties
|
train
|
function clearOwnProperties(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = undefined;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q21786
|
do_replyto_header
|
train
|
function do_replyto_header (cb) {
const replyto = trans.header.get('reply-to');
const rmatch = email_re.exec(replyto);
if (rmatch) {
return plugin.do_lookups(connection, cb, rmatch[1], 'replyto');
}
cb();
}
|
javascript
|
{
"resource": ""
}
|
q21787
|
do_msgid_header
|
train
|
function do_msgid_header (cb) {
const msgid = trans.header.get('message-id');
const mmatch = /@([^>]+)>/.exec(msgid);
if (mmatch) {
return plugin.do_lookups(connection, cb, mmatch[1], 'msgid');
}
cb();
}
|
javascript
|
{
"resource": ""
}
|
q21788
|
get_pool
|
train
|
function get_pool (port, host, local_addr, is_unix_socket, max) {
port = port || 25;
host = host || 'localhost';
const name = `outbound::${port}:${host}:${local_addr}:${cfg.pool_timeout}`;
if (!server.notes.pool) server.notes.pool = {};
if (server.notes.pool[name]) return server.notes.pool[name];
const pool = generic_pool.Pool({
name,
create: function (done) {
_create_socket(this.name, port, host, local_addr, is_unix_socket, done);
},
validate: socket => socket.__fromPool && socket.writable,
destroy: socket => {
logger.logdebug(`[outbound] destroying pool entry ${socket.__uuid} for ${host}:${port}`);
socket.removeAllListeners();
socket.__fromPool = false;
socket.on('line', line => {
// Just assume this is a valid response
logger.logprotocol(`[outbound] S: ${line}`);
});
socket.once('error', err => {
logger.logwarn(`[outbound] Socket got an error while shutting down: ${err}`);
});
socket.once('end', () => {
logger.loginfo("[outbound] Remote end half closed during destroy()");
socket.destroy();
})
if (socket.writable) {
logger.logprotocol(`[outbound] [${socket.__uuid}] C: QUIT`);
socket.write("QUIT\r\n");
}
socket.end(); // half close
},
max: max || 10,
idleTimeoutMillis: cfg.pool_timeout * 1000,
log: (str, level) => {
if (/this._availableObjects.length=/.test(str)) return;
level = (level === 'verbose') ? 'debug' : level;
logger[`log${level}`](`[outbound] [${name}] ${str}`);
}
});
server.notes.pool[name] = pool;
return pool;
}
|
javascript
|
{
"resource": ""
}
|
q21789
|
sort_mx
|
train
|
function sort_mx (mx_list) {
const sorted = mx_list.sort((a,b) => a.priority - b.priority);
// This isn't a very good shuffle but it'll do for now.
for (let i=0,l=sorted.length-1; i<l; i++) {
if (sorted[i].priority === sorted[i+1].priority) {
if (Math.round(Math.random())) { // 0 or 1
const j = sorted[i];
sorted[i] = sorted[i+1];
sorted[i+1] = j;
}
}
}
return sorted;
}
|
javascript
|
{
"resource": ""
}
|
q21790
|
setupListener
|
train
|
function setupListener (host_port, listenerDone) {
const hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
if (!hp) return listenerDone(
new Error('Invalid "listen" format in smtp.ini'));
const host = hp[1];
const port = parseInt(hp[2], 10);
Server.get_smtp_server(host, port, inactivity_timeout, (server) => {
if (!server) return listenerDone();
server.notes = Server.notes;
if (Server.cluster) server.cluster = Server.cluster;
server
.on('listening', function () {
const addr = this.address();
logger.lognotice(`Listening on ${addr.address}:${addr.port}`);
listenerDone();
})
.on('close', () => {
logger.loginfo(`Listener ${host}:${port} stopped`);
})
.on('error', e => {
if (e.code !== 'EAFNOSUPPORT') return listenerDone(e);
// Fallback from IPv6 to IPv4 if not supported
// But only if we supplied the default of [::0]:25
if (/^::0/.test(host) && Server.default_host) {
server.listen(port, '0.0.0.0', 0);
return;
}
// Pass error to callback
listenerDone(e);
})
.listen(port, host, 0);
});
}
|
javascript
|
{
"resource": ""
}
|
q21791
|
map
|
train
|
function map(arr, fun, thisp) {
var i,
length = arr.length,
result = [];
for (i = 0; i < length; i += 1) {
if (arr.hasOwnProperty(i)) {
result[i] = fun.call(thisp, arr[i], i, arr);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q21792
|
unitConvert
|
train
|
function unitConvert(obj, k) {
if (objType(obj) === 'number') {
return obj * 72 / 96 / k;
} else {
var newObj = {};
for (var key in obj) {
newObj[key] = obj[key] * 72 / 96 / k;
}
return newObj;
}
}
|
javascript
|
{
"resource": ""
}
|
q21793
|
html2pdf
|
train
|
function html2pdf(src, opt) {
// Create a new worker with the given options.
var worker = new html2pdf.Worker(opt);
if (src) {
// If src is specified, perform the traditional 'simple' operation.
return worker.from(src).save();
} else {
// Otherwise, return the worker for new Promise-based operation.
return worker;
}
}
|
javascript
|
{
"resource": ""
}
|
q21794
|
mergeBranch
|
train
|
function mergeBranch(branch) {
var mergeCmd = 'git merge --no-ff --no-edit ' + branch;
console.log('Merging release into master.')
return exec('git checkout master && ' + mergeCmd).then(function() {
console.log('Merging release into develop.')
return exec('git checkout develop && ' + mergeCmd);
});
}
|
javascript
|
{
"resource": ""
}
|
q21795
|
getRealHueRange
|
train
|
function getRealHueRange(colorHue)
{ if (!isNaN(colorHue)) {
var number = parseInt(colorHue);
if (number < 360 && number > 0) {
return getColorInfo(colorHue).hueRange
}
}
else if (typeof colorHue === 'string') {
if (colorDictionary[colorHue]) {
var color = colorDictionary[colorHue];
if (color.hueRange) {
return color.hueRange
}
} else if (colorHue.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)) {
var hue = HexToHSB(colorHue)[0]
return getColorInfo(hue).hueRange
}
}
return [0,360]
}
|
javascript
|
{
"resource": ""
}
|
q21796
|
_jQueryPlugin
|
train
|
function _jQueryPlugin(config){
return this.each(function(){
var $this = plugin(this),
data = plugin(this).data(DATA_NAMESPACE);
if( ! data ){
data = new StickySidebar(this, typeof config == 'object' && config);
$this.data(DATA_NAMESPACE, data);
}
if( 'string' === typeof config){
if (data[config] === undefined && ['destroy', 'updateSticky'].indexOf(config) === -1)
throw new Error('No method named "'+ config +'"');
data[config]();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q21797
|
projectEnvironmentMapGPU
|
train
|
function projectEnvironmentMapGPU(renderer, envMap) {
var shTexture = new Texture2D({
width: 9,
height: 1,
type: Texture.FLOAT
});
var pass = new Pass({
fragment: projectEnvMapShaderCode
});
pass.material.define('fragment', 'TEXTURE_SIZE', envMap.width);
pass.setUniform('environmentMap', envMap);
var framebuffer = new FrameBuffer();
framebuffer.attach(shTexture);
pass.render(renderer, framebuffer);
framebuffer.bind(renderer);
// TODO Only chrome and firefox support Float32Array
var pixels = new vendor.Float32Array(9 * 4);
renderer.gl.readPixels(0, 0, 9, 1, Texture.RGBA, Texture.FLOAT, pixels);
var coeff = new vendor.Float32Array(9 * 3);
for (var i = 0; i < 9; i++) {
coeff[i * 3] = pixels[i * 4];
coeff[i * 3 + 1] = pixels[i * 4 + 1];
coeff[i * 3 + 2] = pixels[i * 4 + 2];
}
framebuffer.unbind(renderer);
framebuffer.dispose(renderer);
pass.dispose(renderer);
return coeff;
}
|
javascript
|
{
"resource": ""
}
|
q21798
|
projectEnvironmentMapCPU
|
train
|
function projectEnvironmentMapCPU(renderer, cubePixels, width, height) {
var coeff = new vendor.Float32Array(9 * 3);
var normal = vec3.create();
var texel = vec3.create();
var fetchNormal = vec3.create();
for (var m = 0; m < 9; m++) {
var result = vec3.create();
for (var k = 0; k < targets.length; k++) {
var pixels = cubePixels[targets[k]];
var sideResult = vec3.create();
var divider = 0;
var i = 0;
var transform = normalTransform[targets[k]];
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
normal[0] = x / (width - 1.0) * 2.0 - 1.0;
// TODO Flip y?
normal[1] = y / (height - 1.0) * 2.0 - 1.0;
normal[2] = -1.0;
vec3.normalize(normal, normal);
fetchNormal[0] = normal[transform[0]] * transform[3];
fetchNormal[1] = normal[transform[1]] * transform[4];
fetchNormal[2] = normal[transform[2]] * transform[5];
texel[0] = pixels[i++] / 255;
texel[1] = pixels[i++] / 255;
texel[2] = pixels[i++] / 255;
// RGBM Decode
var scale = pixels[i++] / 255 * 8.12;
texel[0] *= scale;
texel[1] *= scale;
texel[2] *= scale;
vec3.scaleAndAdd(sideResult, sideResult, texel, harmonics(fetchNormal, m) * -normal[2]);
// -normal.z equals cos(theta) of Lambertian
divider += -normal[2];
}
}
vec3.scaleAndAdd(result, result, sideResult, 1 / divider);
}
coeff[m * 3] = result[0] / 6.0;
coeff[m * 3 + 1] = result[1] / 6.0;
coeff[m * 3 + 2] = result[2] / 6.0;
}
return coeff;
}
|
javascript
|
{
"resource": ""
}
|
q21799
|
train
|
function () {
var enabledAttributes = this.getEnabledAttributes();
for (var i = 0; i < enabledAttributes.length; i++) {
this.dirtyAttribute(enabledAttributes[i]);
}
this.dirtyIndices();
this._enabledAttributes = null;
this._cache.dirty('any');
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.