diff --git "a/data/literate-coffeescript/data.json" "b/data/literate-coffeescript/data.json" deleted file mode 100644--- "a/data/literate-coffeescript/data.json" +++ /dev/null @@ -1,100 +0,0 @@ -{"size":239,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"check if current login user is administrator\n\n module.exports = (req, res, next) ->\n if req.user.email in sails.config.admin\n return next()\n res.forbidden \"#{req.user.email} not in #{JSON.stringify sails.config.admin}\"\n","avg_line_length":34.1428571429,"max_line_length":83,"alphanum_fraction":0.6736401674} -{"size":1337,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"\n# Application Errors\n\nTo configure error middleware, the only object we need access to is `app`. This module\ncan be called with `require(\".\/lib\/error\")(app)` as long as `app` is an already\ninitialized ExpressJS application.\n\n module.exports = (app) ->\n\n## Catch All\n\nIf an error occurs, return an HTTP 500\n\n app.use (err, req, res, next) ->\n console.error(err.stack)\n res.status(500)\n res.render('error\/500')\n\n## Copying\n\nThis software is released under the ISC License.\n\nCopyright (c) 2013, Cameron King \n\nPermission to use, copy, modify, and\/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n\n\n","avg_line_length":34.2820512821,"max_line_length":87,"alphanum_fraction":0.7486910995} -{"size":929,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":" Offline = {}\n\n\nTrue if we're running inside of a\n[web worker](http:\/\/www.w3.org\/TR\/workers\/).\n\n Offline.isWebWorker =\n Meteor.isClient and\n not window? and not document? and importScripts?\n\n\nOn the client, offline data is supported if\n\n1. the browser supports Web SQL Database (`openDatabase`); and\n\n2. we have a way to communicate between windows: either the browser\n supports shared web workers (and the developer hasn't disabled\n using them with Meteor.settings), or the browser supports\n browser-msg.\n\n if Offline.isWebWorker\n\n Offline.persistent = true\n\n\n else if Meteor.isClient\n\n Offline.persistent =\n (not Meteor.settings?.public?.offlineData?.disable) and\n openDatabase? and\n ((not Meteor.settings?.public?.offlineData?.disableWorker and\n SharedWorker?) or\n BrowserMsg?.supported)\n\n else if Meteor.isServer\n\n Offline.persistent = true\n","avg_line_length":24.4473684211,"max_line_length":69,"alphanum_fraction":0.6932185145} -{"size":7611,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Blot\n====\n\n#### A short animation, which calculates itself based on time and velocity\n\n class Blot\n C: 'Blot'\n toString: -> \"[object #{@C}]\"\n\n constructor: (config={}) ->\n\n\n\n\nProperties\n----------\n\n\n#### `xx `\nXx. \n\n @xx = null\n\n\n\n\nStatic Methods\n--------------\n\n#### `square()`\n- `time ` From 0 to 1\n- `velocity ` From 0 to 1\n- `ctx2d ` The canvas context to draw on\n- `size ` Pixel width and height of the canvas\n\nXx. \n\n Blot.square = (time, velocity, ctx2d, size) ->\n scale = size * velocity * (1-time)\n topleft = (size - scale) \/ 4\n ctx2d.fillRect topleft, topleft, scale, scale\n\n\n Blot.circle = (time, velocity, ctx2d, size) ->\n radius = Math.max size * velocity * (1-time), 0\n center = size \/ 2\n ctx2d.beginPath()\n ctx2d.arc center, center, radius \/ 2, 0, 2*Math.PI\n ctx2d.fill()\n\n\n Blot.squtrisqu = (time, velocity, ctx2d, size) ->\n velocity *= 0.6 # looks better smaller\n if 0.5 < time then time = 1 - time # at the end, simulate the start\n scale = size * velocity * (1-time) # in pixels, fills the canvas at t=0\n halfScale = scale \/ 2 # \n center = size \/ 2 # \n ctx2d.beginPath()\n ctx2d.moveTo center - (halfScale*(1-time)), center - halfScale # top left\n ctx2d.lineTo center + (halfScale*(1-time)), center - halfScale # top right\n ctx2d.lineTo center + (scale*time), center + scale # bottom right\n ctx2d.lineTo center - (scale*time), center + scale # bottom left\n ctx2d.fill()\n\n\n Blot.triangle = (time, velocity, ctx2d, size) ->\n scale = size * velocity * (1-time)\n halfScale = scale \/ 2\n center = size \/ 2\n ctx2d.beginPath()\n ctx2d.moveTo center, center - halfScale # top center point\n ctx2d.lineTo center + halfScale, center + scale # bottom right\n ctx2d.lineTo center - halfScale, center + scale # bottom left\n ctx2d.fill()\n\n\n Blot.dots = (time, velocity, ctx2d, size) ->\n i = 5\n while --i\n ctx2d.setTransform(\n 1 \/ i * velocity, # scaling in the X-direction\n 0, # skewing\n 0, # skewing\n .5 \/ i, # scaling in the Y-direction\n ( (size * i) \/ 4 - (size \/ 4) ) \/ 2, # moving in the X-direction\n size \/ 2 - (size \/ 4 * velocity) # moving in the Y-direction\n )\n Blot.circle(time, velocity, ctx2d, size)\n ctx2d.setTransform 1, 0, 0, 1, 0, 0\n\n\n\n\n Blot.galaxy = (time, velocity, ctx2d, size) ->\n time = 1 - time # reverse direction\n i = 5\n while i--\n ctx2d.setTransform(\n .5 \/ time, # scaling in the X-direction\n 0, # skewing\n 0, # skewing\n .5 \/ time \/ i, # scaling in the Y-direction\n size \/ i \/ 4, # moving in the X-direction\n size \/ 4 # moving in the Y-direction\n )\n Blot.circle(time, velocity, ctx2d, size)\n ctx2d.setTransform 1, 0, 0, 1, 0, 0\n\n\n\n\n Blot.oddtriangle = (time, velocity, ctx2d, size) ->\n scale = size * velocity * (1-time)\n halfScale = scale \/ 2\n center = size \/ 2\n ctx2d.beginPath()\n ctx2d.moveTo center, center - halfScale # top center point\n ctx2d.lineTo center + halfScale, scale # bottom right\n ctx2d.lineTo center - halfScale, scale # bottom left\n ctx2d.fill()\n\n\n\n\n Blot.barupdown = (time, velocity, ctx2d, size) ->\n if 0.5 > time then time = 1 - time # at the start, simulate the end\n scale = size * velocity * (1-time) # in pixels, fills the canvas at t=0\n topleft = (size - scale) \/ 2 # in pixels, from 0 at t=0\n width = Math.max scale, size \/ 3 # horizontal bar\n ctx2d.fillRect topleft \/ 2, topleft, width, scale\n if 0.9 > time\n ctx2d.fillRect topleft \/ 2, topleft * 0.8, width, size \/ 100\n ctx2d.fillRect topleft \/ 2, topleft * 1.2, width, size \/ 100\n if 0.7 > time\n ctx2d.fillRect topleft \/ 2, topleft * 0.6, width, size \/ 100\n ctx2d.fillRect topleft \/ 2, topleft * 1.4, width, size \/ 100\n\n\n\n Blot.circleupdown = (time, velocity, ctx2d, size) ->\n if 0.5 > time then time = 1 - time # at the start, simulate the end\n radius = Math.max size * velocity * (1-time), 0\n center = size \/ 2\n ctx2d.beginPath()\n ctx2d.arc center, center, radius * 0.8, 0, 2*Math.PI * time * velocity\n ctx2d.fill()\n if 0.9 > time\n ctx2d.arc center, center * 0.4 * (time + 1), radius * 0.6, 0, Math.PI * time * velocity\n ctx2d.arc center, center * 0.8 * (time + 1), radius * 0.6, 0, Math.PI * time * velocity\n ctx2d.fill()\n if 0.7 > time\n ctx2d.arc center * 0.2 * (time + 1), center, radius * 0.4, 0, Math.PI * time * velocity\n ctx2d.arc center * 1.0 * (time + 1), center, radius * 0.4, 0, Math.PI * time * velocity\n ctx2d.fill()\n\n\n\n\n Blot.linecrowd = (time, velocity, ctx2d, size) ->\n if 0.5 > time then time = 1 - time # at the start, simulate the end\n scale = size * velocity * (1-time) # in pixels, fills the canvas at t=0\n topleft = (size - scale) \/ 2 # in pixels, from 0 at t=0\n topleft = topleft * ( (Math.random() + 7) \/ 8 )\n width = Math.max scale, size \/ 2 # horizontal bar\n ctx2d.rotate 0.03\n if 0.6 > time\n ctx2d.fillRect topleft \/ 2, topleft * 0.8, width, size \/ 100\n ctx2d.fillRect topleft \/ 2, topleft * 1.2, width, size \/ 100\n if 0.7 > time\n ctx2d.fillRect topleft \/ 2, topleft * 0.6, width, size \/ 100\n ctx2d.fillRect topleft \/ 2, topleft * 1.4, width, size \/ 100\n if 0.8 > time\n ctx2d.fillRect topleft \/ 2, topleft * 0.4, width, size \/ 100\n ctx2d.fillRect topleft \/ 2, topleft * 1.6, width, size \/ 100\n if 0.9 > time\n ctx2d.fillRect topleft \/ 2, topleft * 0.2, width, size \/ 100\n ctx2d.fillRect topleft \/ 2, topleft * 1.8, width, size \/ 100\n ctx2d.setTransform 1, 0, 0, 1, 0, 0\n\n\n\n\n Blot.radiation = (time, velocity, ctx2d, size) ->\n\n rTime = 1-time # reciprocal time\n\nDraw the central dot. \n\n radius = size * velocity * time * 0.1\n center = size \/ 2\n ctx2d.beginPath()\n ctx2d.arc center, center, radius * 0.5, 0, 2*Math.PI\n ctx2d.fill()\n\nDraw lines and more dots. \n\n if 0.1 < time\n ctx2d.fillRect center * 0.95 * velocity, size * 0.4 * rTime, size * 0.05 * velocity, center * 0.8 * rTime\n\n if 0.2 < time\n ctx2d.rotate 0.1\n ctx2d.fillRect center * 0.96 * velocity, size * 0.4 * rTime, size * 0.04 * velocity, center * 0.8 * rTime\n ctx2d.beginPath()\n ctx2d.arc center, center, radius * 0.35, 0, 2*Math.PI\n ctx2d.fill()\n\n if 0.5 < time\n ctx2d.rotate 0.2\n ctx2d.fillRect center * 0.97 * velocity, size * 0.4 * rTime, size * 0.03 * velocity, center * 0.8 * rTime\n ctx2d.beginPath()\n ctx2d.arc center, center, radius * 0.2, 0, 2*Math.PI\n ctx2d.fill()\n\n if 0.7 < time\n ctx2d.rotate 0.4\n ctx2d.fillRect center * 0.98 * velocity, size * 0.4 * rTime, size * 0.02 * velocity, center * 0.8 * rTime\n ctx2d.beginPath()\n ctx2d.arc center, center, radius * 0.1, 0, 2*Math.PI\n ctx2d.fill()\n \n\n ctx2d.setTransform 1, 0, 0, 1, 0, 0\n\n #scale = size * velocity * (1-time)\n #topleft = (size - scale) \/ 4\n #ctx2d.fillRect topleft, topleft, scale, scale\n\n\n\n\n","avg_line_length":32.9480519481,"max_line_length":113,"alphanum_fraction":0.5547234266} -{"size":1807,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# Why not extend Object?\n\nThis approach is fun but dangerous (much like ...). Keeping our changes\ncontained makes use by others more flexible and not \"all or nothing.\"\n\nIf we ever finish the basic functionality we might add an option to \"monkey\npatch\" the core Node and JavaScript classes.\n\n# Model\n\nA Model is a class with extra features.\n\n Model = (name, info) ->\n { prototype = {}\n features = -> false\n } = info\n\n model = Object.assign Object.create(Model.prototype),\n constructor: this\n {name, prototype, features}\n\n Model.registered[name] = model\n\n Object.assign Model,\n\nThese are methods and properties of Model itself.\n\n registered: {}\n\nThese are the methods and properties for instances of Model, not the instance\nmethods for instances of a given Model. Model() creates new models. (model =\nModel())() spawns an instance of model.\n\nModel::prototype is a function so that it can be used to create instances of\nmodels.\n\n prototype:\n (info) ->\n instance = Object.create @prototype\n instance.constructor = this\n\n for iface in @interfaces and iface.init?\n ret = iface.init.apply instance, info\n\n if 'object' is typeof ret\n instance = ret\n\n addFeature: (feature) ->\n @chkMethod fn for fName in feature.does\n @addMethod fn for fName in feature.does\n\n chkMethod: (fn) ->\n if @protected[fn.name]\n throw new Error \"Cannot add method #{name}\"\n\n addMethod: (fn) ->\n if fn.protected\n @protected[fn.name] = fn\n\n this[fn.name] = @constructor.features\n\n Object.assign Model.prototype,\n\nThese are the default\/minimum methods and properties on instances of instances\nof Model.\n\n prototype: {}\n\n","avg_line_length":26.1884057971,"max_line_length":78,"alphanum_fraction":0.6436081904} -{"size":23081,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":33.0,"content":" vespaControllers = angular.module('vespaControllers')\n\n vespaControllers.controller 'diffCtrl', ($scope, VespaLogger, WSUtils,\n IDEBackend, $timeout, $modal, PositionManager, RefPolicy, $q, SockJSService) ->\n\n comparisonPolicy = null\n comparisonRules = []\n comparisonNodes = []\n comparisonLinks = []\n comparisonNodeMap = {}\n comparisonLinkMap = {}\n comparisonLinkSourceMap = {}\n comparisonLinkTargetMap = {}\n comparison =\n original:\n nodes: []\n links: []\n $scope.input = \n refpolicy: comparisonPolicy\n\n # The 'outstanding' attribute is truthy when a policy is being loaded\n $scope.status = SockJSService.status\n\n $scope.controls =\n showModulesSelect: false\n tab: 'nodesTab'\n linksVisible: false\n links:\n primary: true\n both: true\n comparison: true\n\n $scope.$watch 'controls.links', ((value) -> if value then redraw()), true\n $scope.$watch 'controls.linksVisible', ((value) -> if value == false or value == true then redraw())\n\n comparisonPolicyId = () ->\n if comparisonPolicy then comparisonPolicy.id else \"\"\n\n primaryPolicyId = () ->\n if IDEBackend.current_policy then IDEBackend.current_policy.id else \"\"\n\nGet the raw JSON\n\n fetch_raw = ->\n\n deferred = $q.defer()\n\n WSUtils.fetch_raw_graph(comparisonPolicy._id).then (json) =>\n comparisonRules = []\n comparison.original.nodes = json.parameterized.raw.nodes\n comparison.original.links = json.parameterized.raw.links\n comparisonNodes = json.parameterized.raw.nodes\n comparisonLinks = json.parameterized.raw.links\n\n deferred.resolve()\n\n return deferred.promise\n\nFetch the policy info (refpolicy) needed to get the raw JSON\n\n load_refpolicy = (id)->\n if comparisonPolicy? and comparisonPolicy.id == id\n return\n\n deferred = @_deferred_load || $q.defer()\n\n req = \n domain: 'refpolicy'\n request: 'get'\n payload: id\n\n SockJSService.send req, (data)=>\n if data.error?\n comparisonPolicy = null\n deferred.reject(comparisonPolicy)\n else\n comparisonPolicy = data.payload\n comparisonPolicy._id = comparisonPolicy._id.$oid\n\n deferred.resolve(comparisonPolicy)\n\n return deferred.promise\n \nEnumerate the differences between the two policies\n\n find_differences = () =>\n graph.links.length = 0\n\n primaryNodes = $scope.primaryNodes\n primaryLinks = $scope.primaryLinks\n primaryNodeMap = $scope.nodeMap\n primaryLinkMap = $scope.linkMap\n\n # Reset the \"selected\" flag when changing policies\n primaryNodes.forEach (n) -> n.selected = true\n comparisonNodes.forEach (n) -> n.selected = true\n\n # Reconcile the two lists of links\n # Loop over the primary links: if in comparison links\n # - change \"policy\" to \"both\"\n # - remove from comparisonLinkMap\n primaryLinks.forEach (link) ->\n comparisonLink = comparisonLinkMap[\"#{link.source.type}-#{link.source.name}-#{link.target.type}-#{link.target.name}\"]\n if comparisonLink\n link.policy = \"both\"\n delete comparisonLinkMap[\"#{link.source.type}-#{link.source.name}-#{link.target.type}-#{link.target.name}\"]\n\n comparisonLinks = d3.values(comparisonLinkMap)\n graph.links = comparisonLinks.concat(primaryLinks)\n\n # Reconcile the two lists of nodes\n # Loop over the primary nodes: if in comparison nodes\n # - change \"policy\" to \"both\"\n # - set it to unselected\n # - copy over its links to the primary node\n # - remove from comparisonNodeMap\n primaryNodes.forEach (node) ->\n comparisonNode = comparisonNodeMap[\"#{node.type}-#{node.name}\"]\n if comparisonNode\n node.policy = \"both\"\n node.selected = false\n # Filter out duplicate links we already deleted\n node.links = node.links.concat(comparisonNode.links.filter((l) ->\n return comparisonLinkMap[\"#{l.source.type}-#{l.source.name}-#{l.target.type}-#{l.target.name}\"]))\n delete comparisonNodeMap[\"#{node.type}-#{node.name}\"]\n\n # Rewire the links to use the \"both\" node instead of comparisonNode\n if comparisonLinkSourceMap[\"#{comparisonNode.type}-#{comparisonNode.name}\"]\n comparisonLinkSourceMap[\"#{comparisonNode.type}-#{comparisonNode.name}\"].forEach (l) ->\n l.source = node\n if comparisonLinkTargetMap[\"#{comparisonNode.type}-#{comparisonNode.name}\"]\n comparisonLinkTargetMap[\"#{comparisonNode.type}-#{comparisonNode.name}\"].forEach (l) ->\n l.target = node\n\n comparisonNodes = d3.values comparisonNodeMap\n\n # Remove any duplicate links we may have generated by rewiring the links\n # TODO: Probably not any duplicates. Verify whether there can be, and remove code if not.\n graph.links = _.uniqBy(graph.links, (l) ->\n return \"#{l.source.type}-#{l.source.name}-#{l.target.type}-#{l.target.name}\")\n\n graph.allNodes = primaryNodes.concat comparisonNodes\n\n graph.subjNodes = []\n graph.objNodes = []\n graph.classNodes = []\n graph.permNodes = []\n\n graph.allNodes.forEach (n) ->\n if n.type == \"subject\"\n graph.subjNodes.push n\n else if n.type == \"object\"\n graph.objNodes.push n\n else if n.type == \"class\"\n graph.classNodes.push n\n else #perm\n graph.permNodes.push n\n \n $scope.selectionChange = () ->\n redraw()\n\n $scope.load = ->\n load_refpolicy($scope.input.refpolicy.id).then(fetch_raw).then(update)\n\n $scope.list_refpolicies = \n query: (query)->\n promise = RefPolicy.list()\n promise.then(\n (policy_list)->\n dropdown = \n results: for d in policy_list\n id: d._id.$oid\n text: d.id\n data: d\n\n query.callback(dropdown)\n )\n\n width = 350\n height = 500\n padding = 50\n radius = 5\n graph =\n links: []\n subjNodes: []\n objNodes: []\n classNodes: []\n permNodes: []\n allNodes: []\n $scope.graph = graph\n color = d3.scale.category10()\n svg = d3.select(\"svg.diffview\").select(\"g.viewer\")\n subjSvg = svg.select(\"g.subjects\").attr(\"transform\", \"translate(0,0)\")\n permSvg = svg.select(\"g.permissions\").attr(\"transform\", \"translate(#{width+padding},0)\")\n objSvg = svg.select(\"g.objects\").attr(\"transform\", \"translate(#{2*(width+padding)},-#{height\/2})\")\n classSvg = svg.select(\"g.classes\").attr(\"transform\", \"translate(#{3*(width+padding)},0)\")\n\n subjSvg.append(\"rect\")\n .attr(\"width\", width + 16)\n .attr(\"height\", height + 16)\n .attr(\"x\", -8)\n .attr(\"y\", -8)\n .attr(\"style\", \"fill:rgba(200,200,200,0.15)\")\n objSvg.append(\"rect\")\n .attr(\"width\", width + 16)\n .attr(\"height\", height + 16)\n .attr(\"x\", -8)\n .attr(\"y\", -8)\n .attr(\"style\", \"fill:rgba(200,200,200,0.15)\")\n classSvg.append(\"rect\")\n .attr(\"width\", width + 16)\n .attr(\"height\", height + 16)\n .attr(\"x\", -8)\n .attr(\"y\", -8)\n .attr(\"style\", \"fill:rgba(200,200,200,0.15)\")\n permSvg.append(\"rect\")\n .attr(\"width\", width + 16)\n .attr(\"height\", height + 16)\n .attr(\"x\", -8)\n .attr(\"y\", -8)\n .attr(\"style\", \"fill:rgba(200,200,200,0.15)\")\n\n linkScale = d3.scale.linear()\n .range([1,2*radius])\n\n gridLayout = d3.layout.grid()\n .points()\n .size([width, height])\n\n textStyle =\n 'text-anchor': \"middle\"\n 'fill': \"#ccc\"\n 'font-size': \"56px\"\n svg.select(\"g.labels\").append(\"text\")\n .attr \"x\", width \/ 2\n .attr \"y\", height \/ 2\n .style textStyle\n .text \"subjects\"\n svg.select(\"g.labels\").append(\"text\")\n .attr \"x\", (width + padding) + width \/ 2\n .attr \"y\", height \/ 2\n .style textStyle\n .text \"permissions\"\n svg.select(\"g.labels\").append(\"text\")\n .attr \"x\", 2 * (width + padding) + width \/ 2\n .attr \"y\", 0\n .style textStyle\n .text \"objects\"\n svg.select(\"g.labels\").append(\"text\")\n .attr \"x\", 3 * (width + padding) + width \/ 2\n .attr \"y\", height \/ 2\n .style textStyle\n .text \"classes\"\n\n nodeExpand = (show, type, clickedNodeData) ->\n # If a node is associated with this on, and has the given type, set the selected attr\n l = -1\n while ++l < clickedNodeData.links.length\n if clickedNodeData.links[l].source.type == type\n clickedNodeData.links[l].source.selected = show\n if clickedNodeData.links[l].target.type == type\n clickedNodeData.links[l].target.selected = show\n\n $scope.update_view = (data) ->\n $scope.policy = IDEBackend.current_policy\n\n if $scope.policy?.json?.parameterized?.raw?\n $scope.primaryNodes = $scope.policy.json.parameterized.raw.nodes\n $scope.primaryLinks = $scope.policy.json.parameterized.raw.links\n\n update()\n\n update = () ->\n $scope.policyIds =\n primary: primaryPolicyId()\n both: if comparisonPolicyId() then \"both\" else undefined\n comparison: comparisonPolicyId() || undefined\n\n if not $scope.primaryNodes?.length or\n not $scope.primaryLinks?.length or\n not comparison?.original?.nodes?.length or\n not comparison?.original?.links?.length\n return\n\n nodeMapReducer = (map, currNode) ->\n map[\"#{currNode.type}-#{currNode.name}\"] = currNode\n return map\n\n linkMapReducer = (map, currLink) ->\n map[\"#{currLink.source.type}-#{currLink.source.name}-#{currLink.target.type}-#{currLink.target.name}\"] = currLink\n return map\n\n addPolicy = (policyId) ->\n return (item) ->\n item.policy = policyId\n\n nodeMapKey = (link) -> \"#{link.source.type}-#{link.source.name}-#{link.target.type}-#{link.target.name}\"\n\n # Need shallow copies of the nodes and links arrays\n $scope.primaryNodes = $scope.primaryNodes.slice()\n $scope.primaryLinks = $scope.primaryLinks.slice()\n $scope.primaryNodes.forEach addPolicy(primaryPolicyId())\n $scope.primaryLinks.forEach addPolicy(primaryPolicyId())\n comparisonNodes = comparison.original.nodes.slice()\n comparisonLinks = comparison.original.links.slice()\n comparisonNodes.forEach addPolicy(comparisonPolicyId())\n comparisonLinks.forEach addPolicy(comparisonPolicyId())\n\n\n # Convert the nodes and links arrays into maps\n $scope.nodeMap = $scope.primaryNodes.reduce nodeMapReducer, {}\n $scope.linkMap = $scope.primaryLinks.reduce linkMapReducer, {}\n comparisonNodeMap = comparisonNodes.reduce nodeMapReducer, {}\n comparisonLinkMap = comparisonLinks.reduce linkMapReducer, {}\n comparisonLinkSourceMap = comparisonLinks.reduce((map, currLink)->\n map[\"#{currLink.source.type}-#{currLink.source.name}\"] = map[\"#{currLink.source.type}-#{currLink.source.name}\"] or []\n map[\"#{currLink.source.type}-#{currLink.source.name}\"].push currLink\n return map\n , {})\n comparisonLinkTargetMap = comparisonLinks.reduce((map, currLink)->\n map[\"#{currLink.target.type}-#{currLink.target.name}\"] = map[\"#{currLink.target.type}-#{currLink.target.name}\"] or []\n map[\"#{currLink.target.type}-#{currLink.target.name}\"].push currLink\n return map\n , {})\n\n find_differences()\n\n $scope.clickedNode = null\n $scope.clickedNodeRules = []\n\n if $scope.policyIds.primary and $scope.policyIds.comparison\n redraw()\n\n redraw = () ->\n [\n {nodes: graph.subjNodes, svg: subjSvg},\n {nodes: graph.objNodes, svg: objSvg},\n {nodes: graph.permNodes, svg: permSvg},\n {nodes: graph.classNodes, svg: classSvg}\n ].forEach (tuple) ->\n getConnected = (d) ->\n linksToShow = d.links\n\n linksToShow = linksToShow.filter (l) -> return l.source.selected && l.target.selected\n\n uniqNodes = linksToShow.reduce((prev, l) ->\n prev.push l.source\n prev.push l.target\n return prev\n , [])\n\n # No links to show, so make sure we highlight the node the user moused over\n if uniqNodes.length == 0\n uniqNodes.push d\n\n uniqNodes = _.uniq uniqNodes\n\n return [uniqNodes, linksToShow]\n\n nodeMouseover = (d) ->\n [uniqNodes, linksToShow] = getConnected(d)\n\n d3.selectAll uniqNodes.map((n) -> return \"g.node.\" + CSS.escape(\"t-#{n.type}-#{n.name}\")).join(\",\")\n .classed \"highlight\", true\n .each () -> @.parentNode.appendChild(@)\n\n # No links to show, so return\n if linksToShow.length == 0\n return\n\n d3.selectAll linksToShow.map((link) -> \".\" + CSS.escape(\"l-#{link.source.type}-#{link.source.name}-#{link.target.type}-#{link.target.name}\")).join \",\"\n .classed \"highlight\", true\n .each () -> @.parentNode.appendChild(@)\n\n nodeMouseout = (d) ->\n link.classed \"highlight\", false\n d3.selectAll \"g.node.highlight\"\n .classed \"highlight\", false\n\n nodeClick = (clickedNode) =>\n [uniqNodes, linksToShow] = getConnected(clickedNode)\n clicked = !clickedNode.clicked\n\n if clicked\n $scope.clickedNode = clickedNode\n $scope.clickedNodeRules = []\n\n reqParams = {}\n\n deferred = $q.defer()\n\n reqParams[clickedNode.type] = clickedNode.name\n\n req = \n domain: 'raw'\n request: 'fetch_rules'\n payload:\n policy: [IDEBackend.current_policy._id, comparisonPolicy._id]\n params: reqParams\n\n SockJSService.send req, (result)=>\n if result.error?\n $scope.clickedNodeRules = []\n else\n rules = JSON.parse(result.payload)\n $scope.clickedNodeRules = rules.sort (a,b) ->\n if a.policy != b.policy then return a.policy - b.policy\n return a.rule - b.rule\n if !$scope.$$phase then $scope.$apply()\n\n else\n $scope.clickedNode = null\n $scope.clickedNodeRules = []\n if !$scope.$$phase then $scope.$apply()\n\n changedNodes = graph.allNodes.filter (n) -> return n.clicked\n changedLinks = graph.links.filter (l) -> return l.source.clicked && l.target.clicked\n changedLinks = changedLinks.concat linksToShow\n\n # Set clicked = false on all nodes\n graph.subjNodes.forEach (d) -> d.clicked = false\n graph.objNodes.forEach (d) -> d.clicked = false\n graph.classNodes.forEach (d) -> d.clicked = false\n graph.permNodes.forEach (d) -> d.clicked = false\n\n # Toggle clicked\n uniqNodes.forEach (d) -> d.clicked = clicked\n\n changedNodes = changedNodes.concat uniqNodes\n\n # For all nodes with clicked == true, add the \"clicked\" class\n d3.selectAll _.uniq(changedNodes.map((n) -> return \"g.node.\" + CSS.escape(\"t-#{n.type}-#{n.name}\"))).join(\",\")\n .classed \"clicked\", (d) -> d.clicked\n .each () -> @.parentNode.appendChild(@)\n\n # No links to show, so return\n if changedLinks.length == 0\n return\n\n d3.selectAll changedLinks.map((link) -> \".\" + CSS.escape(\"l-#{link.source.type}-#{link.source.name}-#{link.target.type}-#{link.target.name}\")).join \",\"\n .classed \"clicked\", (d) -> d.source.clicked && d.target.clicked\n\n # Sort first by policy, then by name\n tuple.nodes.sort (a,b) ->\n if (a.policy == primaryPolicyId() && a.policy != b.policy) || (a.policy == \"both\" && b.policy == comparisonPolicyId())\n return -1\n else if a.policy == b.policy\n return if a.name == b.name then 0 else if a.name < b.name then return -1 else return 1\n else\n return 1\n\n node = tuple.svg.selectAll \".node\"\n \n # Clear the old nodes and redraw everything\n node.remove()\n\n node = tuple.svg.selectAll \".node\"\n .data gridLayout(tuple.nodes.filter (d) -> return d.selected)\n .attr \"class\", (d) -> \"node t-#{d.type}-#{d.name}\"\n .classed \"clicked\", (d) -> d.clicked\n\n nodeEnter = node.enter().append \"g\"\n .attr \"class\", (d) -> \"node t-#{d.type}-#{d.name}\"\n .attr \"transform\", (d) -> return \"translate(#{d.x},#{d.y})\"\n .classed \"clicked\", (d) -> d.clicked\n\n nodeEnter.append \"text\"\n .attr \"class\", (d) -> \"node-label t-#{d.type}-#{d.name}\"\n .attr \"x\", 0\n .attr \"y\", \"-5px\"\n .text (d) -> d.name\n\n nodeEnter.append \"circle\"\n .attr \"r\", radius\n .attr \"cx\", 0\n .attr \"cy\", 0\n .attr \"class\", (d) ->\n if d.policy == primaryPolicyId()\n return \"diff-left\"\n else if d.policy == comparisonPolicyId()\n return \"diff-right\"\n .on \"mouseover\", nodeMouseover\n .on \"mouseout\", nodeMouseout\n .on \"click\", nodeClick\n\n node.exit().remove()\n\n genContextItems = (data) ->\n menuItems = {}\n if data.type != 'subject'\n menuItems['show-subject'] =\n label: 'Show connected subjects'\n callback: ->\n nodeExpand(true, 'subject', data)\n redraw()\n menuItems['hide-subject'] =\n label: 'Hide connected subjects'\n callback: ->\n nodeExpand(false, 'subject', data)\n redraw()\n if data.type != 'object'\n menuItems['show-object'] =\n label: 'Show connected objects'\n callback: ->\n nodeExpand(true, 'object', data)\n redraw()\n menuItems['hide-object'] =\n label: 'Hide connected objects'\n callback: ->\n nodeExpand(false, 'object', data)\n redraw()\n if data.type != 'perm'\n menuItems['show-permission'] =\n label: 'Show connected permissions'\n callback: ->\n nodeExpand(true, 'perm', data)\n redraw()\n menuItems['hide-permission'] =\n label: 'Hide connected permissions'\n callback: ->\n nodeExpand(false, 'perm', data)\n redraw()\n if data.type != 'class'\n menuItems['show-class'] =\n label: 'Show connected classes'\n callback: ->\n nodeExpand(true, 'class', data)\n redraw()\n menuItems['hide-class'] =\n label: 'Hide connected classes'\n callback: ->\n nodeExpand(false, 'class', data)\n redraw()\n return menuItems\n\n d3.selectAll('.node circle').each (d) ->\n context_items = genContextItems(d)\n $(this).contextmenu\n target: '#diff-context-menu'\n items: context_items\n\n link = svg.select(\"g.links\").selectAll \".link\"\n\n # Clear the old links and redraw everything\n link.remove()\n\n link = svg.select(\"g.links\").selectAll \".link\"\n .data graph.links.filter((d) ->\n policyFilter = true\n for type,id of $scope.policyIds\n if id == d.policy then policyFilter = $scope.controls.links[type]\n return d.source.selected && d.target.selected && policyFilter\n ), (d,i) -> return \"#{d.source.type}-#{d.source.name}-#{d.target.type}-#{d.target.name}\"\n\n link.enter().append \"line\"\n .attr \"class\", (d) -> \"link l-#{d.source.type}-#{d.source.name}-#{d.target.type}-#{d.target.name}\"\n .style \"stroke-width\", (d) -> 1\n .attr \"x1\", (d) ->\n offset = 0\n if d.source.type == \"perm\"\n offset = width + padding\n else if d.source.type == \"object\"\n offset = 2 * (width + padding)\n return d.source.x + offset\n .attr \"y1\", (d) -> return d.source.y - if d.source.type == \"object\" then height\/2 else 0\n .attr \"x2\", (d) ->\n offset = width + padding\n if d.target.type == \"object\"\n offset = 2 * (width + padding)\n else if d.target.type == \"class\"\n offset = 3 * (width + padding)\n return d.target.x + offset\n .attr \"y2\", (d) -> return d.target.y - if d.target.type == \"object\" then height\/2 else 0\n .classed \"clicked\", (d) -> d.source.clicked && d.target.clicked\n .classed \"visible\", $scope.controls.linksVisible\n\n link.exit().remove()\n\nSet up the viewport scroll\n\n positionMgr = PositionManager(\"tl.viewport::#{IDEBackend.current_policy._id}\",\n {a: 0.7454701662063599, b: 0, c: 0, d: 0.7454701662063599, e: 200, f: 50}\n )\n\n svgPanZoom.init\n selector: '#surface svg.diffview'\n panEnabled: true\n zoomEnabled: true\n dragEnabled: false\n minZoom: 0.5\n maxZoom: 10\n onZoom: (scale, transform) ->\n positionMgr.update transform\n onPanComplete: (coords, transform) ->\n positionMgr.update transform\n\n $scope.$watch(\n () -> return (positionMgr.data)\n , \n (newv, oldv) ->\n if not newv? or _.keys(newv).length == 0\n return\n g = svgPanZoom.getSVGViewport($(\"#surface svg.diffview\")[0])\n svgPanZoom.set_transform(g, newv)\n )\n\n IDEBackend.add_hook \"json_changed\", $scope.update_view\n IDEBackend.add_hook \"policy_load\", IDEBackend.load_raw_graph\n \n $scope.$on \"$destroy\", ->\n IDEBackend.unhook \"json_changed\", $scope.update_view\n IDEBackend.unhook \"policy_load\", IDEBackend.load_raw_graph\n\n $scope.policy = IDEBackend.current_policy\n\n # Load the raw graph data if it is not loaded\n if $scope.policy?._id and not $scope.policy.json?.parameterized?.raw?\n IDEBackend.load_raw_graph()\n\n # If the graph data is already loaded, render the view\n if $scope.policy?.json?.parameterized?.raw?\n $scope.update_view()","avg_line_length":37.1077170418,"max_line_length":163,"alphanum_fraction":0.556171743} -{"size":539,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":10.0,"content":" Client = require('raven').Client\n\n module.exports = new Client process.env.SENTRY_DNS\n module.exports.parseRequest = (req, kwargs = {}) ->\n kwargs.http =\n method: req.method\n query: req.query\n headers: req.headers\n data: req.body\n url: req.originalUrl\n\n kwargs\n\n if process.env.NODE_ENV is 'production'\n module.exports.patchGlobal (id, err) ->\n console.error 'Uncaught Exception'\n console.error err.message\n console.error err.stack\n process.exit 1\n","avg_line_length":26.95,"max_line_length":55,"alphanum_fraction":0.6178107607} -{"size":2931,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"# \/api\/App Components\/Batman.View\/Batman.View Lifecycle\n\nWhen [`Batman.View`](\/docs\/api\/batman.view.html) is rendered, it goes through many steps. Lifecycle callbacks allow you to hook into those steps and control or respond to the rendering process.\n\n### Listening for Lifecycle Events\n\nTo set up handlers for a `View`'s lifecycle, You can either call [`on`](\/docs\/api\/batman.eventemitter.html#prototype_function_on) on the `View`'s prototype:\n\n```coffeescript\nclass MyApp.FadingView extends Batman.View\n @::on 'viewWillAppear', -> $(@get('node')).hide()\n\n @::on 'viewDidAppear', -> $(@get('node')).fadeIn('fast')\n\n @::on 'viewWillDisappear', -> $(@get('node')).fadeOut('fast')\n```\n\nor define functions with the same name as the events:\n\n```coffeescript\nclass MyApp.FadingView extends Batman.View\n viewWillAppear: -> $(@get('node')).hide()\n\n viewDidAppear: -> $(@get('node')).fadeIn('fast')\n\n viewWillDisappear: -> $(@get('node')).fadeOut('fast')\n```\n\n### Lifecycle Events and Subviews\n\nA `View` propagates its lifecycle events to its [`subviews`](\/docs\/api\/batman.view.html#prototype_property_subviews), so it's likely that a lifecycle event will be called more than once. `ready` is an exception -- it's a one-shot event.\n\n## viewWillAppear\n\nThe view is about to be attached to the DOM. It has a [`superview`](\/docs\/api\/batman.view.html#prototype_property_superview).\n\n## viewDidAppear\n\nThe view has just been attached to the DOM. Its [`node`](\/docs\/api\/batman.view.html#prototype_accessor_node) is on the page and can be selected with `document.querySelector`.\n\n## viewDidLoad\n\nThe view's [`node`](\/docs\/api\/batman.view.html#prototype_accessor_node) has been loaded from its [`html`](\/docs\/api\/batman.view.html#prototype_accessor_html)). It may not be in the DOM yet.\n\n## ready\n\nThe view's bindings have been initialized. The view may or may not be in the DOM. `ready` is a one-shot event.\n\n## viewWillDisappear\n\nThe view is about to be detached from the DOM. It still has a [`superview`](\/docs\/api\/batman.view.html#prototype_property_superview) and its [`node`](\/docs\/api\/batman.view.html#prototype_accessor_node) is still selectable.\n\n## viewDidDisappear\n\nThe view has been detached from the DOM. It still has a [`superview`](\/docs\/api\/batman.view.html#prototype_property_superview) but its [`node`](\/docs\/api\/batman.view.html#prototype_accessor_node) is not selectable.\n\n## destroy\n\n[`die`](\/docs\/api\/batman.view.html#prototype_function_die) was called on this view. It will be removed from its superview, removed from the DOM, and have all of its properties set to `null`.\n\n## viewDidMoveToSuperview\n\nThe view has been attached to its [`superview`](\/docs\/api\/batman.view.html#prototype_property_superview), but it is not yet in the DOM.\n\n## viewWillRemoveFromSuperview\n\nThe view is about removed from its [`superview`](\/docs\/api\/batman.view.html#prototype_property_superview), then it will be detached from the DOM.\n","avg_line_length":43.1029411765,"max_line_length":236,"alphanum_fraction":0.747185261} -{"size":634,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Item.Tone.Sine\n==============\n\n@todo describe\n\n\n#### A simple sine wave\n\n class Item.Tone.Sine extends Item.Tone\n C: 'Item.Tone.Sine'\n toString: -> '[object Item.Tone.Sine]'\n\n constructor: (config={}) ->\n M = \"\/ldc\/src\/Item\/Tone\/Sine.litcoffee\n Item.Tone.Sine()\\n \"\n\n super config\n\n\n\n\nProperties\n----------\n\n\n#### `x `\n@todo describe\n\n @x = null\n\n\n\n\nMethods\n-------\n\n\n#### `xx()`\n- `yy ` @todo describe\n- `` does not return anything\n\n@todo describe\n\n xx: (yy) ->\n M = \"\/ldc\/src\/Item\/Tone\/Sine.litcoffee\n Item.Tone.Sine::xx()\\n \"\n\n\n\n ;\n","avg_line_length":12.431372549,"max_line_length":46,"alphanum_fraction":0.5094637224} -{"size":15956,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":58.0,"content":"Leisure Cliient Adapter\n=======================\nCopyright (C) 2015, Bill Burdick, Roy Riggs, TEAM CTHULHU\n\nPeer-to-peer connection between Leisure instances. They send \"final\"\ndocument changes to each other, meaning that all document computations\nare complete and only the document changes need be replicated.\n\nLicensed with ZLIB license.\n=============================\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must not\nclaim that you wrote the original software. If you use this software\nin a product, an acknowledgment in the product documentation would be\nappreciated but is not required.\n\n2. Altered source versions must be plainly marked as such, and must not be\nmisrepresented as being the original software.\n\n3. This notice may not be removed or altered from any source distribution.\n\n 'use strict'\n define ['jquery', 'immutable', '.\/utilities', '.\/editor', '.\/editorSupport', 'sockjs', '.\/advice', '.\/common', 'bluebird', 'lib\/ot\/ot', '.\/replacements'], (jq, immutable, Utilities, Editor, Support, SockJS, Advice, Common, Bluebird, OT, Rep)->\n {\n Map\n Set\n } = window.Immutable = immutable\n {\n ajaxGet\n } = Utilities\n {\n DataStore\n preserveSelection\n blockText\n computeNewStructure\n } = Editor\n {\n OrgData\n getDocumentParams\n editorToolbar\n basicDataFilter\n replacementFor\n makeImageBlob\n } = Support\n {\n changeAdvice\n afterMethod\n beforeMethod\n callOriginal\n } = Advice\n {\n noTrim\n } = Common\n {\n Promise\n } = Bluebird\n {\n TextOperation\n Selection\n EditorClient\n } = OT\n {\n isRetain\n isInsert\n isDelete\n } = TextOperation\n {\n Replacements\n replacements\n } = Rep\n\n fileTypes =\n jpg: 'image\/jpeg'\n png: 'image\/png'\n gif: 'image\/gif'\n bmp: 'image\/bmp'\n xpm: 'image\/xpm'\n svg: 'image\/svg+xml'\n\n diag = (args...)-> console.log args...\n\nPeer is the top-level object for a peer-to-peer-capable Leisure instance.\n\n class Peer\n constructor: ->\n @data = new OrgData()\n @namd = randomUserName()\n @guardedChangeId = 0\n @guardPromises = {}\n setEditor: (@editor)->\n disconnect: ->\n @con?.close()\n @con = null\n connect: (@url, @connectedFunc)->\n console.log \"CONNECTED\"\n @con = new SockJS @url\n opened = false\n new Promise (resolve, reject)=>\n @con.onopen = =>\n opened = true\n @con.onerror = => @closed()\n resolve()\n @con.onerror = -> if !openend then reject()\n @con.onmessage = (msg)=> @handleMessage JSON.parse msg.data\n @con.onclose = => @closed()\n peer = this\n @editor.options.data.peer = this\n configureOpts @editor.options\n @editor.on 'selection', => @getSelection()\n opFor: ({start, end, text}, length)->\n op = new TextOperation()\n if start > 0 then op = op.retain start\n if end > start then op = op.delete end - start\n if text.length then op = op.insert text\n if length > end then op = op.retain length - end\n op\n opsFor: (repls, totalLength)->\n if repls instanceof Replacements\n @baseOpsFor totalLength, (f)->\n t = repls.replacements\n while !t.isEmpty()\n {offset, length, text} = t.peekFirst()\n t = t.removeFirst()\n f offset, length, text\n else if _.isArray repls then @baseOpsFor totalLength, (f)->\n last = 0\n for repl in repls by -1\n f repl.start - last, repl.end - repl.start, repl.text\n last = repl.end\n baseOpsFor: (totalLength, iterate)->\n op = new TextOperation()\n cursor = 0\n iterate (offset, length, text)->\n if offset > 0 then op = op.retain offset\n if length > 0 then op = op.delete length\n if text.length then op = op.insert text\n cursor += offset + length\n if totalLength > cursor then op = op.retain totalLength - cursor\n op\n inverseOpFor: ({start, end, text}, len)->\n @opFor (\n start: start\n end: start + text.length\n text: @data.getDocSubstring start, end), len\n type: 'Unknown Handler'\n close: ->\n console.log \"CLOSING: #{@type}\"\n @con.close()\n closed: ->\n changeAdvice @editor.options, false,\n changesFor: p2p: true\n doCollaboratively: p2p: true\n send: (type, msg)->\n msg.type = type\n #diag \"SEND #{JSON.stringify msg}\"\n @con.send JSON.stringify msg\n handleMessage: (msg)->\n #diag \"RECEIVE #{JSON.stringify msg}\"\n if !(msg.type of @handler)\n console.log \"Received bad message #{msg.type}\", msg\n @close()\n else @handler[msg.type].call this, msg\n finishConnected: ({@id, peers, revision})->\n @editorClient = new EditorClient revision, peers, this, this\n @newConnectionFunc _.size @editorClient.clients\n @connectedFunc?(this)\n @connectedFunc = null\n handler:\n log: (msg)-> console.log msg.msg\n connection: ({peerId, peerName})->\n @serverCallbacks.set_name peerId, peerName\n @newConnectionFunc _.size @editorClient.clients\n disconnection: ({peerId})->\n @serverCallbacks.client_left peerId\n @newConnectionFunc _.size @editorClient.clients\n error: (msg)->\n console.log \"Received error: #{msg.error}\", msg\n @close()\n ack: -> @serverCallbacks.ack()\n ackGuard: ({guardId, operation})->\n @guardPromises[guardId][0](operation)\n delete @guardPromises[guardId]\n rejectGuard: (ack)->\n @guardPromises[ack.guardId][1](ack)\n delete @guardPromises[ack.guardId]\n operation: ({peerId, operation, meta})->\n @fromServer = true\n @editor.options.data.allowObservation => @serverCallbacks.operation operation\n @fromServer = false\n @serverCallbacks.selection peerId, meta\n selection: ({peerId, selection})->\n @serverCallbacks.selection selection\n setName: ({peerId, name})->\n @serverCallbacks.set_name peerId, name\n @newConnectionFunc _.size @editorClient.clients\n createSession: (@host, connectedFunc, @newConnectionFunc)->\n peer = this\n @type = 'Master'\n @newConnectionFunc = @newConnectionFunc ? ->\n @handler =\n __proto__: Peer::handler\n connected: (msg)->\n @guid = msg.guid\n @connectUrl = new URL(\"join-#{@guid}\", @url)\n @editorClient = new EditorClient 0, {}, this, this\n @finishConnected msg\n slaveConnect: (msg)->\n @send 'slaveApproval', slaveId: msg.slaveId, approval: true\n slaveDisconnect: (msg)->\n requestFile: ({slaveId, filename, id})->\n @editor.options.data.getFile filename, ((content)=>\n @send 'fileContent', {slaveId, id, content: btoa(content)}), ((failure)->\n @send 'fileError', {slaveId, id, failure})\n customMessage: ({name, args, slaveId, msgId})->\n peer.editor.options._runCollaborativeCode name, slaveId, args\n .then (result)=> @send 'customResponse', {slaveId, msgId, result}\n .catch (err)=>\n console.error \"Error with custom message name: #{name}, slaveId: #{slaveId}, msgId: #{msgId}\\n#{err.stack}\"\n @send 'customError', {slaveId, msgId, err: err.stack}\n @connect \"http:\/\/#{@host}\/Leisure\/create\", =>\n @send 'initDoc', doc: @data.getText(), name: @name\n @docSnap = @data.getText()\n connectedFunc()\n @docSnap = @data.getText()\n connectToSession: (@url, connected, @newConnectionFunc)->\n @type = 'Slave'\n @newConnectionFunc = @newConnectionFunc ? ->\n @localResources = {}\n @imgCount = 0\n fileRequestCount = 0\n customMessageCount = 0\n pendingRequests = new Map()\n peer = this\n getFile = (filename, cont, fail)->\n p = new Promise (success, failure)->\n id = \"request-#{fileRequestCount++}\"\n pendingRequests = pendingRequests.set(id, [success, failure])\n peer.send 'requestFile', {id, filename}\n if cont || fail then p.then cont, fail\n else p\n changeAdvice @editor.options.data, true,\n getFile: p2p: (parent)-> getFile\n Leisure.localActivateScripts @editor.options\n changeAdvice @editor.options, true,\n imageError: p2p: (parent)->(img, e)->\n src = img.getAttribute 'src'\n if !src.match '^.*:.*'\n name = src.match(\/([^#?]*)([#?].*)?$\/)?[1]\n src = \"#{src}\"\n else name = src.match(\/^file:([^#?]*)([#?].*)?$\/)?[1]\n if name\n if !img.id then img.id = \"p2p-image-#{peer.imgCount++}\"\n img.src = ''\n peer.fetchImage img.id, src\n doCollaboratively: p2p: (parent)-> (name, args)-> peer.sendCustom name, args\n @fetchImage = (imgId, src)->\n if img = $(\"##{imgId}\")[0]\n if data = @localResources[src]\n if data instanceof Promise then data.then (data)=>\n @replaceImage img, src, data\n else preserveSelection (range)=> @replaceImage img, src, data\n else @localResources[src] = new Promise (resolve, reject)=>\n getFile src, ((file)=>\n data = @localResources[src] = makeImageBlob src, file\n preserveSelection (range)=> @replaceImage img, src, data\n resolve data), reject\n @replaceImage = (img, src, data)-> setTimeout (=>\n img.src = data\n #img.onload = =>\n ), 0\n @pendingCustomMessages = {}\n @handler =\n __proto__: Peer::handler\n connected: (msg)->\n @finishConnected msg\n @editor.options.load 'shared', msg.doc\n @docSnap = msg.doc\n fileContent: ({id, content})->\n [cont] = pendingRequests.get(id)\n pendingRequests = pendingRequests.remove(id)\n cont atob(content)\n fileError: ({id, failure})->\n [cont, fail] = pendingRequests.get(id)\n pendingRequests = pendingRequests.remove(id)\n fail failure\n customResponse: ({msgId, result})->\n [success] = @pendingCustomMessages[msgId]\n delete @pendingCustomMessages[msgId]\n success result\n customError: ({msgId, err})->\n [..., failure] = @pendingCustomMessages[msgId]\n delete @pendingCustomMessages[msgId]\n failure err\n @sendCustom = (name, args)->\n new Promise (succeed, fail)=>\n msgId = \"custom-#{customMessageCount++}\"\n @pendingCustomMessages[msgId] = [succeed, fail]\n @send 'customMessage', {name, args, msgId}\n @connect @url, =>\n @send 'intro', name: @name\n connected?()\n replsForTextOp: (textOp)->\n repls = []\n popLastEmpty = ->\n if (r = _.last repls) && r.start == r.end && r.text.length == 0\n repls.pop()\n cursor = 0\n for op in textOp.ops\n if isRetain op\n cursor += op\n popLastEmpty()\n repls.push start: cursor, end: cursor, text: ''\n else if isDelete op\n cursor -= op\n _.last(repls).end = cursor\n else _.last(repls).text += op\n popLastEmpty()\n #console.log \"INCOMING REPLACE: #{JSON.stringify repls}\"\n repls\n replaceText: (start, end, text)-> @data.replaceText {start, end, text, source: 'peer'}\n # OT API\n registerCallbacks: (cb)->\n if cb.client_left then @serverCallbacks = cb\n else @editorCallbacks = cb\n # EditorAdapter methods\n registerUndo: (@undoFunc)->\n registerRedo: (@redoFunc)->\n getValue: -> @data.getText()\n applyOperation: (op)->\n preserveSelection (sel)=>\n if sel.type != 'None'\n @data.addMark 'selStart', sel.start\n @data.addMark 'selEnd', sel.start + sel.length\n for repl in @replsForTextOp op by -1\n @replaceText repl.start, repl.end, repl.text\n if sel.type != 'None'\n sel.start = @data.getMarkLocation 'selStart'\n sel.length = @data.getMarkLocation('selEnd') - sel.start\n @data.removeMark 'selStart'\n @data.removeMark 'selEnd'\n getSelection: ->\n sel = @editor.getSelectedDocRange()\n newSel = if sel.type == 'Caret' then Selection.createCursor sel.start\n else if sel.type == 'Range'\n new Selection [new Selection.Range(sel.start, sel.start + sel.length)]\n else new Selection()\n newSel.scrollTop = sel.scrollTop\n newSel.scrollLeft = sel.scrollLeft\n newSel\n setSelection: (sel)->\n if sel.ranges.length\n @editor.selectDocRange\n start: sel.ranges[0].start\n length: sel.ranges[0].end - sel.ranges[0].start\n scrollTop: sel.scrollTop\n scrollLeft: sel.scrollLeft\n setOtherSelection: (sel, color, id)->\n #$(\".selection-#{id}\").remove()\n console.log \"OTHER SELECTION: #{JSON.stringify sel}\"\n # ServerAdapter methods\n sendSelection: (sel)-> @send 'selection', selection: sel\n sendOperation: (revision, operation, selection)-> @send 'operation', {revision, operation, selection}\n sendGuardedOperation: (revision, operation, guards)->\n #console.log \"GUARD SENT\"\n guardId = \"guard-#{@guardedChangeId++}\"\n @send 'guardedOperation', {revision, operation, guards, guardId, selection: @editorClient.selection}\n new Promise (success, failure)=> @guardPromises[guardId] = [success, failure]\n\n typeForFile = (name)->\n [ignore, ext] = name.match \/\\.([^#.]*)(#.*)?$\/\n fileTypes[ext]\n\n configureOpts = (opts)->\n data = opts.data\n if !data.peer then return\n peer = data.peer\n changeAdvice data, true,\n replaceText: p2p: (parent)-> (repl)->\n if repl.source != 'peer'\n oldLen = @getLength()\n {start, end, text} = repl\n newLen = oldLen + text.length - end + start\n peer.editorCallbacks.change peer.opFor(repl, oldLen), peer.inverseOpFor(repl, newLen)\n parent repl\n\n window.randomUserName = randomUserName = (done)->\n a = 'a'.charCodeAt(0)\n 'user' + (String.fromCharCode a + Math.floor(Math.random() * 26) for i in [0...10]).join\n\n Object.assign Leisure, {\n configurePeerOpts: configureOpts\n }\n\n {\n Peer\n }\n","avg_line_length":39.3975308642,"max_line_length":247,"alphanum_fraction":0.5476936576} -{"size":399,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"Index Model\n==========\n\n\tmodule.exports = {\n\n\t\tidentity: 'resource'\n\t\tconnection: 'mongo'\n\n\t\tattributes: {\n\n\t\t\ttype: {\n\t\t\t\ttype: 'string'\n\t\t\t\trequired: true\n\t\t\t}\n\n\t\t\tid: {\n\t\t\t\ttype: 'string'\n\t\t\t\trequired: true\n\t\t\t\tunique: true\n\t\t\t}\n\n\t\t\tdata: {\n\t\t\t\ttype: 'json'\n\t\t\t\trequired: true\n\t\t\t}\n\n\t\t\tpermissions: {\n\t\t\t\ttype: 'string'\n\t\t\t\tdefault: 'all'\n\t\t\t} \n\n\t\t\ttoJSON: () ->\n\t\t\t\treturn @toObject()\n\t\t}\n\t\t\t\n\t}","avg_line_length":11.0833333333,"max_line_length":22,"alphanum_fraction":0.4987468672} -{"size":11200,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# SHEET #\nSprite-sheet managing\n\n- - -\n\n## Introduction ##\n\n> *To come.*\n\n## Implementation ##\n\n \"use strict\";\n\n ###\n SHEET\n Sprite-sheet managing\n ---------------------\n ###\n\nThe `Sheet` constructor generates sprite-sheets and manages their rendering on a `CanvasRenderingContext2D`.\nIt is packaged with `Sprite`, which describes a single sprite on the sheet.\n\n### General functions: ###\n\nThe function `drawSprite()` is called by `Sprite`s and `Sheet`s in order to draw their images.\nIt is not exposed to the window.\n\n drawSprite = (sheet, start_index, context, x, y, frame = 0) ->\n\n\u2026That's a lot of arguments. Let's go through them:\n\n- `sheet` is the `Sheet` from which to draw the sprite\n- `start_index` gives us the index of the sprite within the sheet\n- `context` is the `CanvasRenderingContext2D` on which to draw the sprite\n- `x` is the x-coordinate of the top-left corner of the sprite\n- `y` is the y-coordinate of the top-left corner of the sprite\n- `frame` is merely there as a convenience: It increments `start_index` by its value\n\nThe first thing we do is make sure everything is typed correctly.\nThe `sheet` and `context`, clearly, need to be of a certain type in order for this to work.\nIf any of the other provided arguments aren't numbers, however, we can go ahead and reset them to zero.\n\n return unless sheet instanceof Sheet and start_index < sheet.size and context instanceof CanvasRenderingContext2D\n start_index = 0 if isNaN(start_index = Number(start_index))\n x = 0 if isNaN(x = Math.round(x))\n y = 0 if isNaN(y = Math.round(y))\n frame = 0 if isNaN(frame = Number(frame))\n\nNow we can increment `start_index` by `frame`'s value:\n\n start_index += frame\n\nNext, we need to find the horizontal (`i`) and vertical (`j`) position of the sprite on the sheet.\nWe can get this information from `start_index` with a little math:\n\n i = start_index % sheet.width\n j = Math.floor(start_index \/ sheet.width)\n\nThese two lines just make the image a little easier to access:\n\n source = sheet.source\n image = sheet.image\n\nNow we have all we need to draw the sprite!\nThere is a HUGE `if`-statement associated with the draw function, because we want to make sure that what we're drawing is actually there.\nIf it isn't, then obviously we can't draw anything.\n\nRemember also that `image` is preferenced if defined.\n\n context.drawImage((if createImageBitmap? and image instanceof ImageBitmap then image else source), i * width, j * height, width, height, x, y, width, height) if (source instanceof HTMLImageElement and source.complete or source instanceof SVGImageElement or source instanceof HTMLCanvasElement or createImageBitmap? and (image instanceof ImageBitmap or source instanceof ImageBitmap)) and not isNaN(i) and not isNaN(j) and (width = Number(sheet.sprite_width)) and (height = Number(sheet.sprite_height))\n\nLet's go through what that `if`-statement actually did.\nFirst, we make sure that the `Sheet` actually has an image associated with it:\n\n- `source instanceof HTMLImageElement and source.complete`\u2014\n If the image source is an `` element, then it needs to have finished loading.\n\n- `source instanceof SVGImageElement or source instanceof HTMLCanvasElement`\u2014\n The source doesn't have to be an `` element though! It can also be an `` or a ``.\n\n- `createImageBitmap? and (image instanceof ImageBitmap or source instanceof ImageBitmap)`\u2014\n Finally, the source can be an `ImageBitmap`.\n This isn't supported in all browsers, so we check to make sure `createImageBitmap` exists first.\n However, if `createImageBitmap` *is* supported, then `Sheet`s have a special property, `Sheet.image`, which might contain one, and this should be given preference.\n\nWe also need to make sure that the sprite exists on the sheet:\n\n- `not isNaN(i) and not isNaN(j)`\u2014\n This makes sure that our indices are actually, y'know, numbers.\n\n- `(width = Number(sheet.sprite_width)) and (height = Number(sheet.sprite_height))`\u2014\n This makes sure that the sprites in the sheet have a non-zero width and height.\n It also sets the variables `width` and `height` to those values, for convenient access later.\n\n### Sprite: ###\n\n`Sprite` creates a reference to a sprite on a sheet.\nFor efficiency's sake, it does *not* actually contain any of the image data associated with that sprite.\n\n#### The constructor ####\n\nThe constructor takes three arguments: `sheet`, which gives the sheet; `index`, which is the index of the sprite on the sheet; and `length`, which for animated sprites gives the length of the animation.\n\n Sprite = (sheet, index, length = 1) ->\n\nIf `index` or `length` aren't numbers, then we go ahead and set them to `0` and `1`, respectively.\nIf `sheet` isn't a `Sheet`, then we set it to be null.\n\n sheet = null unless sheet instanceof Sheet\n index = 0 if isNaN(index = Number(index))\n length = 1 if isNaN(length = Number(length)) or length <= 0\n\nNow we can set the properties.\nNote that `draw` simply binds `drawSprite` to the given `Sheet` and `index`.\n\n Object.defineProperty this, \"draw\", {value: drawSprite.bind(this, sheet, index)}\n @height = if sheet then sheet.sprite_height else 0\n @index = index\n @frames = length\n @sheet = sheet\n @width = if sheet then sheet.sprite_width else 0\n\nSince `Sprite`s are just static references, they should be immutable:\n\n Object.freeze this\n\nAnd we're done!\n\n#### The prototype ####\n\n`Sprite`s are very simple, and because the `draw` function is bound above, they don't really have a prototype.\nFor purposes of inheritance, however, I've thrown this minimal one together:\n\n Sprite.prototype = {draw: ->}\n Object.freeze Sprite.prototype\n\n### Sheet: ###\n\n`Sheet`s associate images with data and methods to make them easily referencable as sprite-sheets.\n\n#### The constructor ####\n\nThe `Sheet` constructor only takes three arguments: `source`, which gives the source image for the sheet, `sprite_width`, which gives the width of the sprites, and `sprite_height`, which gives their height.\nIn doing so, it makes the assumption that sprites and sprite-sheets do not have any borders or padding.\n(Because borders and padding result in larger download times for users, this restriction is considered acceptable, but it may be lifted at some time in the future.)\n\n Sheet = (source, sprite_width, sprite_height) ->\n\nFirst, we need to handle the arguments.\nIf `source` isn't an image type that we recognize, we go ahead and set it to `null`.\nAnd if the `sprite_width` or `sprite_height` aren't recognizable as numbers, we set them to 0.\n(Note from the above that a `Sheet` with zero `sprite_width` or `sprite_height` cannot be drawn.)\n\n source = null unless source instanceof HTMLImageElement or source instanceof SVGImageElement or source instanceof HTMLCanvasElement or createImageBitmap? and source instanceof ImageBitmap\n sprite_width = 0 if isNaN(sprite_width = Number(sprite_width))\n sprite_height = 0 if isNaN(sprite_height = Number(sprite_height))\n\nRecall that we need to check for `createImageBitmap` before checking to see if the source is an `ImageBitmap`.\n\nWe can get the width and height of the image from one of two sources, depending on the source type.\nAll of the accepted types have `width` and `height` properties, which specify their dimensions.\nHowever, `HTMLImageElement`s also have `naturalWidth` and `naturalHeight` properties, and these should be preferred for pixel-perfect rendering.\n\nIf for some reason we can't get *either* of these properties, then the `source_width` and `source_height` are set to zero.\n\n source_width = 0 unless source? and not isNaN(source_width = Number(if source.naturalWidth? then source.naturalWidth else source.width))\n source_height = 0 unless source? and not isNaN(source_height = Number(if source.naturalHeight? then source.naturalHeight else source.height))\n\nWe now have everything we need to define the properties.\nNote that `width` and `height` are provided in sprite-units, not pixels.\nIf `sprite_width` or `sprite_height` are `0`, then the corresponding `width` and `height` are obviously `NaN`.\n\n @height = Math.floor(source_height \/ sprite_height)\n @source = source\n @sprite_height = sprite_height\n @sprite_width = sprite_width\n @width = Math.floor(source_width \/ sprite_width)\n\nThe `size` property is just `width` times `height`.\n\n @size = @width * @height\n\nThe `image` property is defined using a getter in order to allow the `createImageBitmap` callback to change it.\n\n image = null\n Object.defineProperty(this, \"image\", {get: -> image})\n\n`ImageBitmap`s are optimized for drawing to the canvas.\nIf they are supported, we can pre-render the sprite-sheet and store this in the `image` property.\n\n createImageBitmap(source).then((img) -> image = img) if createImageBitmap?\n\nBecause `Sheet`s contain static images, it doesn't make sense for them to change after creation.\nWe freeze them:\n\n Object.freeze this\n\n#### The prototype ####\n\nThe `Sheet` prototype is fairly minimal, consisting of only two functions.\n\n Sheet.prototype =\n\nThe first, `drawIndex`, draws the sprite located at the given `index`.\nIt is little more than a repackaging of `drawSprite`.\n\n drawIndex: (context, index, x, y) -> drawSprite(this, index, context, x, y)\n\nThe second, `getSprite`, creates a new `Sprite` pointing to the given `index`.\nIt is the most convenient way of creating `Sprite` objects.\nIt takes two arguments, the `index` of the sprite, and the `length` of the animation.\n\n getSprite: (index, length = 1) -> new Sprite(this, index, length)\n\nWe can now freeze the prototype:\n\n Object.freeze Sheet.prototype\n\n#### Final touches ####\n\nFor convenience's sake, two static methods have been defined for `Sheet` to let you draw arbitrary sprites.\nThese are largely intended for use with callbacks.\n\nThe first is called `draw`, and takes five arguments:\n\n- `context`: A `CanvasRenderingContext2D`\n- `sprite`: A `Sprite`\n- `x`: The x-coordinate at which to draw the sprite\n- `y`: The y-coordinate at which to draw the sprite\n- `frame`: The frame of the animation which to draw\n\nIt maps onto `sprite.draw`:\n\n Sheet.draw = (context, sprite, x, y, frame = 0) -> sprite.draw(context, x, y, frame) if sprite instanceof Sprite\n\nThe second is called `drawSheetAtIndex`, and also takes five arguments:\n\n- `context`: A `CanvasRenderingContext2D`\n- `sheet`: A `Sheet`\n- `index`: The index of the sprite\n- `x`: The x-coordinate at which to draw the sprite\n- `y`: The y-coordinate at which to draw the sprite\n\nIt maps onto `sheet.drawIndex`:\n\n Sheet.drawSheetAtIndex = (context, sheet, index, x, y) -> sheet.drawIndex(context, index, x, y) if sheet instanceof Sheet\n\nWith those functions defined, we can add the `Sprite` constructor to `Sheet` for later access, and then make `Sheet` available to the window.\nWe go ahead and freeze both to keep them safe.\n\n Sheet.Sprite = Object.freeze(Sprite)\n @Sheet = Object.freeze(Sheet)\n\n\u2026And that's the end!\n","avg_line_length":43.9215686275,"max_line_length":509,"alphanum_fraction":0.7230357143} -{"size":2558,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"# \/api\/App Components\/Batman.StorageAdapter\/Batman.StorageAdapter Errors\n\nWhen a [`Batman.StorageAdapter`](\/docs\/api\/batman.storageadapter.html) fails to complete an operation, it throws a specific error. `Batman.Controller` can set up handlers for these errors with `@catchError`. Each error class prototype has:\n\n- `name`, which matches its class name (eg, `Batman.StorageAdapter.RecordExistsError::name` is `\"RecordExistsError\"`)\n- `message`, which describes the error\n\n## Storage Errors and HTTP Status Codes\n\n`Batman.RestStorage` (and, by inheritance, `Batman.RailsStorage`) throws storage errors according to to the HTTP status codes. Each code is mapped to an error:\n\nHTTP Code | Storage Error\n-- | --\n`0` | `Batman.StorageAdapter.CommunicationError`\n`401` | `Batman.StorageAdapter.UnauthorizedError`\n`403` | `Batman.StorageAdapter.NotAllowedError`\n`404` | `Batman.StorageAdapter.NotFoundError`\n`406` | `Batman.StorageAdapter.NotAcceptableError`\n`409` | `Batman.StorageAdapter.RecordExistsError`\n`413` | `Batman.StorageAdapter.EntityTooLargeError`\n`422` | `Batman.StorageAdapter.UnprocessableRecordError`\n`500` | `Batman.StorageAdapter.InternalStorageError`\n`501` | `Batman.StorageAdapter.NotImplementedError`\n`502` | `Batman.StorageAdapter.BadGatewayError`\n\n## Batman.StorageAdapter.StorageError\n\nThe base class for all other storage errors.\n\n## Batman.StorageAdapter.RecordExistsError\n\nDefault message: `\"Can't create this record because it already exists in the store!\"`.\n\n## Batman.StorageAdapter.NotFoundError\n\nDefault message: `\"Record couldn't be found in storage!\"`.\n\n## Batman.StorageAdapter.UnauthorizedError\n\nDefault message: `\"Storage operation denied due to invalid credentials!\"`.\n\n## Batman.StorageAdapter.NotAllowedError\n\nDefault message: `\"Storage operation denied access to the operation!\"`.\n\n## Batman.StorageAdapter.NotAcceptableError\n\nDefault message: `\"Storage operation permitted but the request was malformed!\"`.\n\n## Batman.StorageAdapter.EntityTooLargeError\n\nDefault message: `\"Storage operation denied due to size constraints!\"`.\n\n## Batman.StorageAdapter.UnprocessableRecordError\n\nDefault message: `\"Storage adapter could not process the record!\"`.\n\n## Batman.StorageAdapter.InternalStorageError\n\nDefault message: `\"An error occurred during the storage operation!\"`.\n\n## Batman.StorageAdapter.NotImplementedError\n\nDefault message: `\"This operation is not implemented by the storage adapter!\"`.\n\n## Batman.StorageAdapter.BadGatewayError\n\nDefault message: `\"Storage operation failed due to unavailability of the backend!\"`.\n","avg_line_length":37.0724637681,"max_line_length":239,"alphanum_fraction":0.7888975762} -{"size":1704,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"The CIE AFAICT don't publish reference translation tables, so we generate some\nwith the code at (which\nis assumed to be correct and safe.)\n\n [path, fs, _] = ['path', 'fs', 'underscore'].map require\n library = path.resolve(__dirname, '..', '..', '..', 'vendor', 'brucelindbloom.com', 'ColorConv.js')\n eval fs.readFileSync(library, 'utf8')\n\nWe consider the translation of 400 SRGB vectors with values scaled to the open\ninterval [0,1]:\n\n r = () -> Math.random()\n sRGBs = [1..400].map () -> [r(), r(), r()]\n\n form =\n RGBModel: { selectedIndex: 14 } # sRGB\n Gamma: { selectedIndex: 0 } # sRGB\n Adaptation: { selectedIndex: 3 } # None\n RefWhite: { selectedIndex: 5 } # D65\n RGBModelChange form\n\nLindbloom's functions depend heavily on global variables; we define wrappers\nthat set these based on arguments, and recover the set results:\n\n FillAllCells = () -> null\n\n toXYZ = (rgb) ->\n [form.RGB_R, form.RGB_G, form.RGB_B] = rgb.map (v) -> {value: v}\n ButtonRGB(form)\n return [XYZ.X, XYZ.Y, XYZ.Z]\n\n toLAB = (rgb) -> \n [form.RGB_R, form.RGB_G, form.RGB_B] = rgb.map (v) -> {value: v}\n ButtonRGB(form)\n return [Lab.L, Lab.a, Lab.b]\n \n toYxy = (rgb) -> \n [form.RGB_R, form.RGB_G, form.RGB_B] = rgb.map (v) -> {value: v}\n ButtonRGB(form)\n return [xyY.Y, xyY.x, xyY.y]\n\nThat's all we need to test functions in any direction.\n\n Array::flatten = () -> _.flatten this\n lines = sRGBs.map (rgb) -> [rgb, toXYZ(rgb), toLAB(rgb), toYxy(rgb)].flatten().join(',')\n fs.writeFileSync path.resolve(__dirname, 'conv.csv'), lines.join('\\n')\n","avg_line_length":36.2553191489,"max_line_length":109,"alphanum_fraction":0.6138497653} -{"size":3392,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# \/api\/Data Structures\/Batman.Set\/Batman.SetIndex\n\n`Batman.SetIndex` is a grouped collection of items derived from a [`Batman.Set`](\/docs\/api\/batman.set.html) filled with [`Batman.Object`](\/docs\/api\/batman.object.html)s. It extends `Batman.Object` and [`Batman.Enumerable`](\/docs\/api\/batman.enumerable.html), so it inherits methods from them, too. In short, a `SetIndex` tracks its base `Set` and contains \"buckets\" of items from that `Set`, grouped by the provided key.\n\n test 'SetIndex groups items by values', ->\n batarang = new Batman.Object(name: \"Batarang\", type: \"ranged\")\n fists = new Batman.Object(name: \"Fists\", type: \"melee\")\n\n weapons = new Batman.Set(batarang, fists)\n # Three ways to create a SetIndex:\n weaponsByType1 = weapons.indexedBy('type')\n weaponsByType2 = weapons.get('indexedBy.type')\n weaponsByType3 = new Batman.SetIndex(weapons, 'type')\n\n # additions to the base Set are tracked by the SetIndex\n grappleGun = new Batman.Object(name: \"Grapple Gun\", type: \"ranged\")\n weapons.add(grappleGun)\n\n for setIndex in [weaponsByType1, weaponsByType2, weaponsByType3]\n equal setIndex.get('ranged').get('length'), 2\n equal setIndex.get('melee').get('length'), 1\n deepEqual setIndex.get('ranged').mapToProperty('name'), [\"Batarang\", \"Grapple Gun\"]\n deepEqual setIndex.toArray(), [\"ranged\", \"melee\"]\n\n\n## ::constructor(base : Set, key : String ) : SetIndex\n\nA `SetIndex` is made with a `base` and a `key`. Items in the `base` set will be grouped according to their value for `key`. The resulting `SetIndex` observes its `base`, so any items added to the `base` are also added (and indexed) in the `SetIndex`\n\n## ::get(value : String) : Set\n\nReturns a `Batman.Set` of items whose indexed `key` matches `value`. It returns an empty set if no items match `value`, but if any matching items are added to the `base` set, they will also be added to this set.\n\n## ::toArray() : Array\n\nReturns an array with the distinct values of `key` provided to the constructor.\n\n## ::forEach(func)\n\nCalls `func(key, group)` for each group in the SetIndex.\n\n# \/api\/Data Structures\/Batman.Set\/Batman.UniqueSetIndex\n\n`Batman.UniqueSetIndex` extends [`SetIndex`](\/docs\/api\/batman.setindex.html) but adds a new consideration: its index contains _first matching item_ for each value of the `key` (rather than all matching items).\n\n test 'UniqueSetIndex takes the first matching item', ->\n batarang = new Batman.Object(name: \"Batarang\", type: \"ranged\")\n fists = new Batman.Object(name: \"Fists\", type: \"melee\")\n\n weapons = new Batman.Set(batarang, fists)\n\n # Three ways to make a UniqueSetIndex:\n weaponsByUniqueType1 = weapons.indexedByUnique('type')\n weaponsByUniqueType2 = weapons.get('indexedByUnique.type')\n weaponsByUniqueType3 = new Batman.UniqueSetIndex(weapons, 'type')\n\n # additions to the base Set are tracked by the SetIndex\n grappleGun = new Batman.Object(name: \"Grapple Gun\", type: \"ranged\")\n weapons.add(grappleGun)\n\n for uniqueSetIndex in [weaponsByUniqueType1, weaponsByUniqueType2, weaponsByUniqueType3]\n equal uniqueSetIndex.get('ranged').get('name'), \"Batarang\"\n equal uniqueSetIndex.get('melee').get('name'), \"Fists\"\n\n## ::get(value : String) : Object\n\nReturns the first matching member whose indexed `key` is equal to `value`.\n","avg_line_length":49.8823529412,"max_line_length":419,"alphanum_fraction":0.7043042453} -{"size":727,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# `Columns.Heading` #\n\n## Usage ##\n\n> ```jsx\n> icon=React.PropTypes.string\n> >\n> {\/* content *\/}\n> <\/Heading>\n> ```\n> Creates a `Heading` component, which is just the heading to a `Column`. The accepted properties are:\n> - **`icon` [REQUIRED `string`] :**\n> The icon to associate with the heading.\n\n## The Component ##\n\nThe `Heading` is just a simple functional React component.\n\n Columns.Heading = (props) ->\n \u5f41 'h2', {className: \"labcoat-heading\"},\n if props.icon\n \u5f41 Shared.Icon, {name: props.icon}\n else null\n props.children\n\n Columns.Heading.propTypes =\n icon: React.PropTypes.string\n","avg_line_length":25.0689655172,"max_line_length":104,"alphanum_fraction":0.552957359} -{"size":1168,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"With Double Extension\n=====================\n\n#### Here, we preceed the `.litcoffee` extension with our own custom extension\n\nTo watch and compile automatically: \n```bash\ncoffee --watch --compile with-double-extension.whoops456.litcoffee\n```\n\n\n\n\nHelpers\n-------\n\n#### `\u00aa()`\nShorthand `console.log()`. \n\n \u00aa = console.log.bind console\n\n\n\n\n#### `vpSize()`\nReturns an array with two elements, the viewport width and the viewport height. \nBased on [this Stack Overflow answer. ](http:\/\/stackoverflow.com\/a\/11744120)\n\n vpSize = ->\n d = document\n e = d.documentElement\n b = d.getElementsByTagName('body')[0]\n w = window.innerWidth || e.clientWidth || b.clientWidth\n h = window.innerHeight || e.clientHeight || b.clientHeight\n #w = window.screen.width\n #h = window.screen.height\n [w,h]\n\n\n\n\nClasses\n-------\n\n@todo describe\n\n class Validator\n\n class ValidatorRx extends Validator\n constructor: (@rx, @message) ->\n check: ($element) -> if @rx.test $element.html() then @message\n\n\n\n\nBoot\n----\n\nWhen the DOM is ready, create an instance of ValidatorRx. \n\n jQuery ->\n window.validatorRx = new ValidatorRx\n\n\n\n\n\n\n","avg_line_length":16.9275362319,"max_line_length":80,"alphanum_fraction":0.636130137} -{"size":2076,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"This file defines the date parser (this.dateMachine).\n\nIn order to work it needs a parserDescription, and functions to run based off it.\n\nTo understand the purpose of the overlapping functions first see ```parserDescription```\nand see that the each pattern has an 'order', that defines how complex the pattern is looking for.\n\n\nThe a leaf node of the parse tree looks like this ```[3, 'month', [...]]```.\n\n- ```3``` is how many capture groups to **take** and pull into the next level of recursion.\n- ```'month'``` is the string **functionName** corresponding to the function to run on the output of the tree\n- ```'[...]'``` is another leaf node **tree**. At the bottom of the tree this is empty,\n and the function runs over the capture groups themselves. Then, the results\n bubble up to the top of the tree, being processed by the named functions along the way.\n\nThe emulator as a whole acts on a the result set of a regular expression from a single pattern.\nIt's recursive, so its arguments look like the structure of a leaf nodes.\n\n reparseEmulator = (take, functionName, tree, matches, functions) ->\n results = []\n currentPosition = 0\n for element in tree\n [elementTake, elementFunctionName, elementTree] = element\n\n releventMatches = matches.slice(currentPosition, currentPosition + elementTake)\n results.push reparseEmulator(elementTake, elementFunctionName, elementTree, releventMatches, functions)\n currentPosition += elementTake\n\n if tree.length is 0\n executeFunction functionName, matches.slice(0, take), functions, true\n else\n executeFunction functionName, results, functions, true\n\n executeFunction = (functionName, arguments_, functions, isType) ->\n functions[functionName].apply(functions[functionName], arguments_)\n\nFinally it's important to set up each regular expression\nso they are regex objects instead of simple strings.\n\n for pattern in parserDescription\n pattern.regex = new RegExp(pattern.regex, \"gi\")\n","avg_line_length":48.2790697674,"max_line_length":115,"alphanum_fraction":0.7080924855} -{"size":5612,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":5.0,"content":"\n## xml2json tests\n\nAuthor: Jan Gottschick\n\nTo test the xml2json ...\n\nImporting the Jasmine test framework addons to describe the specifications by\nexamples.\n\n require 'jasmine-matchers'\n require 'jasmine-given'\n\n xml2json = require '..\/lib\/xml2jsonModule'\n\n compile = (__done, __expr, __test, __debug = false) ->\n try\n __code = xml2json.parse(__expr)\n catch error\n console.log error.name + \" at \" + error.line + \",\" + error.column + \": \" + error.message if __debug\n __test false, ''\n __done()\n return\n __test true, __code\n __done()\n\nAnd the tests...\n\n describe 'The XML elements', ->\n\n it 'should code a closed tag', (done) ->\n compile done, '''\n \n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[]}])\n\n it 'should code an empty tag', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[]}])\n\n it 'should code embedded tags', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{tag1:[]},{tag2:[]}]}])\n\n it 'should code tag values', (done) ->\n compile done, '''\n 123\n 456<\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'#text':'123'},{'#text':'456'}]}])\n\n describe 'The XML attributes', ->\n\n it 'should code an single attribute', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a':\"1\"}]}])\n\n it 'should code an empty attribute', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a':null}]}])\n\n it 'should code multiple attributes', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a1':\"1\"},{'@a2':\"2\"}]}])\n\n describe 'The XML namespaces', ->\n\n it 'should be define a namespace', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a':\"1\"},{\"@__xmlns__url\":\"http:\/\/www.domain.de\"}]}])\n\n it 'should be used in a namespace of a tag', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a':\"1\"},{\"@__xmlns__url\":\"http:\/\/www.domain.de\"},{\"__http%3A%2F%2Fwww.domain.de__tag\":[]}]}])\n\n it 'should be used in a namespace of a tag including the markers', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a':\"1\"},{\"@__xmlns__url\":\"http:\/\/www.domain__.de\"},{\"__http%3A%2F%2Fwww.domain%5F%5F.de__tag\":[]}]}])\n\n it 'should be used in a namespace of an attribute', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{'@a':\"1\"},{\"@__xmlns__url\":\"http:\/\/www.domain.de\"},{\"tag1\":[{\"@__http%3A%2F%2Fwww.domain.de__a1\":null}]}]}])\n\n it 'should use the right scopes', (done) ->\n compile done, '''\n <\/tag2><\/tag1>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{\"tag1\":[{\"@__xmlns__url\":\"http:\/\/www.domain1.de\"},{\"tag2\":[{\"@a\":\"1\"},{\"@__xmlns__url\":\"http:\/\/www.domain2.de\"},{\"tag3\":[{\"@__http%3A%2F%2Fwww.domain2.de__a1\":null},{\"@__xmlns__url2\":\"http:\/\/www.domain3.de\"},{\"@__http%3A%2F%2Fwww.domain3.de__a2\":null}]}]},{\"tag3\":[{\"@__http%3A%2F%2Fwww.domain1.de__a1\":null}]}]}])\n\n describe 'The XML comments', ->\n\n it 'should comment the header', (done) ->\n compile done, '''\n \n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{\"#comment\":\" my comment \"},{tag:[]}])\n\n it 'should comment tags', (done) ->\n compile done, '''\n <\/tag>\n ''', (ok, result) ->\n expect(ok).toBe true\n expect(JSON.stringify(result)).toBe JSON.stringify([{tag:[{\"#comment\":\" my comment \"}]}])\n","avg_line_length":41.5703703704,"max_line_length":377,"alphanum_fraction":0.5425873129} -{"size":7829,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":"

Laboratory<\/i>
Source Code and Documentation
API Version: 0.4.0<\/i>
Constructors\/Timeline.litcoffee<\/code><\/p>\n\n# THE TIMELINE CONSTRUCTOR #\n\n - - -\n\n## Description ##\n\nThe `Timeline()` constructor creates a unique, read-only object which represents a Mastodon timeline.\nIts properties are summarized below, alongside their Mastodon API equivalents:\n\n| Property | API Response | Description |\n| :-------: | :------------: | :---------- |\n| `posts` | [The response] | An ordered array of posts in the timeline, in reverse-chronological order |\n| `length` | *Not provided* | The length of the timeline |\n\n### Timeline types:\n\nThe possible `Timeline.Type`s are as follows:\n\n| Enumeral | Hex Value | Description |\n| :------: | :----------: | :---------- |\n| `Timeline.Type.UNDEFINED` | `0x00` | No type is defined |\n| `Timeline.Type.PUBLIC` | `0x10` | A public timeline |\n| `Timeline.Type.HOME` | `0x20` | A user's home timeline |\n| `Timeline.Type.NOTIFICATIONS` | `0x21` | A user's notifications |\n| `Timeline.Type.FAVOURITES` | `0x22` | A list of a user's favourites |\n| `Timeline.Type.ACCOUNT` | `0x40` | A timeline of an account's posts |\n| `Timeline.Type.HASHTAG` | `0x80` | A hashtag search |\n\n### Prototype methods:\n\n#### `join()`.\n\n> ```javascript\n> Laboratory.Timeline.prototype.join(data);\n> ```\n>\n> - __`data` :__ A `Post`, array of `Post`s, or a `Timeline`\n\nThe `join()` prototype method joins the `Post`s of a timeline with that of the provided `data`, and returns a new `Timeline` of the results.\n\n#### `remove()`.\n\n> ```javascript\n> Laboratory.Timeline.prototype.remove(data);\n> ```\n>\n> - __`data` :__ A `Post`, array of `Post`s, or a `Timeline`\n\nThe `remove()` prototype method collects the `Post`s of a timeline except for those of the provided `data`, and returns a new `Timeline` of the results.\n\n - - -\n\n## Examples ##\n\n> __[Issue #53](https:\/\/github.com\/marrus-sh\/laboratory\/issues\/53) :__\n> Usage examples for constructors are forthcoming.\n\n - - -\n\n## Implementation ##\n\n### The constructor:\n\nThe `Timeline()` constructor takes a `data` object and uses it to construct a timeline.\n`data` can be either an API response or an array of `Post`s.\n\n Laboratory.Timeline = Timeline = (data) ->\n\n unless this and this instanceof Timeline\n throw new TypeError \"this is not a Timeline\"\n unless data?\n throw new TypeError \"Unable to create Timeline; no data provided\"\n\nMastodon keeps track of ids for notifications separately from ids for posts, as best as I can tell, so we have to verify that our posts are of matching type before proceeding.\nReally all we care about is whether the posts are notifications, so that's all we test.\n\n isNotification = (object) -> !!(\n (\n switch\n when object instanceof Post then object.type\n when object.type? then Post.Type.NOTIFICATION # This is an approximation\n else Post.Type.STATUS\n ) & Post.Type.NOTIFICATION\n )\n\nWe'll use the `getPost()` function in our post getters.\n\n getPost = (id, isANotification) ->\n if isANotification then Store.notifications[id] else Store.statuses[id]\n\nWe sort our data according to when they were created, unless two posts were created at the same time.\nThen we use their ids.\n\n> __Note :__\n> Until\/unless Mastodon starts assigning times to notifications, there are a few (albeit extremely unlikely) edge-cases where the following `sort()` function will cease to be well-defined.\n> Regardless, attempting to create a timeline out of both notifications and statuses will likely result in a very odd sorting.\n\n data.sort (first, second) ->\n if not (isNotification first) and not (isNotification second) and (\n a = Number first instanceof Post and first.datetime or Date first.created_at\n ) isnt (\n b = Number second instanceof Post and second.datetime or Date second.created_at\n ) then -1 + 2 * (a > b) else second.id - first.id\n\nNext we walk the array and look for any duplicates, removing them.\n\n> __Note :__\n> Although `Timeline()` purports to remove all duplicate `Post`s, this behaviour is only guaranteed for *contiguous* `Post`s\u2014given our sort algorithm, this means posts whose `datetime` values are also the same.\n> If the same post ends up sorted to two different spots, `Timeline()` will leave both in place.\n> (Generally speaking, if you find yourself with two posts with identical `id`s but different `datetime`s, this is a sign that something has gone terribly wrong.)\n\n prev = null\n for index in [data.length - 1 .. 0]\n currentID = (current = data[index]).id\n if prev? and currentID is prev.id and\n (isNotification prev) is (isNotification current)\n data.splice index, 1\n continue\n prev = current\n\nFinally, we implement our list of `posts` as getters such that they always return the most current data.\n**Note that this will likely prevent optimization of the `posts` array, so it is recommended that you make a static copy (using `Array.prototype.slice()` or similar) before doing intensive array operations with it.**\n\n> __[Issue #28](https:\/\/github.com\/marrus-sh\/laboratory\/issues\/28) :__\n> At some point in the future, `Timeline` might instead be implemented using a linked list.\n\n @posts = []\n Object.defineProperty @posts, index, {\n enumerable: yes\n get: getPost.bind(this, value.id, isNotification value)\n } for value, index in data\n Object.freeze @posts\n\n @length = data.length\n\n return Object.freeze this\n\n### The prototype:\n\nThe `Timeline` prototype has two functions.\n\n Object.defineProperty Timeline, \"prototype\",\n value: Object.freeze\n\n#### `join()`.\n\nThe `join()` function creates a new `Timeline` which combines the `Post`s of the original and the provided `data`.\nIts `data` argument can be either a `Post`, an array thereof, or a `Timeline`.\nWe don't have to worry about duplicates here because the `Timeline()` constructor should take care of them for us.\n\n join: (data) ->\n return this unless data instanceof Post or data instanceof Array or\n data instanceof Timeline\n combined = post for post in switch\n when data instanceof Post then [data]\n when data instanceof Timeline then data.posts\n else data\n combined.push post for post in @posts\n return new Timeline combined\n\n#### `remove()`.\n\nThe `remove()` function returns a new `Timeline` with the provided `Post`s removed.\nIts `data` argument can be either a `Post`, an array thereof, or a `Timeline`.\n\n remove: (data) ->\n return this unless data instanceof Post or data instanceof Array or\n data instanceof Timeline\n redacted = (post for post in @posts)\n redacted.splice index, 1 for post in (\n switch\n when data instanceof Post then [data]\n when data instanceof Timeline then data.posts\n else data\n ) when (index = redacted.indexOf post) isnt -1\n return new Timeline redacted\n\n### Defining timeline types:\n\nHere we define our `Timeline.Type`s, as described above:\n\n Timeline.Type = Enumeral.generate\n UNDEFINED : 0x00\n PUBLIC : 0x10\n HOME : 0x20\n NOTIFICATIONS : 0x21\n FAVOURITES : 0x22\n ACCOUNT : 0x40\n HASHTAG : 0x80\n","avg_line_length":40.7760416667,"max_line_length":216,"alphanum_fraction":0.6396730106} -{"size":274,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Set up `tudor`\n==============\n\nCreate an instance of `Tudor`, to add tests to. \n\n tudor = new Tudor\n format: if env.has.window then 'html' else 'plain'\n\n\nAllow the `Tudor` instance\u2019s `do()` method to be called using `Che.runTest()`. \n\n Che.runTest = tudor.do\n\n\n\n\n","avg_line_length":16.1176470588,"max_line_length":79,"alphanum_fraction":0.6094890511} -{"size":1599,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"\n getKeys = (object, type) ->\n return Object.keys object.prototype if type == 'prototype'\n Object.keys object\n\n processMap = (byWhatMap) ->\n if byWhatMap instanceof Array\n [byWhatProperty, type, keys] = byWhatMap\n else\n byWhatProperty = byWhatMap\n type ?= 'prototype'\n keys ?= getKeys byWhatProperty, type\n return [byWhatProperty, type, keys]\n\n extendByMap = (what, how) ->\n for whatProperty, byWhatMap of how\n [byWhatProperty, type, keys] = processMap byWhatMap\n if what[whatProperty]?\n for key in keys\n if type == 'prototype'\n what[whatProperty].prototype[key] = byWhatProperty.prototype[key]\n else\n what[whatProperty][key] = byWhatProperty[key]\n else\n what[whatProperty] = byWhatProperty\n\n interfaces = (implementation) ->\n rdf = require switch implementation\n when 'rdf', 'node-rdf'\n '.\/interfaces_rdf'\n else\n '.\/interfaces_rdf'\n ### \/\/ TODO\n when 'rdfi', 'rdf-interfaces'\n '.\/interfaces_rdfi'\n when 'rdf_js_interface', 'rdf_js_interfaces', 'rdfstore', 'rdfstorejs', 'rdfstore.js'\n '.\/interfaces_rdf_js_interface'\n ###\n rdf.interfaces = interfaces\n rdf.use = (extension) ->\n if extension.RDFInterfacesExtMap?\n extendByMap rdf, extension.RDFInterfacesExtMap\n rdf.extensions ?= {}\n rdf.extensions.ClassMap ?= require '.\/ClassMap'\n rdf.extensions.Resource ?= require '.\/Resource'\n rdf\n\n module.exports = interfaces()\n","avg_line_length":32.6326530612,"max_line_length":93,"alphanum_fraction":0.6041275797} -{"size":343,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":" Template.home.helpers\n response: -> (Session.get 'response')?.response\n\n Template.home.events\n 'submit form': (event) ->\n event.preventDefault()\n\n $('.question-form')[0].reset()\n\n Meteor.call 'randomResponse', (error, response) ->\n console.log response\n Session.set 'response', response\n","avg_line_length":26.3846153846,"max_line_length":58,"alphanum_fraction":0.5947521866} -{"size":712,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"DOM Helpers\n===========\n\n#### Helper functions for the HTML Document Object Model\n\n\n#### `$()`\nXx. \n\n $ = document.querySelector.bind document\n\n\n\n\n#### `$$()`\nXx. \n\n $$ = document.querySelectorAll.bind document\n\n\n\n\n#### `vpSize()`\nReturns an array with two elements, the viewport width and the viewport height. \nBased on [this Stack Overflow answer. ](http:\/\/stackoverflow.com\/a\/11744120)\n\n\n vpSize = ->\n d = document\n e = d.documentElement\n b = d.getElementsByTagName('body')[0]\n w = window.innerWidth || e.clientWidth || b.clientWidth\n h = window.innerHeight || e.clientHeight || b.clientHeight\n #w = window.screen.width\n #h = window.screen.height\n [w,h]\n\n\n\n\n","avg_line_length":17.3658536585,"max_line_length":80,"alphanum_fraction":0.6179775281} -{"size":1958,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# `Columns.Go` #\n\n## Usage ##\n\n> ```jsx\n> myID=React.PropTypes.number.isRequired\n> footerLinks=React.PropTypes.object\n> \/>\n> ```\n> Creates a `Column` component which contains a menu of useful tasks. The accepted properties are:\n> - **`myID` [OPTIONAL `number`] :**\n> The id of the currently signed-in user.\n> - **`footerLinks` [OPTIONAL `object`] :**\n> An object whose enumerable own properties provide links to display in the footer.\n\n## The Component ##\n\nThe `Go` component is just a simple functional React component, which loads a `Column` with helpful links.\n\n Columns.Go = (props) ->\n \u5f41 Columns.Column, {id: \"labcoat-go\"},\n \u5f41 Columns.Heading, {icon: \"icon.go\"},\n \u5f41 ReactIntl.FormattedMessage,\n id: \"go.heading\"\n defaultMessage: \"let's GO!\"\n \u5f41 \"nav\", {className: \"labcoat-columnnav\"},\n \u5f41 Columns.GoLink, {to: \"\/user\/\" + props.myID, icon: \"icon.profile\"},\n \u5f41 ReactIntl.FormattedMessage,\n id: 'go.profile'\n defaultMessage: \"Profile\"\n \u5f41 Columns.GoLink, {to: \"\/community\", icon: \"icon.community\"},\n \u5f41 ReactIntl.FormattedMessage,\n id: 'go.community'\n defaultMessage: \"Community\"\n \u5f41 Columns.GoLink, {to: \"\/global\", icon: \"icon.global\"},\n \u5f41 ReactIntl.FormattedMessage,\n id: 'go.global'\n defaultMessage: \"Global\"\n \u5f41 \"footer\", {className: \"labcoat-columnfooter\"},\n \u5f41 \"nav\", null,\n (\u5f41 \"a\", {href: value, target: \"_self\"}, key for key, value of (if props.footerLinks? then props.footerLinks else {}))...\n\n Columns.Go.propTypes =\n footerLinks: React.PropTypes.object\n myID: React.PropTypes.number.isRequired\n","avg_line_length":41.6595744681,"max_line_length":140,"alphanum_fraction":0.5383043922} -{"size":13741,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Tudor\n=====\n\nThe easy-to-write, easy-to-read test framework. \n\n\n\n\nDefine the `Tudor` class\n------------------------\n\n class Tudor\n I: 'Tudor'\n toString: -> \"[object #{I}]\"\n\n articles: []\n\n\n\n\nDefine the constructor\n----------------------\n\n constructor: (@opt={}) ->\n switch @opt.format\n when 'html'\n @pageHead = (summary) -> \"\"\"\n