root
add data
d9f7ff9
Invalid JSON: Unexpected non-whitespace character after JSONat line 2, column 1
{"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 <cking@ecc12.com>\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<!-- vim: ts=2 sts=2 sw=2 expandtab\n CoffeeScript-friendly tabstops in vim. -->\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 <xx>`\nXx. \n\n @xx = null\n\n\n\n\nStatic Methods\n--------------\n\n#### `square()`\n- `time <float>` From 0 to 1\n- `velocity <float>` From 0 to 1\n- `ctx2d <CanvasRenderingContext2D>` The canvas context to draw on\n- `size <integer>` 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 <xx>`\n@todo describe\n\n @x = null\n\n\n\n\nMethods\n-------\n\n\n#### `xx()`\n- `yy <zz>` @todo describe\n- `<undefined>` 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 `<img>` 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 `<img>` element though! It can also be an `<svg>` or a `<canvas>`.\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 <http:\/\/www.brucelindbloom.com\/javascript\/ColorConv.js> (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> <Heading\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 <?xml version=\"1.1\" ?><tag\/>\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 <?xml version=\"1.1\" ?><tag><\/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 <?xml version=\"1.1\" ?><tag><tag1\/><tag2\/><\/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 <?xml version=\"1.1\" ?><tag>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 <?xml version=\"1.1\" ?><tag a=\"1\"><\/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 <?xml version=\"1.1\" ?><tag a><\/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 <?xml version=\"1.1\" ?><tag a1=\"1\" a2=\"2\"><\/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 <?xml version=\"1.1\" ?><tag a=\"1\" xmlns:url=\"http:\/\/www.domain.de\"><\/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 <?xml version=\"1.1\" ?><tag a=\"1\" xmlns:url=\"http:\/\/www.domain.de\"><url:tag\/><\/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 <?xml version=\"1.1\" ?><tag a=\"1\" xmlns:url=\"http:\/\/www.domain__.de\"><url:tag\/><\/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 <?xml version=\"1.1\" ?><tag a=\"1\" xmlns:url=\"http:\/\/www.domain.de\"><tag1 url:a1\/><\/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 <?xml version=\"1.1\" ?><tag1 xmlns:url=\"http:\/\/www.domain1.de\"><tag2 a=\"1\" xmlns:url=\"http:\/\/www.domain2.de\"><tag3 url:a1 xmlns:url2=\"http:\/\/www.domain3.de\" url2:a2\/><\/tag2><tag3 url:a1\/><\/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 <?xml version=\"1.1\" ?><!-- my comment --><tag\/>\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 <?xml version=\"1.1\" ?><tag><!-- my comment --><\/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":"<p align=\"right\"><i>Laboratory<\/i> <br> Source Code and Documentation <br> API Version: <i>0.4.0<\/i> <br> <code>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> <Go\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 <style>\n body { font-family: sans-serif; }\n a { outline: 0; }\n b { display: inline-block; width: .7em }\n\n b.pass { color: #393 }\n b.fail { color: #bbb }\n article.fail b.pass { color: #bbb }\n section.fail b.pass { color: #bbb }\n\n pre { padding: .5em; margin: .2em 0; border-radius: 4px; }\n pre.fn { background-color: #fde }\n pre.pass { background-color: #cfc }\n pre.fail { background-color: #d8e0e8 }\n\n article { margin-bottom: .5rem }\n article h2 { padding-left:.5rem; margin:0; font-weight:normal }\n article.pass { border-left: 5px solid #9c9 }\n article.fail { border-left: 5px solid #9bf }\n article.fail h2 { margin-bottom: .5rem }\n article.pass >div { display: none }\n\n section { margin-bottom: .5rem }\n section h3 { padding-left: .5rem; margin: 0; }\n section.pass { border-left: 3px solid #9c9 }\n section.fail { border-left: 3px solid #9bf }\n section.fail h3 { margin-bottom: .5rem }\n section.pass >div { display: none }\n\n article.fail section.pass { border-left-color: #ccc }\n\n div { padding-left: .5em; }\n div.fail { border-left: 3px solid #9bf; font-size: .8rem }\n div h4 { margin: 0 }\n div h4 { font: normal .8rem\/1.2rem monaco, monospace }\n div.fail, div.fail h4 { margin: .5rem 0 }\n\n <\/style>\n <h4><a href=\"#end\" id=\"top\">\\u2b07<\/a> #{summary}<\/h4>\n \"\"\"\n @pageFoot = (summary) -> \"\"\"\n <h4><a href=\"#top\" id=\"end\">\\u2b06<\/a> #{summary}<\/h4>\n <script>\n document.title='#{summary.replace \/<\\\/?[^>]+>\/g,''}';\n <\/script>\n \"\"\"\n @articleHead = (heading, fail) ->\n \"<article class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h2>#{if fail then @cross else @tick}#{heading}<\/h2><div>\"\n @articleFoot = '<\/div><\/article>'\n @sectionHead = (heading, fail) ->\n \"<section class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h3>#{if fail then @cross else @tick}#{heading}<\/h3><div>\"\n @sectionFoot = '<\/div><\/section>'\n @jobFormat = (heading, result) ->\n \"<div class=\\\"#{if result then 'fail' else 'pass'}\\\">\" +\n \"<h4>#{if result then @cross else @tick}#{heading}<\/h4>\" + \n \"#{if result then @formatError result else ''}\" +\n \"<\/div>\"\n @tick = '<b class=\"pass\">\\u2713<\/b> ' # Unicode CHECK MARK\n @cross = '<b class=\"fail\">\\u2718<\/b> ' # Unicode HEAVY BALLOT X\n else\n @pageHead = (summary) -> \"#{summary}\"\n @pageFoot = (summary) -> \"\\n#{summary}\"\n @articleHead = (heading, fail) -> \"\"\"\n \n #{if fail then @cross else @tick} #{heading}\n ===#{new Array(heading.length).join '='}\n\n \"\"\"\n @articleFoot = ''\n @sectionHead = (heading, fail) -> \"\"\"\n\n #{if fail then @cross else @tick} #{heading}\n ---#{new Array(heading.length).join '-'}\n\n \"\"\"\n @sectionFoot = ''\n @jobFormat = (heading, result) ->\n \"#{if result then @cross else @tick} #{heading}\" +\n \"#{if result then '\\n' + @formatError result else ''}\"\n @jobFoot = ''\n @tick = '\\u2713' # Unicode CHECK MARK\n @cross = '\\u2718' # Unicode HEAVY BALLOT X\n\n\n\n\nDefine public methods\n---------------------\n\n#### `add()`\nAdd a new article to the page. An article must contain at least one section. \n\n add: (lines) ->\n\nCreate the `article` object and initialize `runner` and `section`. \n\n article = { sections:[] }\n runner = null\n section = null\n\nRun some basic validation on the `lines` array. \n\n if oo.A != oo.type lines then throw Error \"`lines` isn\u2019t an array\"\n if 0 == lines.length then throw Error \"`lines` has no elements\"\n if oo.S != oo.type lines[0] then throw Error \"`lines[0]` isn\u2019t a string\"\n\nAdd the article heading. \n\n article.heading = lines.shift()\n\nStep through each line, populating the `article` object as we go. \n\n i = 0\n while i < lines.length\n line = lines[i]\n switch oo.type line\n\nChange the current assertion-runner. \n\n when oo.O\n if ! line.runner then throw new Error \"Errant object\" #@todo better error message\n runner = line.runner\n\nRecord a mock-modifier. \n\n when oo.F\n section.jobs.push line\n\n when oo.S\n\nA string might signify a new assertion in the current section... \n\n if @isAssertion lines[i+1], lines[i+2]\n if ! section then throw new Error \"Cannot add an assertion here\"\n section.jobs.push [\n runner # <function> runner Function to run the assertion\n line # <string> name A short description\n lines[++i] # <mixed> expect Defines success\n lines[++i] # <function> actual Produces the result to test\n ]\n\n...or the beginning of a new section. \n\n else\n section = {\n heading: line\n jobs: []\n }\n article.sections.push section\n\n i++\n\nAppend the article to the `articles` array.\n\n @articles.push article\n\n\n\n\n#### `do()`\nRun the test and return the result. \n\n do: =>\n\nInitialize the output array, as well as `mock` and the page pass\/fail tallies. \n\n pge = []\n mock = []\n pgePass = pgeFail = mockFail = 0\n\n for article in @articles\n art = []\n artPass = artFail = 0\n\n for section in article.sections\n sec = []\n secPass = secFail = 0\n\n for job in section.jobs\n switch oo.type job\n when oo.F # a mock-modifier\n try mock = job.apply @, mock catch e then error = e.message\n if error\n mockFail++\n secFail++ #@todo does this interfere with proper pass\/fail tally?\n sec.push @formatMockModifierError job, error\n when oo.A # in the form `[ runner, heading, expect, actual ]`\n [ runner, heading, expect, actual ] = job # dereference\n result = runner expect, actual, mock # run the test\n if ! result\n sec.push @jobFormat \"#{@sanitize heading}\" \n pgePass++\n artPass++\n secPass++\n else\n sec.push @jobFormat \"#{@sanitize heading}\", result\n pgeFail++\n artFail++\n secFail++\n\n sec.unshift @sectionHead \"#{@sanitize section.heading}\", secFail\n sec.push @sectionFoot\n art = art.concat sec\n\nXx. \n\n art.unshift @articleHead \"#{@sanitize article.heading}\", artFail\n art.push @articleFoot\n pge = pge.concat art\n\nGenerate a page summary message. \n\n summary = if pgeFail\n \"#{@cross} FAILED #{pgeFail}\/#{pgePass + pgeFail}\"\n else\n \"#{@tick} Passed #{pgePass}\/#{pgePass + pgeFail}\"\n if mockFail\n summary = \"\\n#{@cross} (MOCK FAILS)\"\n\nReturn the result as a string, with summary at the start and end. \n\n pge.unshift @pageHead summary\n pge.push @pageFoot summary\n pge.join '\\n'\n\n\n\n\n#### `formatError()`\nFormat an exception or fail result. `result` should be an array with two, three \nor four elements. \n\n formatError: (result) ->\n switch \"#{result.length}-#{@opt.format}\"\n\nTo format an exception, the elements are intro text and an error object. \n\n when '2-html' then \"\"\"\n #{result[0]}\n <pre class=\"fail\">#{@sanitize result[1].message}<\/pre>\n \"\"\"\n when '2-plain' then \"\"\"\n #{result[0]}\n #{@sanitize result[1].message}\n \"\"\"\n\nTo format an normal fail, the elements are 'actual', 'delivery' and 'expected'. \n\n when '3-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]}<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]}<\/pre>\n \"\"\"\n when '3-plain' then \"\"\"\n #{@sanitize @reveal result[0]}\n ...#{result[1]}...\n #{@sanitize @reveal result[2]}\n \"\"\"\n\nA fourth element (of any kind) signifies the fail is just a type-difference. \n\n when '4-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]} (#{oo.type result[0]})<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]} (#{oo.type result[2]})<\/pre>\n \"\"\"\n when '4-plain' then \"\"\"\n #{@sanitize @reveal result[0]} (#{oo.type result[0]})\n ...#{result[1]}...\n #{@sanitize @reveal result[2]} (#{oo.type result[2]})\n \"\"\"\n\nAny other number of elements is invalid. \n\n else\n throw new Error \"Cannot process '#{result.length}-#{@opt.format}'\"\n\n\n\n\n#### `formatMockModifierError()`\nFormat an exception message encountered by a mock-modifier function. \n\n formatMockModifierError: (fn, error) ->\n switch @opt.format\n when 'html' then \"\"\"\n <pre class=\"fn\">#{@sanitize fn+''}<\/pre>\n ...encountered an exception:\n <pre class=\"fail\">#{@sanitize error}<\/pre>\n \"\"\"\n else \"\"\"\n #{@sanitize fn+''}\n ...encountered an exception:\n #{@sanitize error}\n \"\"\"\n\n\n\n\n#### `reveal()`\nConvert to string and reveal invisibles. @todo deal with very long strings, reveal [null] etc, ++more\n\n reveal: (value) ->\n value?.toString().replace \/^\\s+|\\s+$\/g, (match) ->\n '\\u00b7' + (new Array match.length).join '\\u00b7'\n\n\n\n\n#### `sanitize()`\nEscape a string for display, depending on the current `format` option.\n\n sanitize: (value) ->\n switch @opt.format\n when 'html'\n value?.toString().replace \/<\/g, '&lt;'\n else\n value\n\n\n\n\n#### `throw()`\nAn assertion-runner which expects `actual()` to throw an exception. \n\n throw:\n runner: (expect, actual, mock=[]) ->\n error = false\n try actual.apply @, mock catch e then error = e\n if ! error\n [ 'No exception thrown, expected', { message:expect } ]\n else if expect != error.message\n [ error.message, 'was thrown, but expected', expect ]\n\n\n\n\n#### `equal()`\nAn assertion-runner which expects `actual()` and `expect` to be equal. \n\n equal: \n runner: (expect, actual, mock=[]) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != result\n if result+'' == expect+''\n [ result, 'was returned, but expected', expect, true ]\n else\n [ result, 'was returned, but expected', expect ]\n\n\n\n\n#### `is()`\nAn assertion-runner which expects `oo.type( actual() )` and `expect` to be equal. \n\n is: \n runner: (expect, actual, mock=[]) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != oo.type result\n [ \"type #{oo.type result}\", 'was returned, but expected', \"type #{expect}\" ]\n\n\n\n\n#### `match()`\nAn assertion-runner where `expect` is a regexp, or an object containing a \n`test()` method. \n\n match: \n runner: (expect, actual, mock=[]) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if oo.F != typeof expect.test\n [ '`test()` is not a function', { message:expect } ]\n else if ! expect.test ''+result\n [ ''+result, 'failed test', expect ]\n\n\n\n\n#### `isAssertion()`\nXx. @todo\nNote brackets around `oo.O == oo.type line1`, which makes this conditional \nbehave as expected! \n\n isAssertion: (line1, line2) ->\n return false if oo.F != oo.type line2\n return false if (oo.O == oo.type line1) && oo.F == oo.type line1.runner\n true\n\n\n\n\nInstantiate the `tudor` object\n------------------------------\n\nCreate an instance of `Tudor`, to add assertions to. \n\n tudor = new Tudor\n format: if oo.O == typeof window then 'html' else 'plain'\n\n\nExpose Tudor\u2019s `do()` function as a module method, so that any consumer of \nthis module can run its assertions. In Node.js, for example: \n`require('nestag').runTest();`\n\n Nestag.runTest = tudor.do\n ;\n\n\n\n","avg_line_length":30.6035634744,"max_line_length":101,"alphanum_fraction":0.5032384834}
{"size":13703,"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 <style>\n body { font-family: sans-serif; }\n a { outline: 0; }\n b { display: inline-block; width: .7em }\n\n b.pass { color: #393 }\n b.fail { color: #bbb }\n article.fail b.pass { color: #bbb }\n section.fail b.pass { color: #bbb }\n\n pre { padding: .5em; margin: .2em 0; border-radius: 4px; }\n pre.fn { background-color: #fde }\n pre.pass { background-color: #cfc }\n pre.fail { background-color: #d8e0e8 }\n\n article { margin-bottom: .5rem }\n article h2 { padding-left:.5rem; margin:0; font-weight:normal }\n article.pass { border-left: 5px solid #9c9 }\n article.fail { border-left: 5px solid #9bf }\n article.fail h2 { margin-bottom: .5rem }\n article.pass >div { display: none }\n\n section { margin-bottom: .5rem }\n section h3 { padding-left: .5rem; margin: 0; }\n section.pass { border-left: 3px solid #9c9 }\n section.fail { border-left: 3px solid #9bf }\n section.fail h3 { margin-bottom: .5rem }\n section.pass >div { display: none }\n\n article.fail section.pass { border-left-color: #ccc }\n\n div { padding-left: .5em; }\n div.fail { border-left: 3px solid #9bf; font-size: .8rem }\n div h4 { margin: 0 }\n div h4 { font: normal .8rem\/1.2rem monaco, monospace }\n div.fail, div.fail h4 { margin: .5rem 0 }\n\n <\/style>\n <h4><a href=\"#end\" id=\"top\">\\u2b07<\/a> #{summary}<\/h4>\n \"\"\"\n @pageFoot = (summary) -> \"\"\"\n <h4><a href=\"#top\" id=\"end\">\\u2b06<\/a> #{summary}<\/h4>\n <script>\n document.title='#{summary.replace \/<\\\/?[^>]+>\/g,''}';\n <\/script>\n \"\"\"\n @articleHead = (heading, fail) ->\n \"<article class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h2>#{if fail then @cross else @tick}#{heading}<\/h2><div>\"\n @articleFoot = '<\/div><\/article>'\n @sectionHead = (heading, fail) ->\n \"<section class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h3>#{if fail then @cross else @tick}#{heading}<\/h3><div>\"\n @sectionFoot = '<\/div><\/section>'\n @jobFormat = (heading, result) ->\n \"<div class=\\\"#{if result then 'fail' else 'pass'}\\\">\" +\n \"<h4>#{if result then @cross else @tick}#{heading}<\/h4>\" + \n \"#{if result then @formatError result else ''}\" +\n \"<\/div>\"\n @tick = '<b class=\"pass\">\\u2713<\/b> ' # Unicode CHECK MARK\n @cross = '<b class=\"fail\">\\u2718<\/b> ' # Unicode HEAVY BALLOT X\n else\n @pageHead = (summary) -> \"#{summary}\"\n @pageFoot = (summary) -> \"\\n#{summary}\"\n @articleHead = (heading, fail) -> \"\"\"\n \n #{if fail then @cross else @tick} #{heading}\n ===#{new Array(heading.length).join '='}\n\n \"\"\"\n @articleFoot = ''\n @sectionHead = (heading, fail) -> \"\"\"\n\n #{if fail then @cross else @tick} #{heading}\n ---#{new Array(heading.length).join '-'}\n\n \"\"\"\n @sectionFoot = ''\n @jobFormat = (heading, result) ->\n \"#{if result then @cross else @tick} #{heading}\" +\n \"#{if result then '\\n' + @formatError result else ''}\"\n @jobFoot = ''\n @tick = '\\u2713' # Unicode CHECK MARK\n @cross = '\\u2718' # Unicode HEAVY BALLOT X\n\n\n\n\nDefine public methods\n---------------------\n\n#### `add()`\nAdd a new article to the page. An article must contain at least one section. \n\n add: (lines) ->\n\nCreate the `article` object and initialize `runner` and `section`. \n\n article = { sections:[] }\n runner = null\n section = null\n\nRun some basic validation on the `lines` array. \n\n if \u00aaA != \u00aatype lines then throw new Error \"`lines` isn\u2019t an array\"\n if 0 == lines.length then throw new Error \"`lines` has no elements\"\n if \u00aaS != \u00aatype lines[0] then throw new Error \"`lines[0]` isn\u2019t a string\"\n\nAdd the article heading. \n\n article.heading = lines.shift()\n\nStep through each line, populating the `article` object as we go. \n\n i = 0\n while i < lines.length\n line = lines[i]\n switch \u00aatype line\n\nChange the current assertion-runner. \n\n when \u00aaO\n if ! line.runner then throw new Error \"Errant object\" #@todo better error message\n runner = line.runner\n\nRecord a mock-modifier. \n\n when \u00aaF\n section.jobs.push line\n\n when \u00aaS\n\nA string might signify a new assertion in the current section... \n\n if @isAssertion lines[i+1], lines[i+2]\n if ! section then throw new Error \"Cannot add an assertion here\"\n section.jobs.push [\n runner # <function> runner Function to run the assertion\n line # <string> name A short description\n lines[++i] # <mixed> expect Defines success\n lines[++i] # <function> actual Produces the result to test\n ]\n\n...or the beginning of a new section. \n\n else\n section = {\n heading: line\n jobs: []\n }\n article.sections.push section\n\n i++\n\nAppend the article to the `articles` array.\n\n @articles.push article\n\n\n\n\n#### `do()`\nRun the test and return the result. \n\n do: =>\n\nInitialize the output array, as well as `mock` and the page pass\/fail tallies. \n\n pge = []\n mock = null\n pgePass = pgeFail = mockFail = 0\n\n for article in @articles\n art = []\n artPass = artFail = 0\n\n for section in article.sections\n sec = []\n secPass = secFail = 0\n\n for job in section.jobs\n switch \u00aatype job\n when \u00aaF # a mock-modifier\n try mock = job.apply @, mock catch e then error = e.message\n if error\n mockFail++\n secFail++ #@todo does this interfere with proper pass\/fail tally?\n sec.push @formatMockModifierError job, error\n when \u00aaA # in the form `[ runner, heading, expect, actual ]`\n [ runner, heading, expect, actual ] = job # dereference\n result = runner expect, actual, mock # run the test\n if ! result\n sec.push @jobFormat \"#{@sanitize heading}\" \n pgePass++\n artPass++\n secPass++\n else\n sec.push @jobFormat \"#{@sanitize heading}\", result\n pgeFail++\n artFail++\n secFail++\n\n sec.unshift @sectionHead \"#{@sanitize section.heading}\", secFail\n sec.push @sectionFoot\n art = art.concat sec\n\nXx. \n\n art.unshift @articleHead \"#{@sanitize article.heading}\", artFail\n art.push @articleFoot\n pge = pge.concat art\n\nGenerate a page summary message. \n\n summary = if pgeFail\n \"#{@cross} FAILED #{pgeFail}\/#{pgePass + pgeFail}\"\n else\n \"#{@tick} Passed #{pgePass}\/#{pgePass + pgeFail}\"\n if mockFail\n summary = \"\\n#{@cross} (MOCK FAILS)\"\n\nReturn the result as a string, with summary at the start and end. \n\n pge.unshift @pageHead summary\n pge.push @pageFoot summary\n pge.join '\\n'\n\n\n\n\n#### `formatError()`\nFormat an exception or fail result. `result` should be an array with two, three \nor four elements. \n\n formatError: (result) ->\n switch \"#{result.length}-#{@opt.format}\"\n\nTo format an exception, the elements are intro text and an error object. \n\n when '2-html' then \"\"\"\n #{result[0]}\n <pre class=\"fail\">#{@sanitize result[1].message}<\/pre>\n \"\"\"\n when '2-plain' then \"\"\"\n #{result[0]}\n #{@sanitize result[1].message}\n \"\"\"\n\nTo format an normal fail, the elements are 'actual', 'delivery' and 'expected'. \n\n when '3-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]}<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]}<\/pre>\n \"\"\"\n when '3-plain' then \"\"\"\n #{@sanitize @reveal result[0]}\n ...#{result[1]}...\n #{@sanitize @reveal result[2]}\n \"\"\"\n\nA fourth element (of any kind) signifies the fail is just a type-difference. \n\n when '4-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]} (#{\u00aatype result[0]})<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]} (#{\u00aatype result[2]})<\/pre>\n \"\"\"\n when '4-plain' then \"\"\"\n #{@sanitize @reveal result[0]} (#{\u00aatype result[0]})\n ...#{result[1]}...\n #{@sanitize @reveal result[2]} (#{\u00aatype result[2]})\n \"\"\"\n\nAny other number of elements is invalid. \n\n else\n throw new Error \"Cannot process '#{result.length}-#{@opt.format}'\"\n\n\n\n\n#### `formatMockModifierError()`\nFormat an exception message encountered by a mock-modifier function. \n\n formatMockModifierError: (fn, error) ->\n switch @opt.format\n when 'html' then \"\"\"\n <pre class=\"fn\">#{@sanitize fn+''}<\/pre>\n ...encountered an exception:\n <pre class=\"fail\">#{@sanitize error}<\/pre>\n \"\"\"\n else \"\"\"\n #{@sanitize fn+''}\n ...encountered an exception:\n #{@sanitize error}\n \"\"\"\n\n\n\n\n#### `reveal()`\nConvert to string and reveal invisibles. @todo deal with very long strings, reveal [null] etc, ++more\n\n reveal: (value) ->\n value?.toString().replace \/^\\s+|\\s+$\/g, (match) ->\n '\\u00b7' + (new Array match.length).join '\\u00b7'\n\n\n\n\n#### `sanitize()`\nEscape a string for display, depending on the current `format` option.\n\n sanitize: (value) ->\n switch @opt.format\n when 'html'\n value?.toString().replace \/<\/g, '&lt;'\n else\n value\n\n\n\n\n#### `throw()`\nAn assertion-runner which expects `actual()` to throw an exception. \n\n throw:\n runner: (expect, actual, mock) ->\n error = false\n try actual.apply @, mock catch e then error = e\n if ! error\n [ 'No exception thrown, expected', { message:expect } ]\n else if expect != error.message\n [ error.message, 'was thrown, but expected', expect ]\n\n\n\n\n#### `equal()`\nAn assertion-runner which expects `actual()` and `expect` to be equal. \n\n equal: \n runner: (expect, actual, mock) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != result\n if result+'' == expect+''\n [ result, 'was returned, but expected', expect, true ]\n else\n [ result, 'was returned, but expected', expect ]\n\n\n\n\n#### `is()`\nAn assertion-runner which expects `\u00aatype( actual() )` and `expect` to be equal. \n\n is: \n runner: (expect, actual, mock) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != \u00aatype result\n [ \"type #{\u00aatype result}\", 'was returned, but expected', \"type #{expect}\" ]\n\n\n\n\n#### `match()`\nAn assertion-runner where `expect` is a regexp, or an object containing a \n`test()` method. \n\n match: \n runner: (expect, actual, mock) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if \u00aaF != typeof expect.test\n [ '`test()` is not a function', { message:expect } ]\n else if ! expect.test ''+result\n [ ''+result, 'failed test', expect ]\n\n\n\n\n#### `isAssertion()`\nXx. @todo\nNote brackets around `\u00aaO == \u00aatype line1`, which makes this conditional behave \nas expected! \n\n isAssertion: (line1, line2) ->\n if \u00aaF != \u00aatype line2 then return false\n if (\u00aaO == \u00aatype line1) && \u00aaF == \u00aatype line1.runner then return false\n true\n\n\n\n\nInstantiate the `tudor` object\n------------------------------\n\nCreate an instance of `Tudor`, to add assertions to. \n\n tudor = new Tudor\n format: if \u00aaO == typeof window then 'html' else 'plain'\n\n\nExpose Tudor\u2019s `do()` function as a module method, so that any consumer of \nthis module can run its assertions. In Node.js, for example: \n`require('permasalt').runTest();`\n\n Permasalt.runTest = tudor.do\n ;\n\n\n\n","avg_line_length":30.5189309577,"max_line_length":101,"alphanum_fraction":0.504561045}
{"size":978,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# \/api\/Data Structures\/Batman.Object\/Batman.Proxy\n\n`Batman.Proxy` extends `Batman.Object` but implements the default accessor to `get`, `set`, and `unset` on its `target`.\n\nAny accessors without explicit definitions will be delegated to `target`:\n\n test \"a Batman.Proxy delegates to its target\", ->\n class CustomProxy extends Batman.Proxy\n @accessor 'customValue', -> \"Custom Value!\"\n\n targetObject = new Batman.Object({name: \"Batman\", favoriteColor: \"#000\"})\n proxy = new CustomProxy(targetObject)\n\n equal proxy.get('favoriteColor'), '#000', \"Default accessor delegates to target\"\n equal proxy.get('customValue'), \"Custom Value!\", \"Custom accessors override delegated ones\"\n\n## ::constructor(target : Batman.Object) : Proxy\n\nReturns a new `Batman.Proxy` delegating to `target`.\n\n## ::.isProxy[=true] : Boolean\n\nReturns `true`. Shows that the object is a proxy.\n\n## ::%target : Object\n\nReturns the object which the `Proxy` is delegating to.\n\n\n","avg_line_length":32.6,"max_line_length":120,"alphanum_fraction":0.7044989775}
{"size":389,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Xx. @todo intro\n\n tudor.add [\n \"09 `apage.add()` Advanced Usage\"\n\n \n\n\n \"Adding articles with non-mandatory config keys\"\n -> new Main\n\n tudor.equal\n\n \n \"`id` can be set explicitly during instantiation\"\n '{\"id\":\"apage_xyz\",\"path\":\"abc.md\",\"order\":\"abc\"}'\n (mock) -> mock.add { path:'abc.md', id:'apage_xyz' }; JSON.stringify mock.read 0\n\n ]\n\n","avg_line_length":18.5238095238,"max_line_length":86,"alphanum_fraction":0.5629820051}
{"size":386,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":286.0,"content":"# NGINX extra status codes\n\nThe NGINX web server software expands the 4xx error class to signal issues with the client's request.\n\n status = require '.'\n\nImport default status codes.\n\n for k, v of status\n continue if k is 'extra'\n module.exports[k] = v\n\nMerge default status codes with NGINX status codes.\n\n for k, v of status.extra.nginx\n module.exports[k] = v\n","avg_line_length":22.7058823529,"max_line_length":101,"alphanum_fraction":0.6943005181}
{"size":1164,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Abistract\n=========\n\nXx. \n\n\n\n\nDefine the `Abistract` class\n----------------------------\n\n class Abistract\n I: 'Abistract'\n\n\n\n\nAllow custom `toString()` renderer\n----------------------------------\n\n toString: (renderer) ->\n if renderer then renderer.call @ else \"[object #{@I}]\"\n\n\n\n\nDefine the constructor\n----------------------\n\n constructor: (opt={}) ->\n\nSet up the canvas element. \n\n opt.canvas.style.backgroundColor = opt.bgcolor\n @ctx = opt.canvas.getContext '2d'\n @ctx.lineWidth = 5\n\nSet up `shapes`, which will store all the Shape instances. \n\n @shapes = []\n\n\n\n\nDefine public methods\n---------------------\n\n#### `addLine()`\nXx. \n\n addLine: (startX, startY, endX, endY, color) ->\n\nCreate a new `Line` instance, pass it the 2D context, and set its start and \nend positions. \n\n @shapes.push new Line\n ctx: @ctx\n startX: startX\n startY: startY\n endX: endX\n endY: endY\n color: color\n\n\n\n\n#### `renderAll()`\nStep through every `Shape` in `shapes`, rendering each one. \n\n renderAll: ->\n\n shape.render() for shape in @shapes\n\n\n\n","avg_line_length":15.3157894737,"max_line_length":76,"alphanum_fraction":0.5257731959}
{"size":54,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# Static main coffeescript.\n\n $(document).ready ->\n","avg_line_length":13.5,"max_line_length":27,"alphanum_fraction":0.6481481481}
{"size":3370,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":"<p align=\"right\"><i>Laboratory<\/i> <br> Source Code and Documentation <br> API Version: <i>0.4.0<\/i> <br> <code>API\/Attachment.litcoffee<\/code><\/p>\n\n# ATTACHMENT REQUESTS #\n\n - - -\n\n## Description ##\n\nThe __Attachment__ module of the Laboratory API is comprised of those requests which are related to Mastodon media attachments.\n\n### Quick reference:\n\n#### Requests.\n\n| Request | Description |\n| :------ | :---------- |\n| `Attachment.Request()` | Requests a media attachment from the Mastodon server. |\n\n### Requesting an attachment:\n\n> ```javascript\n> request = new Laboratory.Attachment.Request(data);\n> ```\n>\n> - __API equivalent :__ `\/api\/v1\/media`\n> - __Data parameters :__\n> - __`file` :__ The file to upload\n> - __Response :__ An [`Attachment`](..\/Constructors\/Attachment.litcoffee)\n\nLaboratory Attachment requests are used to upload files to the server and receive media `Attachment`s which can then be linked to posts.\nThe only relevant parameter is `file`, which should be the `File` to upload.\n\n - - -\n\n## Examples ##\n\n### Uploading an attachment to the Mastodon server:\n\n> ```javascript\n> \/\/ Suppose `myAttachment` is a `File`.\n> var request = new Laboratory.Attachment.Request({\n> file: myAttachment\n> });\n> request.addEventListener(\"response\", requestCallback);\n> request.start();\n> ```\n\n### Using the result of an Attachment request:\n\n> ```javascript\n> function requestCallback(event) {\n> useAttachment(event.response);\n> }\n> ```\n\n - - -\n\n## Implementation ##\n\n### Making the request:\n\n Object.defineProperty Attachment, \"Request\",\n configurable: no\n enumerable: yes\n writable: no\n value: do ->\n\n AttachmentRequest = (data) ->\n\nOur first order of business is checking that we were provided a `File` and that `FormData` is supported on our platform.\nIf not, that's a `TypeError`.\n\n unless this and this instanceof AttachmentRequest\n throw new TypeError \"this is not an AttachmentRequest\"\n unless typeof File is \"function\" and (file = data.file) instanceof File\n throw new TypeError \"Unable to create attachment; none provided\"\n unless typeof FormData is \"function\"\n throw new TypeError \"Unable to create attachment; `FormData` not supported\"\n\nWe create a new `form` and add the `file` to it.\nThis will be directly uploaded to the server during the request.\n\n form = new FormData\n form.append \"file\", file\n\nHere we create the request.\n\n Request.call this, \"POST\", Store.auth.origin + \"\/api\/v1\/media\", form,\n Store.auth.accessToken, (result) =>\n dispatch \"LaboratoryAttachmentReceived\", decree =>\n @response = police -> new Attachment result\n\n Object.freeze this\n\nOur `Attachment.Request.prototype` just inherits from `Request`.\n\n Object.defineProperty AttachmentRequest, \"prototype\",\n configurable: no\n enumerable: no\n writable: no\n value: Object.freeze Object.create Request.prototype,\n constructor:\n enumerable: no\n value: AttachmentRequest\n\n return AttachmentRequest\n","avg_line_length":31.4953271028,"max_line_length":147,"alphanum_fraction":0.6204747774}
{"size":304,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":"\nRestify formatter - text\/tab-separated-values\n\n\n self = null\n\n class FormatterTab\n \n constructor: (options) ->\n self = @\n @options = options\n \n output: (req, res, body) =>\n console.log(\"tabFormat\")\n \n module.exports = FormatterTab","avg_line_length":19.0,"max_line_length":45,"alphanum_fraction":0.5230263158}
{"size":2740,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":33.0,"content":" vespaControllers = angular.module('vespaControllers') \n\n vespaControllers.controller 'modal.refpolicy', (\n $scope, $modalInstance, RefPolicy, AsyncFileReader) ->\n\n $scope.input = \n refpolicy: RefPolicy.current_as_select2()\n\n $scope.fileerrors = null\n\n $scope.uploading = \n status: false\n name: null\n\n $scope.invalid = ->\n not $scope.input.refpolicy?\n\n $scope.load = ->\n $modalInstance.close(RefPolicy.load($scope.input.refpolicy.id))\n\n $scope.cancel = ->\n $modalInstance.dismiss('cancel')\n\n $scope.upload_refpolicy = (file)->\n if file.type != 'application\/zip' and file.type != 'application\/x-zip-compressed'\n $scope.$apply ->\n $scope.fileerrors = \"Reference policy must be uploaded as a zipfile\"\n console.log($scope.fileerrors)\n\n else\n $scope.$apply ->\n $scope.uploading.status = 1\n $scope.uploading.name = file.name\n $scope.fileerrors = null\n\n AsyncFileReader.read_binary_chunks file, (chunk, start, len, total)->\n uploading = RefPolicy.upload_chunk file.name, chunk, start, len, total\n\n uploading.then(\n (status)->\n console.log status.progress\n $scope.uploading.status = status.progress * 100.0\n\n if status.progress >= 1\n $scope.uploading.status = false\n $scope.input.refpolicy = \n id: status.info._id.$oid\n text: status.info.id\n data: status.info\n ,\n (error)->\n AsyncFileReader.have_error = true\n $scope.fileerrors = error\n $scope.uploading.status = false\n $scope.uploading.name = null\n )\n\n return uploading\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 $scope.deleting = false\n\n $scope.delete = ->\n $modalInstance.close(RefPolicy.delete($scope.input.refpolicy.id))\n\n return null\n\n","avg_line_length":33.8271604938,"max_line_length":95,"alphanum_fraction":0.4627737226}
{"size":3125,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Akaybe Simple Object Utilities\n==============================\n\n#### Functions which operate on simple objects. \n\nA \u2018simple object\u2019 is defined as a standard JavaScript object created using the \n`{}` syntax, whose values are any of the following types: \n\n- `boolean`\n- `number`\n- `string`\n- `undefined`\n- `null`\n\nSince simple objects cannot contain arrays or objects, the `sou` functions are \nmuch easier to use and understand. \n\n\n\n\n#### `\u00aapopulate()`\nChecks whether a candidate\u2019s keys and values conform to a given set of rules. \nIf `candidate` breaks any rules, `\u00aapopulate()` returns an array of error \nmessages, one for each broken rule. Otherwise, it populates `subject` with new \nvalues and returns `undefined`. \n\n \u00aapopulate = (candidate, subject, rules, updating) ->\n\n if \u00aaO != \u00aatype candidate\n throw new Error \"`candidate` is type '#{\u00aatype candidate}' not 'object'\"\n\nEvery `rule` must contain four elements:\n\n- `key <string>` Specifies the key to be tested\n- `use <sotype>` `undefined` for mandatory keys, else the default value to use\n- `use <array>` Where element 0 is a function, and the rest are arguments\n- `type <string>` The expected result when `\u00aatype()` is called on the value\n- `test <object>` An object with `test()` and `toString()` methods, eg a regexp\n\nEnforce each `rule` in the `rules` array. \n\n errors = []\n for rule in rules\n\nDestructure the rule, and get the canditate\u2019s value (if present). \n\n [key,use,type,test] = rule\n value = candidate[key]\n\nDeal with a missing value. This can be safely ignored if `rule` supplies a \ndefault, or if `\u00aapopulate()` has been called in `updating` mode. @todo test `updating` mode\n\n if undefined == value\n if updating or undefined != use then continue # not an error\n else errors.push \"Missing field '#{key}' is mandatory\"\n\nMake sure that the value is of expected `type`, and passes the `test`. \n\n else if type != \u00aatype value\n errors.push \"Field '#{key}' is type '#{\u00aatype value}' not '#{type}'\"\n else if ! test.test value\n errors.push \"Field '#{key}' is '#{value}' which fails #{'' + test}\" #@todo sanitize `value`\n\nThrow an exception for an invalid `candidate`. \n\n if errors.length then throw new Error errors.join '\\n'\n\nRecord the candidate\u2019s values in the subject. \n\n for rule in rules\n [key,use,type,test] = rule\n value = candidate[key]\n\nDeal with a missing value. Otherwise record the candidate\u2019s value. @todo thoroughly test this logic\n\n if undefined == value\n if undefined == subject[key]\n if \u00aaA == \u00aatype use\n subject[key] = use[0].apply @, use.slice 1\n else\n subject[key] = use\n else\n subject[key] = value\n\nReturn `undefined`, to signify no errors were encountered. \n\n return\n\n\n\n\n#### `\u00aaclone()`\nUses an array of keys or rules (see `\u00aapopulate()` above) to clone `subject`. \n\n \u00aaclone = (subject, rules) ->\n out = {}\n for rule in rules\n key = if \u00aaS == typeof rule then rule else rule[0]\n out[key] = subject[key]\n out\n\n\n\n\n","avg_line_length":29.7619047619,"max_line_length":101,"alphanum_fraction":0.6432}
{"size":2079,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"01 ShapelyDee Constructor\n=========================\n\n tudor.add [\n \"01 ShapelyDee Constructor\"\n tudor.is\n\n\n\n\n \"The class and instance are expected types\"\n\nPrepare a test-instance. \n\n -> [new ShapelyDee]\n\n\n \"The ShapelyDee class is a function\"\n oo.F\n -> ShapelyDee\n\n\n \"`new` returns an object\"\n oo.O\n (shapelydee) -> shapelydee\n\n\n tudor.equal\n\n\n \"`ShapelyDee::C` is 'ShapelyDee'\"\n 'ShapelyDee'\n (shapelydee) -> shapelydee.C\n\n\n \"`ShapelyDee::toString()` is '[object ShapelyDee]'\"\n '[object ShapelyDee]'\n (shapelydee) -> shapelydee+''\n\n\n\n\n \"Instance properties as expected\"\n\n\n tudor.equal\n\n\n \"`ShapelyDee::x` is the number `123`\"\n 123\n (shapelydee) -> shapelydee.x\n\n\n \"`ShapelyDee::_shapes` is private, and is an array\"\n 'array'\n (shapelydee) -> oo.type shapelydee[oo._]._shapes\n\n\n \"`ShapelyDee::_shapes` is an empty array\"\n 0\n (shapelydee) -> shapelydee[oo._]._shapes.length\n\n\n \"`ShapelyDee::_pixels` is private, and is an array\"\n 'array'\n (shapelydee) -> oo.type shapelydee[oo._]._pixels\n\n\n \"`ShapelyDee::_pixels` is an empty array\"\n 0\n (shapelydee) -> shapelydee[oo._]._pixels.length\n\n\n\n\n \"config.pixelCoords usage\"\n\n\n tudor.equal\n\n\n \"`config.pixelCoords` can be passed an empty array\"\n 0\n () -> (new ShapelyDee { pixelCoords:[] } )[oo._]._pixels.length\n\n\n \"`ShapelyDee::_pixels` contains one Pixel, if pixelCoords is 3 numbers\"\n 1\n () -> (new ShapelyDee { pixelCoords:[0,1,2] } )[oo._]._pixels.length\n\n\n\n\n\"config.pixelCoords exceptions\"\n\n\ntudor.throw\n\n\n\"pixelCoords must not contain 4 numbers\"\n\"\"\"\n\/shapelydee\/src\/Pixel.litcoffee Pixel()\nconfig.y is undefined and has no fallback\"\"\"\n() -> (new ShapelyDee { pixelCoords:[1,2,3,4] } )[oo._]._pixels.length\n\n\n\"pixelCoords must not contain a boolean\"\n\"\"\"\n\/shapelydee\/src\/Pixel.litcoffee Pixel()\nconfig.z is type boolean not number\"\"\"\n() -> (new ShapelyDee { pixelCoords:[1,2,true] } )[oo._]._pixels.length\n\n\n\n\n ];\n\n\n","avg_line_length":17.4705882353,"max_line_length":77,"alphanum_fraction":0.607022607}
{"size":4339,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"# \/api\/Data Structures\/Batman.Hash\n\n`Batman.Hash` is an observable [`Batman.Object`](\/docs\/api\/batman.object.html) wrapper around `Batman.SimpleHash`. `Hash` also extends [`Batman.Enumerable`](\/docs\/api\/batman.enumerable.html), which provides [many useful methods](\/docs\/api\/batman.enumerable.html).\n\n`Batman.Hash` is a great choice when you need an iterable, observable key-value store.\n\n### Hash, SimpleHash, and Object\n\n`Hash` brings in methods from [`Batman.Object`](\/docs\/api\/batman.object.html) and `Batman.SimpleHash` and provides some new methods of its own.\nFrom `Object`, `Hash` gains:\n\n- observable properties and accessors (eg, [`::observe`](docs\/api\/batman.object.html#prototype_function_observe) and [`@accessor`](\/docs\/api\/batman.object.html#class_function_accessor))\n- observable mutation events (`itemsWereAdded`, `itemsWereChanged`, `itemsWereRemoved`)\n\nFrom `SimpleHash`, `Hash` gains:\n\n- all methods on [`Batman.Enumerable`](\/docs\/api\/batman.enumerable.html)\n- basic key-value storage, as described below\n- serialization via [`toObject`](\/docs\/api\/batman.hash.html#prototype_function_toobject) and [`toJSON`](\/docs\/api\/batman.hash.html#prototype_function_tojson) as described below\n\n`SimpleHash` methods take precedence over `Object` methods inside `Hash`. For example, `Hash::toJSON` is inherited from `SimpleHash`, not `Object`. By default, `get` and `set` affect key-value pairs in the `Hash`. You can override this by defining your own accessors.\n\n## ::constructor(obj: Object) : Hash\n\nCreates a new `Hash` with the key-value pairs in `obj`.\n\n## get, set, unset, and @accessor\n\nBy default, `get`, `set` and `unset` change values in the `Hash`'s storage. If you define your own accessors with `@accessor`, `get` and `set` for that key will be handled by the custom accessor.\n\n test 'custom accessors take precedence over Hash storage', ->\n class CustomHash extends Batman.Hash\n @accessor 'timesTwo',\n set: (key, value) -> @_customValue = value\n get: -> @_customValue * 2\n\n customHash = new CustomHash\n customHash.set('normalKey', 'value')\n customHash.set('timesTwo', 4)\n equal customHash.get('normalKey'), 'value', \"The default accessor is used\"\n equal customHash.get('timesTwo'), 8, \"The custom accessor is used\"\n equal customHash.hasKey('timesTwo'), false, \"The custom accessor doesn't use hash storage\"\n\n## ::keys() : Array\n\nReturns an array of the keys in the `Hash`.\n\n## ::isEmpty() : Boolean\n\nReturns true if the `Hash`'s length is 0.\n\n## ::toArray() : Array\n\nReturns an array of keys in the `Hash`.\n\n## ::forEach(func : Function)\n\nCalls `func(key, value)` for each pair in the `Hash`.\n\n## ::hasKey(testKey : String ) : Boolean\n\nReturns `true` if `testKey` exists on the `Hash`.\n\n## ::clear() : Array\n\nUnsets all keys, then fires an `itemsWereRemoved` event with the removed keys and values. It returns all values that were in the `Hash`.\n\n## ::merge(hashes... : Hash) : Hash\n\nCreates a __new `Hash`__ by merging pairs from `hashes` into the `Hash` and returns the merged result.\n\n## ::update(obj: Object)\n\nFor each key-value pair in `obj`, the keys in the `Hash` are updated with the provided values.\n\n- If any of the keys in `obj` were not in the `Hash` before, an `itemsWereAdded` event is fired with the new keys and new values.\n- If any of the keys in `obj` were already present in the `Hash`, an `itemsWereChanged` event is fired with the other keys, their new values (from `obj`) and their previous values.\n\n## ::replace(obj: Object)\n\nThe key-value pairs in `Hash` are completely replaced with those in `obj`.\n\n- If there were any keys in `obj` that weren't previously in the `Hash`, an `itemsWereAdded` event is fired with the new keys and their values.\n- If any keys were present in the `Hash` but weren't present in `obj` then those keys are unset on `Hash` and an `itemsWereRemoved` event is fired with the removed keys and their values.\n- If any keys were present in the `Hash` and in `obj`, then an `itemsWereChanged` event is fired with those keys, their previous values and their new values.\n\n## ::toObject() : Object\n\nReturns a plain JavaScript Object with the contents of the `Hash`.\n\n## ::toJSON() : Object\n\nReturns a plain JavaScript Object, like `toObject`, but calls `toJSON` on the each value, if it has a `toJSON` method.\n","avg_line_length":46.1595744681,"max_line_length":267,"alphanum_fraction":0.720903434}
{"size":211,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Allow users to update their own user data. This is needed to be able to remember\nwhether the user has seen the tip about drag and drop.\n\n Meteor.users.allow\n update: (userId, user) -> user._id == userId\n","avg_line_length":35.1666666667,"max_line_length":80,"alphanum_fraction":0.7203791469}
{"size":13749,"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 <style>\n body { font-family: sans-serif; }\n a { outline: 0; }\n b { display: inline-block; width: .7em }\n\n b.pass { color: #393 }\n b.fail { color: #bbb }\n article.fail b.pass { color: #bbb }\n section.fail b.pass { color: #bbb }\n\n pre { padding: .5em; margin: .2em 0; border-radius: 4px; }\n pre.fn { background-color: #fde }\n pre.pass { background-color: #cfc }\n pre.fail { background-color: #d8e0e8 }\n\n article { margin-bottom: .5rem }\n article h2 { padding-left:.5rem; margin:0; font-weight:normal }\n article.pass { border-left: 5px solid #9c9 }\n article.fail { border-left: 5px solid #9bf }\n article.fail h2 { margin-bottom: .5rem }\n article.pass >div { display: none }\n\n section { margin-bottom: .5rem }\n section h3 { padding-left: .5rem; margin: 0; }\n section.pass { border-left: 3px solid #9c9 }\n section.fail { border-left: 3px solid #9bf }\n section.fail h3 { margin-bottom: .5rem }\n section.pass >div { display: none }\n\n article.fail section.pass { border-left-color: #ccc }\n\n div { padding-left: .5em; }\n div.fail { border-left: 3px solid #9bf; font-size: .8rem }\n div h4 { margin: 0 }\n div h4 { font: normal .8rem\/1.2rem monaco, monospace }\n div.fail, div.fail h4 { margin: .5rem 0 }\n\n <\/style>\n <h4><a href=\"#end\" id=\"top\">\\u2b07<\/a> #{summary}<\/h4>\n \"\"\"\n @pageFoot = (summary) -> \"\"\"\n <h4><a href=\"#top\" id=\"end\">\\u2b06<\/a> #{summary}<\/h4>\n <script>\n document.title='#{summary.replace \/<\\\/?[^>]+>\/g,''}';\n <\/script>\n \"\"\"\n @articleHead = (heading, fail) ->\n \"<article class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h2>#{if fail then @cross else @tick}#{heading}<\/h2><div>\"\n @articleFoot = '<\/div><\/article>'\n @sectionHead = (heading, fail) ->\n \"<section class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h3>#{if fail then @cross else @tick}#{heading}<\/h3><div>\"\n @sectionFoot = '<\/div><\/section>'\n @jobFormat = (heading, result) ->\n \"<div class=\\\"#{if result then 'fail' else 'pass'}\\\">\" +\n \"<h4>#{if result then @cross else @tick}#{heading}<\/h4>\" + \n \"#{if result then @formatError result else ''}\" +\n \"<\/div>\"\n @tick = '<b class=\"pass\">\\u2713<\/b> ' # Unicode CHECK MARK\n @cross = '<b class=\"fail\">\\u2718<\/b> ' # Unicode HEAVY BALLOT X\n else\n @pageHead = (summary) -> \"#{summary}\"\n @pageFoot = (summary) -> \"\\n#{summary}\"\n @articleHead = (heading, fail) -> \"\"\"\n \n #{if fail then @cross else @tick} #{heading}\n ===#{new Array(heading.length).join '='}\n\n \"\"\"\n @articleFoot = ''\n @sectionHead = (heading, fail) -> \"\"\"\n\n #{if fail then @cross else @tick} #{heading}\n ---#{new Array(heading.length).join '-'}\n\n \"\"\"\n @sectionFoot = ''\n @jobFormat = (heading, result) ->\n \"#{if result then @cross else @tick} #{heading}\" +\n \"#{if result then '\\n' + @formatError result else ''}\"\n @jobFoot = ''\n @tick = '\\u2713' # Unicode CHECK MARK\n @cross = '\\u2718' # Unicode HEAVY BALLOT X\n\n\n\n\nDefine public methods\n---------------------\n\n#### `add()`\nAdd a new article to the page. An article must contain at least one section. \n\n add: (lines) ->\n\nCreate the `article` object and initialize `runner` and `section`. \n\n article = { sections:[] }\n runner = null\n section = null\n\nRun some basic validation on the `lines` array. \n\n if oo.A != oo.type lines then throw Error \"`lines` isn\u2019t an array\"\n if 0 == lines.length then throw Error \"`lines` has no elements\"\n if oo.S != oo.type lines[0] then throw Error \"`lines[0]` isn\u2019t a string\"\n\nAdd the article heading. \n\n article.heading = lines.shift()\n\nStep through each line, populating the `article` object as we go. \n\n i = 0\n while i < lines.length\n line = lines[i]\n switch oo.type line\n\nChange the current assertion-runner. \n\n when oo.O\n if ! line.runner then throw new Error \"Errant object\" #@todo better error message\n runner = line.runner\n\nRecord a mock-modifier. \n\n when oo.F\n section.jobs.push line\n\n when oo.S\n\nA string might signify a new assertion in the current section... \n\n if @isAssertion lines[i+1], lines[i+2]\n if ! section then throw new Error \"Cannot add an assertion here\"\n section.jobs.push [\n runner # <function> runner Function to run the assertion\n line # <string> name A short description\n lines[++i] # <mixed> expect Defines success\n lines[++i] # <function> actual Produces the result to test\n ]\n\n...or the beginning of a new section. \n\n else\n section = {\n heading: line\n jobs: []\n }\n article.sections.push section\n\n i++\n\nAppend the article to the `articles` array.\n\n @articles.push article\n\n\n\n\n#### `do()`\nRun the test and return the result. \n\n do: =>\n\nInitialize the output array, as well as `mock` and the page pass\/fail tallies. \n\n pge = []\n mock = []\n pgePass = pgeFail = mockFail = 0\n\n for article in @articles\n art = []\n artPass = artFail = 0\n\n for section in article.sections\n sec = []\n secPass = secFail = 0\n\n for job in section.jobs\n switch oo.type job\n when oo.F # a mock-modifier\n try mock = job.apply @, mock catch e then error = e.message\n if error\n mockFail++\n secFail++ #@todo does this interfere with proper pass\/fail tally?\n sec.push @formatMockModifierError job, error\n when oo.A # in the form `[ runner, heading, expect, actual ]`\n [ runner, heading, expect, actual ] = job # dereference\n result = runner expect, actual, mock # run the test\n if ! result\n sec.push @jobFormat \"#{@sanitize heading}\" \n pgePass++\n artPass++\n secPass++\n else\n sec.push @jobFormat \"#{@sanitize heading}\", result\n pgeFail++\n artFail++\n secFail++\n\n sec.unshift @sectionHead \"#{@sanitize section.heading}\", secFail\n sec.push @sectionFoot\n art = art.concat sec\n\nXx. \n\n art.unshift @articleHead \"#{@sanitize article.heading}\", artFail\n art.push @articleFoot\n pge = pge.concat art\n\nGenerate a page summary message. \n\n summary = if pgeFail\n \"#{@cross} FAILED #{pgeFail}\/#{pgePass + pgeFail}\"\n else\n \"#{@tick} Passed #{pgePass}\/#{pgePass + pgeFail}\"\n if mockFail\n summary = \"\\n#{@cross} (MOCK FAILS)\"\n\nReturn the result as a string, with summary at the start and end. \n\n pge.unshift @pageHead summary\n pge.push @pageFoot summary\n pge.join '\\n'\n\n\n\n\n#### `formatError()`\nFormat an exception or fail result. `result` should be an array with two, three \nor four elements. \n\n formatError: (result) ->\n switch \"#{result.length}-#{@opt.format}\"\n\nTo format an exception, the elements are intro text and an error object. \n\n when '2-html' then \"\"\"\n #{result[0]}\n <pre class=\"fail\">#{@sanitize result[1].message}<\/pre>\n \"\"\"\n when '2-plain' then \"\"\"\n #{result[0]}\n #{@sanitize result[1].message}\n \"\"\"\n\nTo format an normal fail, the elements are 'actual', 'delivery' and 'expected'. \n\n when '3-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]}<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]}<\/pre>\n \"\"\"\n when '3-plain' then \"\"\"\n #{@sanitize @reveal result[0]}\n ...#{result[1]}...\n #{@sanitize @reveal result[2]}\n \"\"\"\n\nA fourth element (of any kind) signifies the fail is just a type-difference. \n\n when '4-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]} (#{oo.type result[0]})<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]} (#{oo.type result[2]})<\/pre>\n \"\"\"\n when '4-plain' then \"\"\"\n #{@sanitize @reveal result[0]} (#{oo.type result[0]})\n ...#{result[1]}...\n #{@sanitize @reveal result[2]} (#{oo.type result[2]})\n \"\"\"\n\nAny other number of elements is invalid. \n\n else\n throw new Error \"Cannot process '#{result.length}-#{@opt.format}'\"\n\n\n\n\n#### `formatMockModifierError()`\nFormat an exception message encountered by a mock-modifier function. \n\n formatMockModifierError: (fn, error) ->\n switch @opt.format\n when 'html' then \"\"\"\n <pre class=\"fn\">#{@sanitize fn+''}<\/pre>\n ...encountered an exception:\n <pre class=\"fail\">#{@sanitize error}<\/pre>\n \"\"\"\n else \"\"\"\n #{@sanitize fn+''}\n ...encountered an exception:\n #{@sanitize error}\n \"\"\"\n\n\n\n\n#### `reveal()`\nConvert to string and reveal invisibles. @todo deal with very long strings, reveal [null] etc, ++more\n\n reveal: (value) ->\n value?.toString().replace \/^\\s+|\\s+$\/g, (match) ->\n '\\u00b7' + (new Array match.length).join '\\u00b7'\n\n\n\n\n#### `sanitize()`\nEscape a string for display, depending on the current `format` option.\n\n sanitize: (value) ->\n switch @opt.format\n when 'html'\n value?.toString().replace \/<\/g, '&lt;'\n else\n value\n\n\n\n\n#### `throw()`\nAn assertion-runner which expects `actual()` to throw an exception. \n\n throw:\n runner: (expect, actual, mock=[]) ->\n error = false\n try actual.apply @, mock catch e then error = e\n if ! error\n [ 'No exception thrown, expected', { message:expect } ]\n else if expect != error.message\n [ error.message, 'was thrown, but expected', expect ]\n\n\n\n\n#### `equal()`\nAn assertion-runner which expects `actual()` and `expect` to be equal. \n\n equal: \n runner: (expect, actual, mock=[]) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != result\n if result+'' == expect+''\n [ result, 'was returned, but expected', expect, true ]\n else\n [ result, 'was returned, but expected', expect ]\n\n\n\n\n#### `is()`\nAn assertion-runner which expects `oo.type( actual() )` and `expect` to be equal. \n\n is: \n runner: (expect, actual, mock=[]) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != oo.type result\n [ \"type #{oo.type result}\", 'was returned, but expected', \"type #{expect}\" ]\n\n\n\n\n#### `match()`\nAn assertion-runner where `expect` is a regexp, or an object containing a \n`test()` method. \n\n match: \n runner: (expect, actual, mock=[]) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if oo.F != typeof expect.test\n [ '`test()` is not a function', { message:expect } ]\n else if ! expect.test ''+result\n [ ''+result, 'failed test', expect ]\n\n\n\n\n#### `isAssertion()`\nXx. @todo\nNote brackets around `oo.O == oo.type line1`, which makes this conditional \nbehave as expected! \n\n isAssertion: (line1, line2) ->\n return false if oo.F != oo.type line2\n return false if (oo.O == oo.type line1) && oo.F == oo.type line1.runner\n true\n\n\n\n\nInstantiate the `tudor` object\n------------------------------\n\nCreate an instance of `Tudor`, to add assertions to. \n\n tudor = new Tudor\n format: if oo.O == typeof window then 'html' else 'plain'\n\n\nExpose Tudor\u2019s `do()` function as a module method, so that any consumer of \nthis module can run its assertions. In Node.js, for example: \n`require('lesspruino').runTest();`\n\n Lesspruino.runTest = tudor.do\n ;\n\n\n\n","avg_line_length":30.6213808463,"max_line_length":101,"alphanum_fraction":0.5035275293}
{"size":1163,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":" {coefficients, vInterpolate} = require(\".\/common\")\n \n## Connect Two Open Contour Lines\n \nThis function will take two lists of vertices and stitch them together\nin a \u2026meaningful\u2026 fa\u00e7on. The general assumption here is that both lists\nare the vertices of open polygonal contour lines and that the end of the\nfirst line needs to be somehow connected to the start of the second one.\n\n module.exports = (firstList, secondList)->\n\nWe make this *very* simplistic for now. We pick the last segment of the\nfirst list and the first segment of the second list.\n\n [prefix...,e1,e2] = firstList\n [s1,s2,suffix...] = secondList\n\nIf they are on intersecting lines, insert the intersection point.\nThis works like the 'trim-both' operation in classic 2d CAD applications.\n\n cs = coefficients([e1,e2],[s1,s2])\n\n if cs?\n p = vInterpolate(e1,e2)(cs[0])\n # would have been equivalent:\n # p = vInterpolate(s1,s2)(cs[1])\n [prefix...,e1, p, s2, suffix...]\n\nOtherwise, don't.\nJust concatenate both lists. We assume that the renderer will\ndraw a straight line between e2 and s1\n\n else\n [firstList..., secondList...]\n\n","avg_line_length":32.3055555556,"max_line_length":73,"alphanum_fraction":0.6887360275}
{"size":12377,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# Batman\n\nBatman includes a number of useful, general purpose helper functions and references. They can all be found attached to the `Batman` object and can optionally be exported into the global namespace with a `$` prefix.\n\n## container\n\n`Batman.container` points to either the `window` object if running in the browser, or the `global` object if running in node. This is useful if you want to add something to the global scope in all environments.\n\n## @typeOf(object) : string\n\n`typeOf` determines a more specific type of an `object` than the native `typeof` operator in JavaScript. This is useful for a number of situations like dealing with `Object` promoted strings and numbers, or arrays which look like `object`s to `typeof`. Use `typeOf` when you need more than `\"object\"` from `typeof`.\n\n_Note_: `typeOf` is substantially slower than `typeof`. `typeOf` works in a somewhat hackish manner by getting the `Object::toString` representation of the object and slicing it to retrieve the name of the constructor.\n\n test 'typeOf returns \"String\" for both strings and Object strings', ->\n primitive = \"test\"\n objectified = new String(\"test\")\n equal typeof primitive, \"string\"\n equal typeof objectified, \"object\"\n equal Batman.typeOf(primitive), \"String\"\n equal Batman.typeOf(objectified), \"String\"\n\n test 'typeOf returns Array for arrays', ->\n array = [];\n equal typeof array, \"object\"\n equal Batman.typeOf(array), \"Array\"\n\n## @mixin(subject, objects...) : subject\n\n`mixin`, occasionally known elsewhere as `extend` or `merge`, flattens a series of objects onto the subject. Key\/value pairs on objects passed as later arguments (arguments with a higher index) take precedence over earlier arguments. Returns the `subject` passed in with the new values.\n\n`mixin` also has special properties that make it different than the canonical `extend` functions:\n\n 1. If the `subject` has a `set` function, `subject.set(key, value)` will be used to apply keys instead of `subject[key] = value`. This means that if the subject is a `Batman.Object`, observers and thus bindings on the object will be notified when other (Batmanified or not) objects are mixed into it.\n 2. If a mixed-in `object` has an `initialize` function defined, that function will be called and passed the `subject`. This is useful for custom extension logic, similar to `self.included` in Ruby. For this reason, the keys `initialize` and `uninitialize` are skipped by `mixin`.\n 3. `mixin` only iterates over keys for which the `hasOwnProperty` test passes.\n\n_Note_: `mixin` is destructive to (only) the first argument. If you need a non-destructive version of `mixin`, just pass an empty object as the first object, and all keys from the successive arguments will be applied to the empty object.\n\n test 'mixin merges argument objects', ->\n subject = {}\n deepEqual Batman.mixin(subject, {fit: true}, {fly: true}, {funky: true}), {fit: true, fly: true, funky: true}, \"mixin returns the subject\"\n deepEqual subject, {fit: true, fly: true, funky: true}, \"the subject is modified destructively\"\n\n test 'mixin merges argument objects', ->\n unmodified = {fit: true}\n deepEqual Batman.mixin({}, unmodified, {fly: true}, {funky: true}), {fit: true, fly: true, funky: true}, \"mixin returns the subject\"\n deepEqual unmodified, {fit: true}, \"argument objects are untouched allowing non-destructive merge\"\n\n test 'mixed in objects passed as higher indexed arguments take precedence', ->\n subject = {}\n deepEqual Batman.mixin(subject, {x: 1, y: 1}, {x: 2}), {x: 2, y: 1}\n\n## @unmixin(subject, objects...) : subject\n\n`unmixin` \"unmerges\" the passed objects from the `subject`. If a key exists on any of the `objects` it will be `delete`d from the `subject`. Returns the `subject`.\n\n`unmixin`, similar to `mixin`, supports calling an `uninitialize` function for each of the `objects` being unmixed in. If an `uninitialize` function exists on each\n\n test 'unmixin removes keys found on the unmixined objects on the subject', ->\n subject = {fit: true, fly: true, funky: true}\n deepEqual Batman.unmixin(subject, {fit: true}, {fly: true}), {funky: true}, \"unmixin returns the subject\"\n deepEqual subject, {funky: true}, \"the subject is destructively modified.\"\n\n## @functionName(function) : string\n\n`functionName` returns the name of a given function, if any. Works with Internet Explorer 7\/8\/9, FireFox, Chrome, and Safari.\n\n test 'functionName returns the name of a given function', ->\n equal Batman.functionName(\"\".toString), 'toString'\n\n## @isChildOf(parent : HTMLElement, child : HTMLElement) : boolean\n\n`isChildOf` is a simple DOM helper which returns a boolean describing if the passed `child` node can be found in the descendants of the passed `parent` node.\n\n## @setImmediate(callback : Function) : object\n\n`setImmediate` (and its sister `clearImmediate`) are a more efficient version of `setTimeout(callback, 0)`. Due to timer resolution issues, setTimeout passed a timeout of 0 doesn't actually execute the function as soon as the JS execution stack has been emptied, but at minimum 4ms and maxmium 25ms after. For this reason Batman provides a cross browser implementation of `setImmediate` which does its best to call the callback immediately after the stack empties. Batman's `setImmediate` polyfill uses the native version if available, `window.postmessage` trickery if supported, and falls back on `setTimeout(->, 0)`.\n\n`setImmediate` returns a handle which can be passed to `clearImmediate` to cancel the future calling of the callback.\n\n## @clearImmediate(handle)\n\n`clearImmediate` stops the calling of a callback in the future when passed its `handle` (which is returned from the `setImmediate` call used to enqueue it).\n\n## @forEach(iterable : object, iterator : Function[, context : Object])\n\nThe `forEach` Batman helper is a universal iteration helper. When passed an `iterable` object, the helper will call the `iterator` (optionally in the `context`) for each item in the `iterable`. The `iterable` can be:\n\n 1. something which has its own `forEach`, in which case the `iterator` will just be passed to `iterable.forEach`.\n 2. an array like object, in which case a JavaScript `for(;;)` loop will be used to iterate over each entry\n 3. or an object, in which case a JavaScript `for-in` loop will be used to iterate over each entry.\n\nThe `forEach` helper is useful for iterating over objects when the type of those objects isn't guaranteed.\n\n test 'forEach iterates over objects with forEach defined', ->\n results = []\n set = new Batman.SimpleSet('a')\n Batman.forEach(set, (x) -> results.push(x))\n deepEqual results, ['a']\n\n test 'forEach iterates over array like objects', ->\n results = []\n ArrayLike = ->\n ArrayLike:: = []\n imitation = new ArrayLike\n Array::push.call(imitation, \"a\")\n Array::push.call(imitation, \"b\")\n Batman.forEach(imitation, (x) -> results.push(x))\n deepEqual results, ['a', 'b']\n\n test 'forEach iterates over objects', ->\n result = {}\n object = {x: true}\n Batman.forEach(object, (key, val) -> result[key] = val)\n deepEqual result, object\n\n## @objectHasKey(object, key) : boolean\n\n`objectHasKey` returns a boolean describing the presence of the `key` in the passed `object`. `objectHasKey` delegates to the `object`'s `hasKey` function if present, and otherwise just does a check using the JavaScript `in` operator.\n\n test 'objectHasKey verifies if a key is present in an object', ->\n subject = {fit: true}\n ok Batman.objectHasKey(subject, 'fit')\n equal Batman.objectHasKey(subject, 'flirty'), false\n\n test 'objectHasKey verifies if a key is present in an object with `hasKey` defined', ->\n subject = new Batman.SimpleHash {fit: true}\n ok Batman.objectHasKey(subject, 'fit')\n equal Batman.objectHasKey(subject, 'flirty'), false\n\n## @contains(object, item) : boolean\n\n`contains` returns a boolean describing if the given `object` has member `item`. Membership in this context is defined as:\n\n + the result of `object.has(item)` if the `object` has a `has` function defined\n + the result of `item in object` if the `object` is arraylike\n + the result of the Batman.objectHasKey otherwise\n\n_Note_: When passed an object without a `has` function, `contains` will return `true` if the `object` has `item` as a *`key`*, not as a value at any key.\n\n`contains` is useful for checking item membership when the type of the object can't be relied on.\n\n## @get(object, key) : value\n\n`get` is a general purpose function for retrieving the value from a `key` on an `object` of an indeterminate type. This is useful if code needs to work with both `Batman.Object`s and Plain Old JavaScript Objects. `get` has the following semantics:\n\n + if the `object` has a `get` function defined, return the result of `object.get(key)`\n + if the object does not have a `get` function defined, use an ephemeral `Batman.Property` to retrieve the key. This is equivalent to `object[key]` for single segment `key`s, but if the `key` is multi-segment (example: 'product.customer.name'), `get` will do nested gets until the either `undefined` or the end of the keypath is reached.\n\n test 'get returns the value at a key on a POJO', ->\n subject = {fit: true}\n equal Batman.get(subject, 'fit'), true\n equal Batman.get(subject, 'flirty'), undefined\n\n test 'get returns the value at a key on a Batman.Object', ->\n subject = Batman {fit: true}\n equal Batman.get(subject, 'fit'), true\n equal Batman.get(subject, 'flirty'), undefined\n\n test 'get returns the value at a deep key on a POJO', ->\n subject = {customer: {name: \"Joe\"}}\n equal Batman.get(subject, 'customer.name'), \"Joe\"\n equal Batman.get(subject, 'customer.age'), undefined\n\n test 'get returns the value at a deep key on a Batman.Object', ->\n subject = Batman {customer: {name: \"Joe\"}}\n equal Batman.get(subject, 'customer.name'), \"Joe\"\n equal Batman.get(subject, 'customer.age'), undefined\n\n## @getPath(base, segments) : string\n\n`getPath` returns the hash value denoted by the specified path, which consists of an array of nested hash keys. See examples below for more detail.\n\n test \"takes a base and an array of keys and returns the corresponding nested value\", ->\n @complexObject = new Batman.Object\n hash: new Batman.Hash\n foo: new Batman.Object(bar: 'nested value'),\n \"foo.bar\": 'flat value'\n equal Batman.getPath(@complexObject, ['hash', 'foo', 'bar']), 'nested value'\n equal Batman.getPath(@complexObject, ['hash', 'foo.bar']), 'flat value'\n strictEqual Batman.getPath(@complexObject, ['hash', 'not-foo', 'bar']), undefined\n\n test \"returns just the base if the key array is empty\", ->\n @complexObject = new Batman.Object\n hash: new Batman.Hash\n foo: new Batman.Object(bar: 'nested value'),\n \"foo.bar\": 'flat value'\n strictEqual Batman.getPath(@complexObject, []), @complexObject\n strictEqual Batman.getPath(null, []), null\n\n test \"returns undefined if the base is null-ish\", ->\n @complexObject = new Batman.Object\n hash: new Batman.Hash\n foo: new Batman.Object(bar: 'nested value'),\n \"foo.bar\": 'flat value'\n strictEqual Batman.getPath(null, ['foo']), undefined\n strictEqual Batman.getPath(undefined, ['foo']), undefined\n\n test \"returns falsy values\", ->\n @complexObject = new Batman.Object\n hash: new Batman.Hash\n foo: new Batman.Object(bar: 'nested value'),\n \"foo.bar\": 'flat value'\n strictEqual Batman.getPath(num: 0, ['num']), 0\n strictEqual Batman.getPath(thing: null, ['thing']), null\n\n## @escapeHTML(input) : string\n\n`escapeHTML` takes a string of unknown origin and makes it safe for display on a web page by encoding control characters in HTML into their HTML entities.\n\n*Warning*: Do not rely on `escapeHTML` to purge unsafe data from user submitted content. While `escapeHTML` is applied to every binding's contents by default, it should not be your only line of defence against script injection attacks.\n\n test 'escapeHTML encodes special characters into HTML entities', ->\n equal Batman.escapeHTML(\"& < > \\\" '\"), \"&amp; &lt; &gt; &#34; &#39;\"\n","avg_line_length":57.3009259259,"max_line_length":618,"alphanum_fraction":0.7068756565}
{"size":3195,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":11.0,"content":"# Bjorklund\n\nThis is an implementation of the algorithm described by Bjorklund, that's been adapted for generating \"Euclidean Rhythms\". This implementation follows the steps described in [\"Structural properties of Euclidean rhythms\"](http:\/\/student.ulb.ac.be\/~ptaslaki\/publications\/structuralProperties.pdf), quotes from that paper appear inline illustrating how the instructions for implementing the algorithm are followed.\n\n> **Bjorklund\u2019s algorithm.** Bjorklund\u2019s algorithm consists of two steps: an initialization step, performed once at the beginning; and a subtraction step, performed repeatedly until the stopping condition is satisfied. At all times Bjorklund\u2019s algorithm maintains two lists `A` and `B` of strings of bits, with `a` and `b` representing the number of strings in each list, respectively.\n\n\t# `k` is pulses, `n` is steps\n bjorklund = (n, k) ->\n\n> **Initialization step.** In this step the algorithm builds the string `{1,..k..,1,0,..n..,0}`, and sets `A` as the first `a = min{k,n\u2212k}` bits of that string, and `B` as the remaining `b = max{k, n \u2212 k} bits`.\n\n A = []\n B = []\n for i in [0...k]\n if i < n then A.push([1]) else B.push([0])\n\n a = A.length\n b = B.length\n\n> Next the algorithm removes `b\/a` strings of a consecutive bits from `B`, starting with the rightmost bit, and places them under the `a`-bit strings in `A` one below the other. Lists `A` and `B` are then redefined: `A` is now composed of `a` strings (the `a` columns in `A`), each having `b\/a + 1` bits, and `B` is composed of `b mod a` strings of `0`-bits. Finally, the algorithm sets `b = b mod a`.\n\n count = Math.floor(b \/ a)\n for i in [0...A.length]\n removed = B.splice(B.length - count, count)\n for value, j in removed\n A[i] = A[i].concat(value)\n\n return [].concat.apply([], A) if B.length == 0 # Return early to prevent dividing by zero later\n\n> **Subtraction step.** At a subtraction step, the algorithm removes `a\/b` strings of `b` consecutive bits (or columns) from `B` and `A`, starting with the rightmost bit of `B` and continuing with the rightmost bit of `A`, and places them at the bottom-left of the strings in `A` one below the other.\n\n loop\n a = A.length\n b = B.length\n stringsToRemove = Math.floor(a \/ b)\n\n joined = A.concat(B)\n for i in [0...stringsToRemove]\n removed = joined.splice(joined.length - b, b)\n for value, j in removed\n joined[j] = joined[j].concat(value)\n\n> Lists `A` and `B` are then redefined as follows: `A` is composed of the first `b` strings (starting with the leftmost bit), while `B` is composed of the remaining `a mod b` strings. Finally, the algorithm sets `b = a mod b` and `a = b` (before `b` was redefined).\n\n b = B.length\n A = joined.splice(0, b)\n B = joined\n\n> The algorithm stops when, after the end of a subtraction step, list `B` is empty or consists of one string. The output then is produced by concatenating the strings of `A` from left to right and the strings of `B`, if not empty.\n\n break unless B.length > 1\n\n joined = A.concat(B)\n return [].concat.apply([], joined)\n","avg_line_length":58.0909090909,"max_line_length":411,"alphanum_fraction":0.6663536776}
{"size":11266,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":"Overview\n--------\n\nThis module wraps all interation with Firebase. It provides a nice dsl to execute operations\nagainst a Firebase datastore. It does make some assumptions - like that when you `add` something\nyou also want to keep track of the `count` for the list of items you just added to.\n\nInitialization\n--------------\n\nPull in our requires and setup our Firebase connection.\n\n__NOTE__ _a FIREBASE_ROOT must be specified. An example would be \"https:\/\/reallycool.firebaseio.com\"_\n\n Firebase = require 'firebase'\n firebase = new Firebase process.env.FIREBASE_ROOT\n q = require 'q'\n async = require 'async'\n \nThis will only execute once - when the module is first loaded. It's only called if a `FIREBASE_KEY`\nis provided. Otherwise `pyro` assumes you don't need to be authed.\n\n if process.env.FIREBASE_KEY?\n firebase.authWithCustomToken process.env.FIREBASE_KEY, () -> console.log 'AUTHED'\n\nHelper to provide easy access to the last element of an array.\n\n Array::last = -> @[@length - 1]\n\nsanitize\n--------\n\nFirebase does not support several characters in the url location. This method scrubs such characters.\n\n sanitize = (location) -> location.replace \/\\.|#|\\$|\\[|\\]\/g, ''\n\nget\n---\n\nGet the value for the specified location from Firebase.\n\n get = (location) ->\n deferred = q.defer()\n\n firebase\n .child sanitize location\n .once 'value', (snapshot) -> deferred.resolve snapshot.val()\n\n deferred.promise\n\nfetch\n-----\n\nGet the value for the specified location from Firebase.\n\n fetch = (path, end) ->\n deferred = q.defer()\n fetched = 0\n limit = 0\n items = [ ]\n\n callback = (snapshot) ->\n item =\n name: snapshot.key()\n value: snapshot.val()\n priority: snapshot.getPriority()\n\n items.push item\n\n deferred.notify item\n \n if ++fetched == limit\n deferred.resolve items\n firebase\n .child sanitize path\n .off 'child_added', callback\n\n count path, end\n .then (cnt) ->\n limit = cnt\n\n firebase\n .child sanitize path\n .on 'child_added', callback\n\n deferred.promise\n\nset\n---\n\n`set` takes a location as a simple string. It does not check to see if a value exists before setting\nand overrites any existing value. This is especially important because the entire node graph\nbeneath the node being written is replaced - meaning `foo`, `bar`, and `baz` would be overwritten\nby setting `foo`. If the new `foo` value does not contain `bar` or `baz` they will just go away. \n\n`set` also specifies a priotity for the data's node. The priority is the time the node gets\nadded. This allows the node to be sorted and used in `startAt` and `endAt` Firebase queries.\n\n set = (location, value, p) ->\n deferred = q.defer()\n loc = sanitize location\n\n firebase\n .child loc\n .setWithPriority value, p || Date.now(), (err) ->\n if err? \n deferred.reject err\n else\n deferred.resolve true\n\n deferred.promise\n\nbiggest\n-------\n\n biggest = (path, options) -> execute_query 'Last', path, options\n\nsmallest\n--------\n\n smallest = (path, options) -> execute_query 'First', path, options\n\nto\n--\n\n to = (path, end, limit) ->\n deferred = q.defer()\n invokes = 0\n out = [ ]\n\n callback = (snapshot) ->\n out.push name: snapshot.key(), value: snapshot.val(), index: invokes\n\n if ++invokes == limit\n firebase\n .child sanitize path\n .off 'child_added', callback\n\n deferred.resolve out\n\n firebase\n .child sanitize path\n .orderByPriority()\n .endAt end\n .limitToFirst limit\n .on 'child_added', callback\n\n deferred.promise\n\ncount\n-----\n \n count = (path, end) ->\n deferred = q.defer()\n\n firebase\n .child sanitize path\n .orderByPriority()\n .endAt end\n .once 'value', (snapshot) ->\n deferred.resolve snapshot.numChildren()\n\n deferred.promise\n\ncounts\n-----\n \n counts = (paths...) ->\n deferred = q.defer()\n out = { }\n\n async.eachSeries paths, (path, next) ->\n firebase\n .child sanitize path\n .once 'value', (snapshot) ->\n out[path] = snapshot.numChildren()\n next()\n , -> deferred.resolve out\n\n deferred.promise\n\nexists\n------\n\n exists = (path, child) ->\n deferred = q.defer()\n\n firebase\n .child sanitize path\n .once 'value', (snapshot) ->\n deferred.resolve snapshot.hasChild sanitize child\n\n deferred.promise\n\nexist\n------\n\n exist = (things) ->\n deferred = q.defer()\n keys = Object.keys things\n results = { }\n responses = 0\n\n keys.forEach (key) ->\n firebase\n .child sanitize key\n .once 'value', (snapshot) ->\n results[key] = snapshot.hasChild sanitize things[key]\n\n deferred.resolve results if ++responses == keys.length\n\n deferred.promise\n\nadd_value\n---------\n\n1. Add the passed value to the location specified\n2. Increment the list count\n\n`add` only sets the specified value at the passed location if the node does not already exist. If \nthe specified location does exist nothing is done.\n\n add_value = (location, value, p) ->\n deferred = q.defer()\n\n get location\n .then (val) ->\n if val?\n deferred.resolve false\n else\n set location, value, p\n .then ( ) -> deferred.resolve true\n .fail (err) -> deferred.reject err\n\n deferred.promise\n\nadd_leaf\n--------\n\n add_leaf = (location, value, p) ->\n deferred = q.defer()\n\n get \"#{location}\/#{value}\"\n .then (val) ->\n if val?\n deferred.resolve false\n else\n set \"#{location}\/#{value}\", Date.now(), p\n .then ( ) -> deferred.resolve true\n .fail (err) -> deferred.reject err\n\n deferred.promise\n\npush\n----\n\n push = (location, value) ->\n deferred = q.defer()\n\n firebase\n .child location\n .push value, (err) ->\n if err?\n deferred.reject err\n else\n deferred.resolve true\n\n deferred.promise\n\nfind\n----\n\n find = (path, options) ->\n deferred = q.defer()\n key = Object.keys(options)[0]\n\n firebase\n .child sanitize path\n .orderByChild key\n .startAt options[key]\n .on 'child_added', (snapshot) ->\n deferred.notify \n name: snapshot.key()\n value: snapshot.val()\n\n deferred.promise\n\ntouch\n-----\n\nUpdate a location's priority.\n\n touch = (location, p) ->\n deferred = q.defer()\n loc = sanitize location\n\n firebase\n .child loc\n .setPriority p || priority(loc), (err) ->\n if err?\n deferred.reject err\n else\n deferred.resolve true\n\n deferred.promise\n\nincrement_count\n---------------\n\n`increment_count` increments the `count` property for the specified location.\n\nIt first gets the current count (initializing it to `0` if it doesn't exist) and then \nupdates the count, incrementing it by one.\n\n`increment_count` also sets a priority for the count using the `priority` method.\n\n increment_count = (location) ->\n deferred = q.defer()\n loc = sanitize location\n count = \"#{loc}\/_count_\"\n\n firebase\n .child count\n .once 'value', (snapshot) ->\n val = snapshot.val() || 0\n\n firebase\n .child count\n .setWithPriority ++val, priority(loc, val), (err) ->\n if err?\n deferred.reject context: 'pyro\/increment_count', error: err\n else\n deferred.resolve()\n\n deferred.promise\n\npriority\n--------\n\nThe function used to set a location's priority.\n\n priority = (location, value) -> Date.now()\n\nwatch\n-----\n\n watch = (path, event) ->\n deferred = q.defer()\n\n firebase\n .child sanitize path\n .on \"child_#{event}\", (snap) -> deferred.notify name: snap.key(), value: snap.val()\n\n deferred.promise\n\nunwatch\n-------\n\n unwatch = (path, event, listener) ->\n firebase\n .child sanitize path\n .off \"child_#{event}\", listener\n\nmonitor\n-------\n\n monitor = (path) ->\n deferred = q.defer()\n\n firebase\n .child sanitize path\n .once 'value', (snapshot) ->\n deferred.notify \n event: 'added'\n value:\n name: snapshot.key()\n value: snapshot.val()\n priority: snapshot.getPriority()\n \n firebase\n .child sanitize path\n .on 'child_changed', (snapshot) ->\n deferred.notify \n event: 'updated'\n value:\n name: snapshot.key()\n value: snapshot.val()\n priority: snapshot.getPriority()\n\n deferred.promise\n\nunmonitor\n---------\n\n unmonitor = (path) ->\n firebase\n .child sanitize path\n .off 'child_changed'\n\nobserve\n-------\n\n observe = (path, event) ->\n deferred = q.defer()\n\n firebase\n .child sanitize path\n .on \"child_#{event}ed\", (snapshot) ->\n deferred.notify\n name: snapshot.key()\n value: snapshot.val()\n priority: snapshot.getPriority()\n\n deferred.promise\n\nremove\n------\n\n remove = (path) ->\n deferred = q.defer()\n\n firebase\n .child sanitize path\n .remove -> deferred.resolve()\n\n deferred.promise\n\nexecute_query\n-------------\n\n execute_query = (mode, path, options) ->\n deferred = q.defer()\n\n query = firebase.child sanitize path\n\n if options.startAt?\n query.startAt options.startAt\n \n if options.key?\n query.orderByChild options.key\n else\n query.orderByPriority()\n\n if options.limit?\n query[\"limitTo#{mode}\"] parseInt options.limit, 10\n\n \n query.once 'value', (snapshot) ->\n out = [ ]\n \n snapshot.forEach (snap) ->\n out.push\n name: snap.key()\n value: snap.val()\n priority: snap.getPriority()\n\n false\n\n deferred.resolve if options.order == 'desc' then out.reverse() else out\n\n deferred.promise\n\n\nPublic interface\n----------------\n\n module.exports = \n to: to\n get: get\n set: set\n push: push\n find: find\n watch: watch\n fetch: fetch\n touch: touch\n count: count\n exist: exist\n counts: counts\n exists: exists\n remove: remove\n unwatch: unwatch\n monitor: monitor\n observe: observe\n biggest: biggest\n smallest: smallest\n priority: priority\n add_leaf: add_leaf\n unmonitor: unmonitor\n add_value: add_value\n increment_count: increment_count","avg_line_length":22.9918367347,"max_line_length":101,"alphanum_fraction":0.5549440795}
{"size":9998,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":" ###!\n jQuery.TextFade v1.0.0\n https:\/\/github.com\/mdesantis\/jquery-textfade\n\n Copyright 2014-2018 Maurizio De Santis\n Released under the MIT license\n https:\/\/github.com\/mdesantis\/jquery-textfade\/LICENSE\n ###\n\n# jQuery.TextFade\n\n## Description\n\n**jQuery.TextFade** is a jQuery plugin which provides some nice fading effects to the contents of\nthe selected elements.\n\nThe fading effect is obtained replacing every character of the text with a blank character in the\ncase of a fade-out effect, and conversely replacing the text with blank characters and replacing\nevery blank character with the corresponding character in the text in the case of a fade-in effect.\n\nIf more elements are selected, their contents will be animated simultaneously.\n\n## API\n\n* **jQuery.textFade(action, options)**: main function\n* **jQuery.textFadeIn(options)**: alias for `jQuery.textFade('in', options)`\n* **jQuery.textFadeOut(options)**: alias for `jQuery.textFade('out', options)`\n\n### Arguments\n\n**jQuery.textFade** takes two arguments:\n- **action**: the fading action; can be `'in'`, which causes the text to appear, or `'out'`, which\n causes the text to disappear. *Default value:* none\n- **options**: the available options, which are:\n - **text**: if this option is specified, its value will replace the content of the selected\n element, so as to be used for the fading effect; otherwise the fading text is the content of the\n selected element. *Default value:* `null`\n - **sequence**: an array of characters indexes, which determine the order of the text fading.\n *Default value:* `'random'`. The value can be any of these types:\n - *array*: it will be iterated in sequence using each value as the index of the character to be\n replaced\n - *string*: it selects one between the preset sequences (more on this [below](#sequences))\n - *function*: it takes the fading text as argument and returns an array containing the\n characters indexes\n - **steps**: a step is the action of the character replacement. These are the available\n options:\n - **duration**: the duration of each character replacement in milliseconds. *Default value:\n `10`*\n - **threads**: the amount of character replacements for each step. *Default value:* `1`\n\n**jQuery.textFadeIn** and **jQuery.textFadeOut** take the **options** argument only.\n\n\n### Events\n\njQuery.textFade triggers two events, **start** and **stop**. In order to listen for them you can use\nthe following event identifiers:\n- **start.textFadeIn**: start of a fade-in\n- **stop.textFadeIn**: stop of a fade-in\n- **start.textFadeOut**: start of a fade-out\n- **stop.textFadeOut**: stop of a fade-out\n- **start.textFade**: start of a fade of any action\n- **stop.textFade**: stop of a fade of any action\n\nIn any case the action is passed as value of the `'action'` key of the first extra parameter, which\nhappens to be an object.\n\n### Examples\n\n- Fade out the text `HEY THERE!` one character every second:\n\n```coffeescript\n$('#text').textFadeIn({\n 'text': 'HEY THERE!',\n 'steps': { 'duration': 1000, 'threads': 1 }\n})\n```\n\n- Fade out the text `SEE YA!` three characters every two seconds, in a\n*left to right - top to bottom* order:\n\n```coffeescript\n$('#text').textFadeOut({\n 'text': 'SEE YA!',\n 'sequence': 'ltr_ttb',\n 'steps': { 'duration': 2000, threads: 3 }\n})\n```\n\n## Source\n\n**TextFade** is the core function: in addition to the arguments described [above](#arguments), it\ntakes the `@$element` argument, that is the jQuery element\/s whose text is going to be animated\n\n TextFade = (@$element, @action, options) ->\n\n### Constants\n\n $ = jQuery\n BLANK_TEXT_REGEXP = \/[^\\n]\/g\n LINES_SPLIT_REGEXP = \/.+\\n?|\\n\/g\n\n#### Sequences\n\n SEQUENCES =\n\n`SEQUENCES` includes some preset sequences, selectable passing the corresponding identifier to\njQuery.textFade. The available identifiers are:\n\n- **random**: the characters fading sequence is random\n\n 'random' : (text) -> shuffle times text.length\n\n- **ltr_ttb** *(left-to-right character, top-to-bottom line)*: the text fading starts at the first\ncharacter of the first line, up to the end of line; then it moves to the next line\n\n 'ltr_ttb' : (text) -> times text.length\n\n- **ltr_btt** *(left-to-right character, bottom-to-top line)*: the text fading starts at the first\ncharacter of the last line, up to the end of line; then it moves to the previous line\n\n 'ltr_btt' : (text) -> flatten (textToSequences text).reverse()\n\n- **rtl_ttb** *(right-to-left character, top-to-bottom line)*: the text fading starts at the last\ncharacter of the first line, up to the start of line; then it moves to the next line\n\n 'rtl_ttb' : (text) -> flatten textToSequences(text).map((v) -> v.reverse())\n\n- **rtl_btt** *(right-to-left character, bottom-to-top line)*: the text fading starts at the last\ncharacter of the last line, up to the start of line; then it moves to the previous line\n\n 'rtl_btt' : (text) -> flatten textToSequences(text).map((v) -> v.reverse()).reverse()\n\n- **ttb_ltr** *(top-to-bottom character, left-to-right line)*: the text fading starts at the first\ncharacter of the first line, up to the first character of the last line; then it moves to the next\ncharacter of the first line\n\n 'ttb_ltr' : (text) -> flatten zip textToSequences text\n\n- **ttb_rtl** *(top-to-bottom character, right-to-left line)*: the text fading starts at the last\ncharacter of the first line, up to the last character of the last line; then it moves to the\nprevious character of the first line\n\n 'ttb_rtl' : (text) -> flatten (zip textToSequences(text).reverse()).reverse()\n\n- **btt_ltr** *(bottom-to-top character, left-to-right line)*: the text fading starts at the first\ncharacter of the last line, up to the first character of the first line; then it moves to the next\ncharacter of the last line\n\n 'btt_ltr' : (text) -> flatten zip textToSequences(text).reverse()\n\n- **btt_rtl** *(bottom-to-top character, right-to-left line)*: the text fading starts at the last\ncharacter of the last line, up to the first character of the last line; then it moves to the next\ncharacter of the last line\n\n 'btt_rtl' : (text) -> flatten (zip textToSequences text).reverse()\n\n### Utility functions\n\n capitalize = (s) -> \"#{s.charAt(0).toUpperCase()}#{s.slice(1)}\"\n\n flatten = (a) -> a.reduce (p, c) -> p.concat c\n\n max = (a) -> a.reduce ((p, c) -> Math.max p, c), -Infinity\n\n shuffle = (a) ->\n i = a.length\n\n while i\n j = Math.floor Math.random()*i\n x = a[--i]\n a[i] = a[j]\n a[j] = x\n\n a\n\n times = (n, fn) ->\n i = 0\n fn ?= (i) -> i\n\n fn i++ while i < n\n\n zip = (a) ->\n result = []\n\n times (max a.map (v) -> v.length), (i) ->\n for v in a\n (result[i] ?= []).push v[i] if v[i]?\n\n result\n\nTake a text and return an array of arrays, each containing the text index of each\ncharacter of the corresponding line\n\n textToSequences = (text) ->\n sequences = []\n charIndex = 0\n lines = text.match LINES_SPLIT_REGEXP\n\n for line, lineIndex in lines\n sequences[lineIndex] = []\n times line.length, () -> sequences[lineIndex].push charIndex++\n\n sequences\n\n### Default options\n\n defaultOptions = ->\n 'text' : null\n 'sequence' : 'random'\n 'steps' :\n 'duration' : 10\n 'threads' : 1\n\n### Private instance methods\n\nTrigger both of the supported event namespaces\n\n @_trigger = (eventName) ->\n extraParameters = [{ 'action' : @action }]\n @$element.trigger \"#{eventName}.textFade#{capitalize(@action)}\", extraParameters\n @$element.trigger \"#{eventName}.textFade\", extraParameters\n\nReplace the character at the given index\n\n @_replace = (index) ->\n text = @$element.text()\n prevChar = @begText.charAt index\n nextChar = @endText.charAt index\n\nThe replacement is skipped if the character is the same\n\n return if prevChar is nextChar\n\n @$element.text \"#{text.substr 0, index}#{nextChar}#{text.substr index+nextChar.length}\"\n\nThe function executed for each character replacement, until the sequence gets empty\n\n @_step = (sequence) ->\n times @options.steps.threads, () =>\n return if sequence.length is 0\n\n @_replace sequence.shift()\n\n if sequence.length is 0\n clearInterval @_interval\n @_trigger 'stop'\n\n### Constructor\n\n @options = $.extend true, defaultOptions(), options\n\n text = @options.text ? @$element.text()\n\n if $.type(@options.sequence) is 'string'\n @options.sequence = SEQUENCES[@options.sequence] text\n else if $.isFunction @options.sequence\n @options.sequence = @options.sequence text\n # else assert @options.sequence to be an array; leave it unchanged\n\nUse an `@options.sequence` clone in order to keep it unchanged\n\n sequenceClone = @options.sequence[0..]\n\nNewlines are preserved in order to preserve the text structure\n\n blankText = text.replace BLANK_TEXT_REGEXP, ' '\n\nThe only difference between fade-in and fade-out is that on fade-in we start with a blank text and\nfinish with the submitted text, while on fade-out we start with the submitted text and finish with\na blank text\n\n switch @action\n when 'in'\n @begText = blankText\n @endText = text\n when 'out'\n @begText = text\n @endText = blankText\n\n @$element.text @begText\n\n @_trigger 'start'\n\n @_interval = setInterval =>\n @_step sequenceClone\n , @options.steps.duration\n\n @\n\n### jQuery bindings\n\n $.fn.textFade = (action, options) ->\n @.each -> new TextFade $(@), action, options\n\n $.fn.textFadeIn = (options) ->\n @.textFade 'in', options\n\n $.fn.textFadeOut = (options) ->\n @.textFade 'out', options\n","avg_line_length":33.2159468439,"max_line_length":100,"alphanum_fraction":0.6574314863}
{"size":5528,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":33.0,"content":" vespaControllers = angular.module('vespaControllers')\n\n vespaControllers.controller 'module_browserCtrl', ($scope, VespaLogger,\n IDEBackend, $timeout, $modal, PositionManager, $q, SockJSService) ->\n\n barHeight = 20\n barWidth = 300\n duration = 400\n root = {}\n svg = d3.select(\"svg.module_browserview\").select(\"g.viewer\")\n tree = d3.layout.tree()\n .nodeSize([0, 20])\n\n $scope.controls =\n showModuleSelect: true\n collapse: 'collapse-all'\n\n collapseAll = (node) ->\n if node.children\n node._children = node.children\n node.children = null\n node._children.forEach collapseAll\n if Array.isArray node._children\n node._children.forEach collapseAll\n\n openAll = (node) ->\n if node._children\n node.children = node._children\n node._children = null\n node.children.forEach openAll\n if Array.isArray node.children\n node.children.forEach openAll\n\n $scope.collapse = (value) ->\n if value == 'collapse-all'\n collapseAll(root)\n else if value == 'open-all'\n openAll(root)\n if value and root.name\n update(root)\n\n $scope.update_view = () ->\n $scope.policy = IDEBackend.current_policy\n\n if not $scope.policy?.modules?\n return\n\n modules_root = \n name: (if $scope.policy?.id? then $scope.policy.id else \"\")\n children: []\n\n # Group the rules by directory and module\n for key, mod of $scope.policy.modules\n if not mod.te_file\n return\n \n path = mod.te_file.split('\/')\n modDirectory = path[path.length - 2]\n directory = _.find(modules_root.children, {directory: modDirectory})\n if directory\n module = _.find(directory.children, {module: mod.name})\n if module\n #module.children.push d\n else\n directory.children.push {name: mod.name, module: mod.name}\n else\n child = {name: mod.name, module: mod.name}\n modules_root.children.push {name: modDirectory, directory: modDirectory, children: [child]}\n\n modules_root.x0 = 0\n modules_root.y0 = 0\n\n update(root = modules_root)\n\n update = (modules_root) ->\n nodes = tree.nodes(root)\n _.each nodes, (d,i) ->\n d.x = i * barHeight\n\n height = 500\n\n d3.select(\"svg.module_browserview\").transition()\n .duration(duration)\n .attr(\"height\", height)\n\n node = svg.selectAll(\"g.node\")\n .data(nodes, (d,i) -> return d.id or (d.id = $scope.policy.id + \"-\" + i))\n\n nodeEnter = node.enter().append(\"g\")\n .attr(\"class\", \"node\")\n .attr(\"transform\", (d) -> return \"translate(#{modules_root.y0},#{modules_root.x0})\")\n .style(\"opacity\", 1e-6)\n\n nodeEnter.append(\"rect\")\n .attr(\"y\", -barHeight\/2)\n .attr(\"height\", barHeight)\n .attr(\"width\", barWidth)\n .style(\"fill\", color)\n .on(\"click\", click)\n\n nodeEnter.append(\"text\")\n .attr(\"dy\", 3.5)\n .attr(\"dx\", 5.5)\n .style(\"fill\", '#333')\n .text((d) -> if d.children? then \"#{d.name} (#{d.children.length})\" else if d._children? then \"#{d.name} (#{d._children.length})\" else d.name)\n\n nodeEnter.transition()\n .duration(duration)\n .attr(\"transform\", (d) -> \"translate(#{d.y},#{d.x})\")\n .style(\"opacity\", 1)\n\n node.transition()\n .duration(duration)\n .attr(\"transform\", (d) -> \"translate(#{d.y},#{d.x})\")\n .style(\"opacity\", 1)\n .select(\"rect\")\n .style(\"fill\", color)\n\n node.exit().transition()\n .duration(duration)\n .attr(\"transform\", (d) -> \"translate(#{modules_root.y},#{modules_root.x})\")\n .style(\"opacity\", 1e-6)\n .remove()\n\n _.each nodes, (d) ->\n d.x0 = d.x\n d.y0 = d.y\n\n click = (d) ->\n if d.children\n d._children = d.children\n d.children = null\n else\n d.children = d._children\n d._children = null\n update(d)\n\n color = (d) ->\n if d._children\n return '#3182bd'\n else if d.children\n return '#c6dbef'\n else\n return '#fd8d3c'\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'\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\")[0])\n svgPanZoom.set_transform(g, newv)\n )\n\n IDEBackend.add_hook \"policy_load\", $scope.update_view\n $scope.$on \"$destroy\", ->\n IDEBackend.unhook \"policy_load\", $scope.update_view\n\n $scope.policy = IDEBackend.current_policy\n\n # If policy already loaded, render it\n if $scope.policy?._id\n $scope.update_view()","avg_line_length":30.3736263736,"max_line_length":152,"alphanum_fraction":0.5435962373}
{"size":13697,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Docco\n=====\n\n**Docco** is a quick-and-dirty documentation generator, written in\n[Literate CoffeeScript](http:\/\/coffeescript.org\/#literate).\nIt produces an HTML document that displays your comments intermingled with your\ncode. All prose is passed through\n[Markdown](http:\/\/daringfireball.net\/projects\/markdown\/syntax), and code is\npassed through [Highlight.js](http:\/\/highlightjs.org\/) syntax highlighting.\nThis page is the result of running Docco against its own\n[source file](https:\/\/github.com\/jashkenas\/docco\/blob\/master\/docco.litcoffee).\n\n1. Install Docco with **npm**: `sudo npm install -g docco`\n\n2. Run it against your code: `docco src\/*.coffee`\n\nThere is no \"Step 3\". This will generate an HTML page for each of the named\nsource files, with a menu linking to the other pages, saving the whole mess\ninto a `docs` folder (configurable).\n\nThe [Docco source](http:\/\/github.com\/jashkenas\/docco) is available on GitHub,\nand is released under the [MIT license](http:\/\/opensource.org\/licenses\/MIT).\n\nDocco can be used to process code written in any programming language. If it\ndoesn't handle your favorite yet, feel free to\n[add it to the list](https:\/\/github.com\/jashkenas\/docco\/blob\/master\/resources\/languages.json).\nFinally, the [\"literate\" style](http:\/\/coffeescript.org\/#literate) of *any*\nlanguage is also supported \u2014 just tack an `.md` extension on the end:\n`.coffee.md`, `.py.md`, and so on.\n\n\nPartners in Crime:\n------------------\n\n* If Node.js doesn't run on your platform, or you'd prefer a more\nconvenient package, get [Ryan Tomayko](http:\/\/github.com\/rtomayko)'s\n[Rocco](http:\/\/rtomayko.github.io\/rocco\/rocco.html), the **Ruby** port that's\navailable as a gem.\n\n* If you're writing shell scripts, try\n[Shocco](http:\/\/rtomayko.github.io\/shocco\/), a port for the **POSIX shell**,\nalso by Mr. Tomayko.\n\n* If **Python** is more your speed, take a look at\n[Nick Fitzgerald](http:\/\/github.com\/fitzgen)'s [Pycco](http:\/\/fitzgen.github.io\/pycco\/).\n\n* For **Clojure** fans, [Fogus](http:\/\/blog.fogus.me\/)'s\n[Marginalia](http:\/\/fogus.me\/fun\/marginalia\/) is a bit of a departure from\n\"quick-and-dirty\", but it'll get the job done.\n\n* There's a **Go** port called [Gocco](http:\/\/nikhilm.github.io\/gocco\/),\nwritten by [Nikhil Marathe](https:\/\/github.com\/nikhilm).\n\n* For all you **PHP** buffs out there, Fredi Bach's\n[sourceMakeup](http:\/\/jquery-jkit.com\/sourcemakeup\/) (we'll let the faux pas\nwith respect to our naming scheme slide), should do the trick nicely.\n\n* **Lua** enthusiasts can get their fix with\n[Robert Gieseke](https:\/\/github.com\/rgieseke)'s [Locco](http:\/\/rgieseke.github.io\/locco\/).\n\n* And if you happen to be a **.NET**\naficionado, check out [Don Wilson](https:\/\/github.com\/dontangg)'s\n[Nocco](http:\/\/dontangg.github.io\/nocco\/).\n\n* Going further afield from the quick-and-dirty, [Groc](http:\/\/nevir.github.io\/groc\/)\nis a **CoffeeScript** fork of Docco that adds a searchable table of contents,\nand aims to gracefully handle large projects with complex hierarchies of code.\n\nNote that not all ports will support all Docco features ... yet.\n\n\nMain Documentation Generation Functions\n---------------------------------------\n\nGenerate the documentation for our configured source file by copying over static\nassets, reading all the source files in, splitting them up into prose+code\nsections, highlighting each file in the appropriate language, and printing them\nout in an HTML template.\n\n document = (options = {}, callback) ->\n config = configure options\n\n fs.mkdirs config.output, ->\n\n callback or= (error) -> throw error if error\n copyAsset = (file, callback) ->\n return callback() unless fs.existsSync file\n fs.copy file, path.join(config.output, path.basename(file)), callback\n complete = ->\n copyAsset config.css, (error) ->\n return callback error if error\n return copyAsset config.public, callback if fs.existsSync config.public\n callback()\n\n files = config.sources.slice()\n\n nextFile = ->\n source = files.shift()\n fs.readFile source, (error, buffer) ->\n return callback error if error\n\n code = buffer.toString()\n sections = parse source, code, config\n format source, sections, config\n write source, sections, config\n if files.length then nextFile() else complete()\n\n nextFile()\n\nGiven a string of source code, **parse** out each block of prose and the code that\nfollows it \u2014 by detecting which is which, line by line \u2014 and then create an\nindividual **section** for it. Each section is an object with `docsText` and\n`codeText` properties, and eventually `docsHtml` and `codeHtml` as well.\n\n parse = (source, code, config = {}) ->\n lines = code.split '\\n'\n sections = []\n lang = getLanguage source, config\n hasCode = docsText = codeText = ''\n\n save = ->\n sections.push {docsText, codeText}\n hasCode = docsText = codeText = ''\n\nOur quick-and-dirty implementation of the literate programming style. Simply\ninvert the prose and code relationship on a per-line basis, and then continue as\nnormal below.\n\n if lang.literate\n isText = maybeCode = yes\n for line, i in lines\n lines[i] = if maybeCode and match = \/^([ ]{4}|[ ]{0,3}\\t)\/.exec line\n isText = no\n line[match[0].length..]\n else if maybeCode = \/^\\s*$\/.test line\n if isText then lang.symbol else ''\n else\n isText = yes\n lang.symbol + ' ' + line\n\n for line in lines\n if line.match(lang.commentMatcher) and not line.match(lang.commentFilter)\n save() if hasCode\n docsText += (line = line.replace(lang.commentMatcher, '')) + '\\n'\n save() if \/^(---+|===+)$\/.test line\n else\n hasCode = yes\n codeText += line + '\\n'\n save()\n\n sections\n\nTo **format** and highlight the now-parsed sections of code, we use **Highlight.js**\nover stdio, and run the text of their corresponding comments through\n**Markdown**, using [Marked](https:\/\/github.com\/chjj\/marked).\n\n format = (source, sections, config) ->\n language = getLanguage source, config\n\nPass any user defined options to Marked if specified via command line option\n\n markedOptions =\n smartypants: true\n\n if config.marked\n markedOptions = config.marked\n\n marked.setOptions markedOptions\n\nTell Marked how to highlight code blocks within comments, treating that code\nas either the language specified in the code block or the language of the file\nif not specified.\n\n marked.setOptions {\n highlight: (code, lang) ->\n lang or= language.name\n\n if highlightjs.getLanguage(lang)\n highlightjs.highlight(lang, code).value\n else\n console.warn \"docco: couldn't highlight code block with unknown language '#{lang}' in #{source}\"\n code\n }\n\n for section, i in sections\n code = highlightjs.highlight(language.name, section.codeText).value\n code = code.replace(\/\\s+$\/, '')\n section.codeHtml = \"<div class='highlight'><pre>#{code}<\/pre><\/div>\"\n section.docsHtml = marked(section.docsText)\n\nOnce all of the code has finished highlighting, we can **write** the resulting\ndocumentation file by passing the completed HTML sections into the template,\nand rendering it to the specified output path.\n\n write = (source, sections, config) ->\n\n getpaths = (file) ->\n _extname = path.extname file\n _dirname = path.dirname file\n _basename = path.basename(file, _extname)\n urlprefix = config.urlprefix\n baseurl = if urlprefix? then urlprefix else '\/'\n relpath = path.join _dirname, \"#{_basename}.html\"\n return {\n url: path.join(baseurl, relpath)\n filepath: path.join(config.output, relpath)\n cssurl: path.join(baseurl, path.basename config.css)\n relpath\n }\n\nThe **title** of the file is either the first heading in the prose, or the\nname of the source file.\n\n firstSection = _.find sections, (section) ->\n section.docsText.length > 0\n first = marked.lexer(firstSection.docsText)[0] if firstSection\n hasTitle = first and first.type is 'heading' and first.depth is 1\n title = if hasTitle then first.text else path.basename source\n paths = getpaths source\n filepath = paths.filepath\n url = paths.url\n cssurl = paths.cssurl\n\n html = config.template {sources: config.sources, cssurl,\n title, hasTitle, sections, path, getpaths}\n\n console.log \"docco: #{source} -> #{filepath}\"\n mkdirp.sync path.dirname filepath\n fs.writeFileSync filepath, html\n\n\nConfiguration\n-------------\n\nDefault configuration **options**. All of these may be extended by\nuser-specified options.\n\n defaults =\n urlprefix: '\/'\n layout: 'parallel'\n output: 'docs'\n template: null\n css: null\n extension: null\n languages: {}\n marked: null\n\n**Configure** this particular run of Docco. We might use a passed-in external\ntemplate, or one of the built-in **layouts**. We only attempt to process\nsource files for languages for which we have definitions.\n\n configure = (options) ->\n config = _.extend {}, defaults, _.pick(options, _.keys(defaults)...)\n\n config.languages = buildMatchers config.languages\n\nThe user is able to override the layout file used with the `--template` parameter.\nIn this case, it is also neccessary to explicitly specify a stylesheet file.\nThese custom templates are compiled exactly like the predefined ones, but the `public` folder\nis only copied for the latter.\n\n if options.template\n unless options.css\n console.warn \"docco: no stylesheet file specified\"\n config.layout = null\n else\n dir = config.layout = path.join __dirname, 'resources', config.layout\n config.public = path.join dir, 'public' if fs.existsSync path.join dir, 'public'\n config.template = path.join dir, 'docco.jst'\n config.css = options.css or path.join dir, 'docco.css'\n config.template = _.template fs.readFileSync(config.template).toString()\n\n if options.marked\n config.marked = JSON.parse fs.readFileSync(options.marked)\n\n config.sources = options.args.filter((source) ->\n lang = getLanguage source, config\n console.warn \"docco: skipped unknown type (#{path.basename source})\" unless lang\n lang\n ).sort()\n\n config\n\n\nHelpers & Initial Setup\n-----------------------\n\nRequire our external dependencies.\n\n _ = require 'underscore'\n fs = require 'fs-extra'\n path = require 'path'\n marked = require 'marked'\n commander = require 'commander'\n highlightjs = require 'highlight.js'\n mkdirp = require 'mkdirp'\n\nLanguages are stored in JSON in the file `resources\/languages.json`.\nEach item maps the file extension to the name of the language and the\n`symbol` that indicates a line comment. To add support for a new programming\nlanguage to Docco, just add it to the file.\n\n languages = JSON.parse fs.readFileSync(path.join(__dirname, 'resources', 'languages.json'))\n\nBuild out the appropriate matchers and delimiters for each language.\n\n buildMatchers = (languages) ->\n for ext, l of languages\n\nDoes the line begin with a comment?\n\n l.commentMatcher = \/\/\/^\\s*#{l.symbol}\\s?\/\/\/\n\nIgnore [hashbangs](http:\/\/en.wikipedia.org\/wiki\/Shebang_%28Unix%29) and interpolations...\n\n l.commentFilter = \/(^#![\/]|^\\s*#\\{)\/\n languages\n languages = buildMatchers languages\n\nA function to get the current language we're documenting, based on the\nfile extension. Detect and tag \"literate\" `.ext.md` variants.\n\n getLanguage = (source, config) ->\n ext = config.extension or path.extname(source) or path.basename(source)\n lang = config.languages?[ext] or languages[ext]\n if lang and lang.name is 'markdown'\n codeExt = path.extname(path.basename(source, ext))\n if codeExt and codeLang = languages[codeExt]\n lang = _.extend {}, codeLang, {literate: yes}\n lang\n\nKeep it DRY. Extract the docco **version** from `package.json`\n\n version = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'))).version\n\n\nCommand Line Interface\n----------------------\n\nFinally, let's define the interface to run Docco from the command line.\nParse options using [Commander](https:\/\/github.com\/visionmedia\/commander.js).\n\n run = (args = process.argv) ->\n c = defaults\n commander.version(version)\n .usage('[options] files')\n .option('-L, --languages [file]', 'use a custom languages.json', _.compose JSON.parse, fs.readFileSync)\n .option('-l, --layout [name]', 'choose a layout (parallel, linear or classic)', c.layout)\n .option('-o, --output [path]', 'output to a given folder', c.output)\n .option('-c, --css [file]', 'use a custom css file', c.css)\n .option('-t, --template [file]', 'use a custom .jst template', c.template)\n .option('-e, --extension [ext]', 'assume a file extension for all inputs', c.extension)\n .option('-m, --marked [file]', 'use custom marked options', c.marked)\n .option('-u, --urlprefix [prefix]', 'set a custom url prefix', c.urlperfix)\n .parse(args)\n .name = \"docco\"\n if commander.args.length\n document commander\n else\n console.log commander.helpInformation()\n\n\nPublic API\n----------\n\n Docco = module.exports = {run, document, parse, format, version}\n","avg_line_length":37.3215258856,"max_line_length":111,"alphanum_fraction":0.660436592}
{"size":10281,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Oopish Helpers\n==============\n\n#### Define the core Oopish helper functions\n\nOopish helper functions are visible to all code defined in \u2018src\/\u2019 and \u2018test\/\u2019 \nbut are hidden from code defined elsewhere in the app. \n\n- Helpers have no side-effects, other than throwing exceptions\n- They run identically in all modern environments (browser, server, desktop, \u2026)\n- They are short - each minifies to xxx bytes, at most @todo how big? zipped?\n- They return the same output for a given set of arguments (except `oo.uid()`)\n\n\n\n\n#### `oo.is()`\nUseful for reducing CoffeeScript\u2019s verbose conditional syntax, eg: \n`if condition then 123 else 456` becomes `oo.is condition, 123, 456`. \n\n oo.is = (c, t=true, f=false) ->\n if c then t else f\n\n\n\n\n#### `oo.isU()`\n@todo description\n\n oo.isU = (x) ->\n oo.U == typeof x\n\n\n\n\n#### `oo.isX()`\n@todo description\n\n oo.isX = (x) ->\n null == x\n\n\n\n\n#### `oo.type()`\nTo detect the difference between 'null', 'array', 'regexp' and 'object' types, \nwe use [Angus Croll\u2019s one-liner](http:\/\/goo.gl\/WlpBEx). This can be used in \nplace of JavaScript\u2019s familiar `typeof` operator, with one important exception: \nwhen the variable being tested does not exist, `typeof foobar` will return \n`undefined`, whereas `oo.type(foobar)` will throw an error. \n\n oo.type = (a) ->\n return oo.X if oo.isX a # prevent `domwindow` in some UAs\n ta = typeof a\n return ta if { undefined:1, string:1, number:1, boolean:1 }[ta]\n if ! a.nodeName and a.constructor != Array and \/function\/i.test(''+a)\n return oo.F # IE<=8 http:\/\/goo.gl\/bTbbov\n ({}).toString.call(a).match(\/\\s([a-z0-9]+)\/i)[1].toLowerCase()\n\n\n\n\n#### `oo.ex()`\nExchanges a character from one set for its equivalent in another. To decompose \nan accent, use `oo.ex(c, '\u00e0\u00e1\u00e4\u00e2\u00e8\u00e9\u00eb\u00ea\u00ec\u00ed\u00ef\u00ee\u00f2\u00f3\u00f6\u00f4\u00f9\u00fa\u00fc\u00fb\u00f1\u00e7', 'aaaaeeeeiiiioooouuuunc')`\n\n oo.ex = (x, a, b) ->\n if -1 == pos = a.indexOf x then x else b.charAt pos\n\n\n\n\n#### `oo.has()`\nDetermines whether haystack contains a given needle. @todo arrays and objects\n\n oo.has = (h, n, t=true, f=false) ->\n if -1 != h.indexOf n then t else f\n\n\n\n\n#### `oo.uid()`\nXx optional prefix. @todo description\n\n oo.uid = (p='id') ->\n p + '_' + ( Math.random().toString(36) + '00000000' ).substr 2,8\n\n\n\n\n#### `oo.uid62()`\nXx optional prefix. @todo description\n\n oo.uid62 = (p='id', l=8) ->\n c = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n p + '_' + ( c.charAt(Math.floor(Math.random()*62)) while l-- ).join('')\n\n\n\n\n#### `oo.pad()` or `oo.lpad()`\nXx. @todo description\n\n oo.pad = oo.lpad = (s, l, c=' ') ->\n s + Array(l-s.length+1).join(c)\n\n\n\n\n#### `oo.rpad()`\nXx. @todo description\n\n oo.rpad = (s, l, c=' ') ->\n Array(l-s.length+1).join(c) + s\n\n\n\n\n#### `oo.insert()`\nXx. @todo description\n\n oo.insert = (basis, overlay, offset) ->\n basis.slice(0, offset) + overlay + basis.slice(offset+overlay.length)\n\n\n\n\n#### `oo.define()`\n- `'constant'` Enumerable but immutable\n\nConvert a property to one of XX kinds:\n\n if oo.ROBUSTABLE\n oo.define = (obj, name, value, kind) ->\n switch kind\n when 'constant'\n Object.defineProperty obj, name, { value:value, enumerable:true }\n when 'private'\n Object.defineProperty obj, name, { value:value, enumerable:false }\n else\n oo.define = (obj, name, value, kind) -> # legacy UAs\n obj[name] = value\n\n\n\n\n#### `oo.lock()`\n\n@todo describe\n\n if oo.ROBUSTABLE\n oo.lock = (obj) ->\n for key in Object.keys obj\n Object.defineProperty obj, key, { writable:false, configurable:false }\n Object.preventExtensions obj\n if obj.prototype and obj != obj.prototype then oo.lock obj.prototype\n else\n oo.lock = -> # legacy UAs\n\n\n\n\n#### `oo.vArray()`\n- `M <string>` a method-name prefix to add to exception messages\n- `arr <array>` the array which contains the values to validate\n- `signature <string>` type and rules for elements\n- `fallback <array>` (optional) a value to use if the array is empty\n- `<array>` returns the valid array\n\nValidates an array. \n\n oo.vArray = (M, arr, signature, fallback) ->\n\nGet `types` and `rule` from the signature. @todo min and max array sizes\n\n matches = signature.match \/^<\\[([|a-z]+)\\s*(.*)\\](\\d+-\\d+)?>$\/i\n if ! matches then throw RangeError \"\/bemusicalchairs\/oopish\/oo-helpers.litcoffee\n oo.vArray()\\n signature #{signature} is invalid\"\n [signature, types, rule, limit] = matches\n\nUse the fallback if needed. Otherwise, make sure we are dealing with an array. \n\n if ! arr then return fallback\n if oo.A != oo.type arr then throw RangeError M +\n \" is type #{oo.type arr} not array\"\n\nCheck the number of elements. \n\n if limit\n [min, max] = limit.split '-'\n if arr.length < min or arr.length > max\n throw RangeError M + \".length is #{arr.length} (must be #{limit})\"\n\nThe special 'any' type allows the array to contain anything. \n\n if 'any' == types then return arr\n\nStep through each element in `arr`, and get its value\u2019s type. \n\n for value,i in arr\n tv = oo.type value\n\nCheck the type and rule. \n\n pass = false\n for type in types.split '|'\n if (oo.N == type or oo.I == type) and oo.N == tv\n if oo.I == type and value % 1\n throw RangeError M + \"[#{i}] is a number but not an integer\"\n if rule\n [min, max] = rule.split '-'\n if value < min or value > max\n throw RangeError M + \"[#{i}] is #{value} (must be #{rule})\"\n pass = true\n break\n if type == tv\n if oo.S == tv and rule\n unless RegExp(rule).test value\n throw RangeError M + \"[#{i}] fails #{rule}\"\n pass = true\n break\n if \/^[A-Z]\/.test type\n if oo.O == tv\n if eval \"value instanceof #{type}\" #@todo refactor to avoid `eval()`\n pass = true\n break\n\n if pass then continue\n throw TypeError M + \"[#{i}] is type #{tv} not #{types}\"\n\nReturn the valid array. \n\n return arr\n\n\n\n\n#### `oo.vArg()`\n- `M <string>` a method-name prefix to add to exception messages\n- `value <any>` the value to validate\n- `signature <string>` the value\u2019s name and type\n- `fallback <mixed>` (optional) a value to use if `arg` is undefined\n- `<mixed>` returns the valid value\n\nCreates a custom validator. \n\n oo.vArg = (M, value, signature, fallback) ->\n\nGet `key`, `types` and `rule` from the signature. \n\n matches = signature.match \/^([_a-z][_a-z0-9]*)\\s+<([|a-z]+)\\s*(.*)>$\/i\n if ! matches then throw RangeError \"\/bemusicalchairs\/oopish\/oo-helpers.litcoffee\n oo.vArg()\\n signature #{signature} is invalid\"\n [signature, key, types, rule] = matches\n\nPrepare a prefix for errors. \n\n pfx = M + \"argument #{key} \"\n\nUse the fallback, if needed. \n\n tv = oo.type value\n if oo.U == tv\n if 4 == arguments.length then return fallback\n throw TypeError pfx + \"is undefined and has no fallback\"\n\nCheck the type and rule. \n\n for type in types.split '|'\n if (oo.N == type or oo.I == type) and oo.N == tv\n if oo.I == type and value % 1\n throw RangeError pfx + \"is a number but not an integer\"\n if rule\n [min, max] = rule.split '-'\n if value < min or value > max\n throw RangeError pfx + \"is #{value} (must be #{rule})\"\n return value\n if type == tv\n if oo.S == tv and rule\n unless RegExp(rule).test value\n throw RangeError pfx + \"fails #{rule}\"\n return value\n if \/^[A-Z]\/.test type\n if oo.O == tv\n if eval \"value instanceof #{type}\" #@todo refactor to avoid `eval()`\n return value\n\n throw TypeError pfx + \"is type #{tv} not #{types}\"\n\n\n\n\n#### `oo.vObject()`\n- `M <string>` a method-name prefix to add to exception messages\n- `obj <object>` the object which contains the values to validate\n- `<function>` the validator, which determines a property\u2019s validity\n - `signature <string>` the value\u2019s name and type\n - `fallback <mixed>` (optional) a value to use if `opt[key]` is undefined\n - `<mixed>` returns the valid value\n\nCreates a custom validator. \n\n oo.vObject = (M, objName, obj) ->\n\n if oo.O != oo.type obj\n throw TypeError M + objName + \" is type #{oo.type obj} not object\"\n\n (signature, fallback) ->\n\nGet `key`, `types` and `rule` from the signature. \n\n matches = signature.match \/^([_a-z][_a-z0-9]*)\\s+<([|a-z]+)\\s*(.*)>$\/i\n if ! matches then throw RangeError \"\/bemusicalchairs\/oopish\/oo-helpers.litcoffee\n oo.vObject()\\n signature #{signature} is invalid\"\n [signature, key, types, rule] = matches\n\nUse the fallback, if needed. \n\n value = obj[key]\n tv = oo.type value\n if oo.U == tv\n if 2 == arguments.length then return fallback\n throw TypeError M + objName + '.' + key + \" is undefined and has no fallback\"\n\nCheck the type and rule. \n\n for type in types.split '|'\n if (oo.N == type or oo.I == type) and oo.N == tv\n if oo.I == type and value % 1\n throw RangeError M + objName + '.' + key + \" is a number but not an integer\"\n if rule\n [min, max] = rule.split '-'\n if value < min or value > max\n throw RangeError M + objName + '.' + key + \" is #{value} (must be #{rule})\"\n return value\n if type == tv\n if oo.S == tv and rule\n unless RegExp(rule).test value\n throw RangeError M + objName + '.' + key + \" fails #{rule}\"\n return value\n if \/^[A-Z]\/.test type\n if oo.O == tv\n if eval \"value instanceof #{type}\" #@todo refactor to avoid `eval()`\n return value\n\n throw TypeError M + objName + '.' + key + \" is type #{tv} not #{types}\"\n\n\n\n\n ;\n\n\n","avg_line_length":29.0423728814,"max_line_length":91,"alphanum_fraction":0.568329929}
{"size":4786,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":5.0,"content":"\n## xmlPrettifier tests\n\nAuthor: Jan Gottschick\n\nTo test the xmlPrettifier ...\n\nImporting the Jasmine test framework addons to describe the specifications by\nexamples.\n\n\t\trequire 'jasmine-matchers'\n\t\trequire 'jasmine-given'\n\n\t\txmlPrettifier = require '..\/lib\/xmlPrettifierModule'\n\n\t\tcompile = (__done, __expr, __test, __debug = false) ->\n\t\t\ttry\n\t\t\t\t__code = xmlPrettifier.parse(__expr)\n\t\t\tcatch error\n\t\t\t\tconsole.log error.name + \" at \" + error.line + \",\" + error.column + \": \" + error.message if __debug\n\t\t\t\t__test false, ''\n\t\t\t\t__done()\n\t\t\t\treturn\n\t\t\tconsole.log __code.replace(\/\\t\/g, '\u21a6') if __debug\n\t\t\t__test true, __code\n\t\t\t__done()\n\nAnd the tests...\n\n\t\tdescribe 'The XML header', ->\n\n\t\t\tit 'should print a minimal xml header in one line', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml\n\t\t\t\t\tversion=\"1.1\"\n\t\t\t\t\t?>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n'\n\n\t\t\tit 'should print a full xml header in one line', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml\n\t\t\t\t\tversion=\"1.1\"\n\n\t\t\t\t\tencoding=\"utf-8\" standalone=\"yes\"\n\t\t\t\t\t?>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" encoding=\"utf-8\" standalone=\"yes\" ?>\\n'\n\n\t\t\tit 'should print processing instructions', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml\n\t\t\t\t\tversion=\"1.1\"\n\t\t\t\t\t?>\n\n\t\t\t\t\t<?pi huhuhuhuh huhu\n\n\t\t\t\t\t?>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<?pi huhuhuhuh huhu ?>\\n'\n\n\t\t\tit 'should print comments', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml\n\t\t\t\t\tversion=\"1.1\"\n\t\t\t\t\t?>\n\t\t\t\t\t<!--\n\t\t\t\t\t\tline 1\n\t\t\t\t\t\tline 2\n\t\t\t\t\t-->\n\t\t\t\t\t<?pi huhuhuhuh huhu\n\n\t\t\t\t\t?>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<!--\\n\\tline 1\\n\\tline 2\\n-->\\n<?pi huhuhuhuh huhu ?>\\n'\n\n\t\tdescribe 'The XML element content', ->\n\n\t\t\tit 'should print a single closed tag', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><tag\/>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<tag \/>\\n'\n\n\t\t\tit 'should print a single empty tag', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag> <\/Tag >\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag >\\n<\/Tag >\\n'\n\n\t\t\tit 'should print a single tag with content', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag> 234 <\/Tag >\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag >\\n 234\\n<\/Tag >\\n'\n\n\t\t\tit 'should print a single tag with cdata value', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag> <![CDATA[ dusfhufhu785475uirhruhf98usf hzuii <]]> <\/Tag >\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag >\\n <![CDATA[ dusfhufhu785475uirhruhf98usf hzuii <]]>\\n<\/Tag >\\n'\n\n\t\t\tit 'should print a single tag with mixed value', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag> 234 abc <![CDATA[ dusfhufhu785475uirhruhf98usf hzuii <]]> <\/Tag >\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag >\\n 234 abc\\n <![CDATA[ dusfhufhu785475uirhruhf98usf hzuii <]]>\\n<\/Tag >\\n'\n\n\t\t\tit 'should print a single tag with nested tags', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag1> <tag2> abc\n\t\t\t\t\t<\/tag2> <\/Tag1 >\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag1 >\\n <tag2 >\\n abc\\n <\/tag2 >\\n<\/Tag1 >\\n'\n\n\t\tdescribe 'The XML attribute', ->\n\n\t\t\tit 'should print an attribute with empty content', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag a\/>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag a \/>\\n'\n\n\t\t\tit 'should print an attribute with content', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag a=\"2 d\"\/>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag a=\"2 d\" \/>\\n'\n\n\t\t\tit 'should print multiple attributes', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag a1=\"2\"\n\n\t\t\t\t\ta2=\" d\"\/>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag a1=\"2\" a2=\" d\" \/>\\n'\n\n\t\tdescribe 'The XML comments', ->\n\n\t\t\tit 'should print embedded comments', (done) ->\n\t\t\t\tcompile done, '''\n\t\t\t\t\t<?xml version=\"1.1\" ?><Tag><!-- I am\n\t\t\t\t\tan embedded\n\t\t\t\t\t comment --><\/Tag>\n\t\t\t\t''', (ok, result) ->\n\t\t\t\t\texpect(ok).toBe true\n\t\t\t\t\texpect(result).toBe '<?xml version=\"1.1\" ?>\\n<Tag >\\n <!-- I am\\n an embedded\\n comment -->\\n<\/Tag >\\n'\n","avg_line_length":29.7267080745,"max_line_length":132,"alphanum_fraction":0.5528625157}
{"size":803,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":10.0,"content":"Here is a model to represent a pet. It is also acting as a test to demonstrate\nthat Sails happily copes with literate coffeescript files.\n\n module.exports =\n autoPK: false\n schema: true\n attributes:\n pet_id:\n type: 'integer'\n primaryKey: true\n autoIncrement: true\n name: 'string'\n owner:\n model: 'user'\n bestFriend:\n model: 'user'\n parents:\n collection: 'pet'\n via: 'children'\n children:\n collection: 'pet'\n via: 'parents'\n bestFurryFriend:\n model: 'pet'\n vets:\n collection: 'user'\n via: 'patients'\n\nIt is useful to know whether a pet is a pet, hence:\n\n isPet:\n type: 'boolean'\n defaultsTo: true\n","avg_line_length":23.6176470588,"max_line_length":78,"alphanum_fraction":0.5330012453}
{"size":1006,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":" JsonRenderer = require '.\/json_renderer'\n\n class JsonGround extends JsonRenderer\n\n args: [ 'ground', 'wall' ]\n delegates: [ 'grounder' ]\n\n render: (ctx, path, level_name, done) ->\n ground_segments = @ground.segments\n\n for step, i in path\n ctx[i].ground = [ ]\n\n s = 0\n\n while s < ground_segments\n segment = @grounder @ground, @wall, step, i, path, s, ctx[i].ground\n\n if segment.thickness == -1\n\n j = 0\n\n while j < segment.width\n ctx[i - 1]?.ground[s + j++]?.thickness = 0\n\n seg = @grounder @ground, @wall, direction: 'FAKE', i, path, s, ctx[i].ground\n\n segment.thickness = seg.thickness\n\n k = 0\n\n while k < segment.width\n if ctx[i].ground.length < @ground.segments\n ctx[i].ground.push thickness: segment.thickness\n\n ++k\n ++s\n\n done()\n\n module.exports = JsonGround\n","avg_line_length":23.9523809524,"max_line_length":90,"alphanum_fraction":0.5019880716}
{"size":10483,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":58.0,"content":"Launch Server\n=============\nCopyright (C) 2015, Bill Burdick, Roy Riggs, TEAM CTHULHU\n\nSockJS bindings for OT\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\nLaunch an OT server\n\n require('source-map-support').install()\n sockjs = require 'sockjs'\n sockjsUtil = require 'sockjs\/lib\/utils'\n http = require 'http'\n crypto = require 'crypto'\n serveStatic = require 'serve-static'\n finalhandler = require 'finalhandler'\n path = require 'path'\n console.log \"DIR: #{path.resolve path.dirname(module.filename) + '\/..\/..'}\"\n baseDir = path.resolve path.dirname(module.filename) + \"\/..\/..\"\n _ = require \"#{baseDir}\/lib\/lodash.min\"\n requirejs = require('requirejs').config\n baseUrl: baseDir\n paths:\n immutable: 'lib\/immutable-3.8.1.min.js'\n\n {\n badMasterIdError\n badMsgTypeError\n disapprovedError\n badVersionError\n noTrim\n } = requirejs '.\/common'\n {\n Server: OtServer\n } = requirejs 'lib\/ot\/server'\n {\n WrappedOperation\n } = requirejs 'lib\/ot\/wrapped-operation'\n {\n TextOperation\n } = requirejs 'lib\/ot\/text-operation'\n {\n RejectGuardedOperation\n } = requirejs 'lib\/ot\/guarded-operation'\n {\n GuardedServer\n } = requirejs 'lib\/ot\/guarded-server'\n {\n Selection\n } = requirejs 'lib\/ot\/selection'\n\n masters = {}\n socketPrefix = '\/Leisure\/(create|join(?:-([^\/]*)))'\n\nThanks to [Broofa's stackoverflow post](http:\/\/stackoverflow.com\/questions\/105034\/create-guid-uuid-in-javascript\/105074#105074) Altered the code to use crypto's random.\n\n s4 = ->\n bytes = crypto.randomBytes 2\n n = (bytes[0] + (bytes[1] << 8)).toString(16)\n while n.length < 4\n n = '0' + n\n n\n\n guid = -> \"#{s4()}#{s4()}-#{s4()}-#{s4()}-#{s4()}-#{s4()}#{s4()}#{s4()}\"\n\n diag = (args...)-> console.log args...\n\n class MessageHandler\n constructor: ->\n @guid = guid()\n @messageCount = 1\n @lastVersionAck = -1\n setConnection: (@con)->\n console.log \"#{@type} connection: #{@guid}\"\n @con.leisure = this\n @con.on 'data', (msg)=> @handleMessage JSON.parse msg\n @con.on 'close', => @closed()\n type: 'Unknown Handler'\n close: -> @con.close()\n closed: -> console.log \"#{@type} closed: #{@guid}\"\n send: (msg)->\n diag \"S #{JSON.stringify msg}\"\n @con.write JSON.stringify msg\n broadcast: (msg)-> @master.sendBroadcast this, msg\n sendError: (msg)->\n msg.type = 'error'\n @send msg\n setTimeout (=> @close()), 1\n\nHandle a message from the connected browser\n\n handleMessage: (msg)->\n msg.connectionId = @connectionId\n diag \"R #{JSON.stringify msg}\"\n if !(msg.type of @handler)\n console.log \"Received bad message #{msg.type}\", msg\n @close()\n else\n try\n @handler[msg.type].call this, msg\n catch err\n console.log err.stack\n handler:\n log: (msg)-> console.log msg.msg\n replace: (msg)->\n @lastVersionAck = msg.parent\n @master.relay msg\n conditionalReplace: (msg)->\n if msg.version != @master.version && @master.versionDirty\n @send type: 'rejectChange', targetVersion: msg.targetVersion, version: @version\n else @master.relay msg\n guardedOperation: (msg)-> @master.guardedOperation this, msg\n operation: (msg)-> @master.operation this, msg\n selection: (msg)-> @master.selection this, msg\n setName: (msg)-> @master.setName this, msg\n peerEntry: -> {@name, @selection}\n\n isTextMsg = (msg)-> msg.type in ['replace', 'conditionalReplace']\n\n class MasterHandler extends MessageHandler\n constructor: ->\n super()\n @master = this\n @connectionId = \"peer-0\"\n @slaves = {}\n @pendingSlaves = {}\n @peerCount = 0\n type: 'Master'\n peers: ->\n cons = {}\n cons[@connectionId] = @peerEntry()\n for id, s of @slaves\n cons[id] = s.peerEntry()\n cons\n setConnection: (con)->\n masters[@guid] = this\n super con\n @send type: 'connected', guid: @guid, id: @connectionId, revision: 0, peers: @peers()\n addSlave: (slave)->\n slave.connectionId = \"peer-#{++@peerCount}\"\n @pendingSlaves[slave.connectionId] = slave\n @send type: 'slaveConnect', slaveId: slave.connectionId\n removeSlave: (slave)->\n delete @slaves[slave.connectionId]\n delete @pendingSlaves[slave.connectionId]\n @send type: 'slaveDisconnect', slaveId: slave.connectionId\n @sendBroadcast null, type: 'disconnection', peerId: slave.connectionId\n closed: ->\n delete masters[@con.leisure.id]\n for id, slave of @slaves\n slave.close()\n @slaves = {}\n super()\n sendBroadcast: (sender, msg)->\n for id, slave of @slaves\n if sender != slave then slave.send msg\n if sender != this then @send msg\n guardedOperation: (peer, {revision, operation, selection, guards, guardId})->\n try\n wrapped = new WrappedOperation(\n TextOperation.fromJSON operation,\n selection && Selection.fromJSON(selection))\n catch exc\n peer.send {type: 'rejectGuard', guardId}\n console.error \"Invalid operation received: \" + exc.stack\n return;\n try\n wrappedPrime = @otServer.receiveGuardedOperation revision, wrapped, guards\n if wrappedPrime == RejectGuardedOperation\n peer.send {type: 'rejectGuard', guardId, retryOK: true}\n else\n console.log \"new guard operation: \" + JSON.stringify wrapped\n peer.selection = wrappedPrime.meta\n @sendBroadcast null, type: 'operation', peerId: peer.connectionId, operation: wrappedPrime.wrapped.toJSON(), meta: wrappedPrime.meta\n peer.send {type: 'ackGuard', guardId, operation: wrappedPrime.wrapped.toJSON()}\n catch exc\n peer.send {type: 'rejectGuard', guardId}\n console.error exc.stack\n operation: (peer, {revision, operation, selection})->\n try\n wrapped = new WrappedOperation(\n TextOperation.fromJSON operation,\n selection && Selection.fromJSON(selection))\n catch exc\n console.error \"Invalid operation received: \" + exc.stack\n return;\n try\n wrappedPrime = @otServer.receiveOperation revision, wrapped\n console.log \"new operation: \" + JSON.stringify wrapped\n peer.selection = wrappedPrime.meta\n peer.send type: 'ack'\n peer.broadcast type: 'operation', peerId: peer.connectionId, operation: wrappedPrime.wrapped.toJSON(), meta: wrappedPrime.meta\n catch exc\n console.error exc.stack\n selection: (peer, {selection})->\n if selection then peer.selection = selection;\n else delete peer.selection;\n peer.broadcast type: 'selection', peerId: peer.id, selection: selection\n setName: (peer, {name})->\n peer.name = name;\n peer.broadcast type: 'setName', peerId: peer.id, name: name\n handler:\n __proto__: MessageHandler::handler\n initDoc: ({doc, @name})-> @otServer = new GuardedServer(doc)\n slaveApproval: ({slaveId, approval})->\n if slave = @pendingSlaves[slaveId]\n delete @pendingSlaves[slaveId]\n if approval\n slave.send type: 'connected', id: slave.connectionId, doc: @otServer.document, revision: @otServer.operations.length, peers: @peers()\n @slaves[slaveId] = slave\n else slave.sendError disapprovedError()\n fileContent: (msg)->\n id = msg.slaveId\n delete msg.slaveId\n @slaves[id].send msg\n fileError: (msg)->\n id = msg.slaveId\n delete msg.slaveId\n @slaves[id].send msg\n customResponse: (msg)->\n id = msg.slaveId\n delete msg.slaveId\n @slaves[id].send msg\n\n class SlaveHandler extends MessageHandler\n type: 'Slave'\n setConnection: (con, masterId)->\n if !(@master = masters[masterId])\n @sendError badMasterIdError masterId\n else @master.addSlave this\n super con\n closed: ->\n @master.removeSlave this\n super()\n handler:\n __proto__: MessageHandler::handler\n intro: ({@name})->\n @broadcast type: 'connection', peerId: @connectionId, peerName: @name\n requestFile: (msg)->\n msg.slaveId = @connectionId\n @master.send msg\n customMessage: (msg)->\n msg.slaveId = @connectionId\n @master.send msg\n\n startServer = (port)->\n console.log 'serve: ' + path.dirname(process.cwd())\n files = serveStatic path.dirname(process.cwd()), index: ['index.html']\n docs = serveStatic path.resolve(path.dirname(process.cwd()), \"..\/docs\")\n http_server = http.createServer (req, res)->\n (if m = req.url.match \/^\\\/docs(\\\/.*)$\/\n req.url = m[1]\n docs\n else files) req, res, finalhandler req, res\n sockjs.createServer(\n sockjs_url: 'http:\/\/cdn.jsdelivr.net\/sockjs\/1.0.1\/sockjs.min.js'\n prefix: socketPrefix)\n .on 'connection', (con)->\n if [ignore, type, masterId] = con.pathname.match socketPrefix\n if type == 'create' then new MasterHandler().setConnection con\n else new SlaveHandler().setConnection con, masterId\n .installHandlers(http_server)\n http_server.listen(port, '0.0.0.0')\n masters\n\n module.exports = {\n startServer\n }\n","avg_line_length":36.2733564014,"max_line_length":168,"alphanum_fraction":0.6065057712}
{"size":1611,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"## `show` command handler\n\n\tfs_sync = require 'fs-sync'\n\tfs = require 'fs'\n\tes = require 'event-stream'\n\tpm2 = require 'pm2'\n\tpath = require 'path'\n\texec = require('child_process').exec\n\tspawn = require('child_process').spawn\n\tpkg = require(path.join(__dirname, '..\/package.json'))\n\tcolors = require 'colors'\n\tmoment = require 'moment'\n\trimraf = require 'rimraf'\n\n\tmodule.exports = (end) ->\n\n\t\tapp_name = path.basename process.cwd()\n\t\t\n\t\tif fs_sync.exists path.join(process.cwd(), 'package.json')\n\t\t\tapp_pkg = require(path.join(process.cwd(), 'package.json'))\n\t\t\tapp_name = app_pkg.name\n\t\t\n\t\tapp_name = process.argv[3] if process.argv[3]\n\t\texists = false\n\nFirst we use PM2 to see if the named app is running.\n\n\t\tpm2.connect (err) ->\n\t\t\tend err if err\n\n\t\t\tpm2.list (err, list) ->\n\t\t\t\tend err if err\n\t\t\t\tfor proc in list\n\t\t\t\t\texists = true if proc.name is app_name\n\t\t\t\t\n\t\t\t\tif exists is true\n\t\t\t\t\tpm2.describe app_name, (err, proc) ->\n\t\t\t\t\t\tend err if err\n\t\t\t\t\t\tpm2.disconnect () ->\n\t\t\t\t\t\t\tstatus = if proc[0].pm2_env.status is 'online' then proc[0].pm2_env.status.green else proc[0].pm2_env.status.red\n\t\t\t\t\t\t\tend \"\\n ====================================\\n\n\t\t\t\t\t\t\t\t#{app_name.magenta}\\n\n\t\t\t\t\t\t\t\t------------------------------------\\n\n\t\t\t\t\t\t\t\tInstances: #{proc[0].pm2_env.instances}\\n\n\t\t\t\t\t\t\t\tLast Started: #{moment(proc[0].pm2_env.created_at).fromNow()}\\n\n\t\t\t\t\t\t\t\tStatus: #{status}\\n\n\t\t\t\t\t\t\t\t====================================\"\n\nIf there aren't any matching processes running, end with error.\n\n\t\t\t\tif exists is false\n\t\t\t\t\tpm2.disconnect () ->\n\t\t\t\t\t\tend \"[Error] No app by the name of `#{app_name}` running.\".red","avg_line_length":30.3962264151,"max_line_length":119,"alphanum_fraction":0.5977653631}
{"size":3998,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# `UI.UI` #\n\n## Usage ##\n\n> ```jsx\n> <UI\n> title=React.PropTypes.string\n> maxchars=React.PropTypes.number.isRequired\n> myID=React.PropTypes.number.isRequired\n> defaultPrivacy=React.PropTypes.string\n> thirdColumn=React.PropTypes.element.isRequired\n> showComposer=React.PropTypes.bool\n> composerQuery=React.PropTypes.object\n> >\n> {\/* content *\/}\n> <\/UI>\n> ```\n> Creates a `UI` component, which contains the entire rendered frontend. The accepted properties are:\n> - **`title` [OPTIONAL `string`] :**\n> The title of the site.\n> - **`maxChars` [REQUIRED `number`] :**\n> The maximum number of characters to allow in a post.\n> - **`myID` [REQUIRED `number`] :**\n> The account id for the currently signed-in user.\n> - **`defaultPrivacy` [OPTIONAL `string`] :**\n> The default privacy setting.\n> - **`thirdColumn` [REQUIRED `element`] :**\n> The component to display in the third column.\n> - **`showComposer` [OPTIONAL `boolean`] :**\n> Whether or not to show the composer.\n> - **`composerQuery` [OPTIONAL `object`] :**\n> Query parameters to initialize the composer.\n\n## The Component ##\n\nOur UI doesn't have any properties except for its `title` and children.\n\n UI.UI = React.createClass\n\n mixins: [ReactPureRenderMixin]\n\n propTypes:\n title: React.PropTypes.string\n maxChars: React.PropTypes.number.isRequired\n myID: React.PropTypes.number.isRequired\n thirdColumn: React.PropTypes.element.isRequired\n showComposer: React.PropTypes.bool\n composerQuery: React.PropTypes.object\n\n### Event handling:\n\nHere we will handle events related to the UI:\n\n handleEvent: (e) ->\n switch e.type\n\n#### Drag-and-drop.\n\nThis handles our drag-and-drop events:\n\n when \"dragenter\" then (document.getElementById \"labcoat-ui\").setAttribute \"data-laboratory-dragging\", \"\"\n when \"dragover\"\n do e.preventDefault\n e.dataTransfer.dropEffect = \"copy\"\n when \"dragleave\" then (document.getElementById \"labcoat-ui\").removeAttribute \"data-laboratory-dragging\" unless e.relatedTarget?\n when \"drop\"\n do e.preventDefault\n (document.getElementById \"labcoat-ui\").removeAttribute \"data-laboratory-dragging\"\n # Laboratory.Composer.UploadRequested.dispatch {file: e.dataTransfer.files.item 1} if e.dataTransfer and e.dataTransfer.files.length is 1\n\n\n### Loading:\n\nHere we add our event listeners.\n\n componentWillMount: ->\n document.addEventListener \"dragenter\", this\n document.addEventListener \"dragover\", this\n document.addEventListener \"dragleave\", this\n document.addEventListener \"drop\", this\n\n### Unloading:\n\nWe can remove our event listeners if we're unloading our UI.\n\n componentWillUnmount: ->\n document.removeEventListener \"dragenter\", this\n document.removeEventListener \"dragover\", this\n document.removeEventListener \"dragleave\", this\n document.removeEventListener \"drop\", this\n\n### Rendering:\n\n render: ->\n \u5f41 'div', {id: \"labcoat-ui\"},\n \u5f41 UI.Header, {title: @props.title}\n \u5f41 Columns.Timeline, {name: \"home\"}\n \u5f41 Columns.Timeline, {name: \"notifications\"}\n @props.thirdColumn\n @props.children\n \u5f41 Modules.Composer,\n defaultPrivacy: @props.defaultPrivacy\n myID: @props.myID\n maxChars: @props.maxChars\n visible: @props.showComposer\n text: @props.composerQuery?.text\n inReplyTo: if isFinite @props.composerQuery?.inReplyTo then Number @props.composerQuery.inReplyTo else undefined\n","avg_line_length":37.0185185185,"max_line_length":157,"alphanum_fraction":0.603801901}
{"size":3022,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"04 Listag::delete()\n===================\n\n\n tudor.add [\n \"04 Listag::delete()\"\n tudor.is\n\n\n\n\n \"`delete()` is a function which does not return anything\"\n\nPrepare a test-instance. \n\n -> [new Listag]\n\n\n \"`delete()` is a function\"\n oo.F\n (listag) -> listag.delete\n\n\n \"`delete()` is not writable\"\n oo.F\n (listag) ->\n listag.delete = 123\n listag.delete\n\n\n \"`delete()` is not configurable\"\n oo.F\n (listag) ->\n try\n Object.defineProperty listag, 'delete', { writable:true }\n catch e\n listag.delete = 123\n listag.delete\n\n\n \"`delete('the_first')` returns `undefined`\"\n oo.U\n (listag) ->\n listag.add (new Date), 'the_first'\n listag.delete 'the_first'\n\n tudor.equal\n\n \"After deletion, `total.node` is zero\"\n 0\n (listag) ->\n Object.keys(listag.total).length\n\n\n\n\n \"The `id` argument accepts a string as expected\"\n\n\n \"Shortest possible id\"\n 0\n (listag) ->\n listag.add {}, 'a1'\n listag.delete 'a1'\n Object.keys(listag.total).length\n\n\n \"Longest possible id\"\n 0\n (listag) ->\n listag.add {}, 'abcdefghijklMNOPQRST123_'\n listag.delete 'abcdefghijklMNOPQRST123_'\n Object.keys(listag.total).length\n\n\n \"An autogenerated id\"\n 0\n (listag) ->\n id = listag.add {}\n listag.delete id\n Object.keys(listag.total).length\n\n\n\n\n \"`id` exceptions\"\n tudor.throw\n\n\n \"Is boolean\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id is type boolean not string\"\"\"\n (listag) -> listag.delete true\n\n\n \"Too short\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id fails ^[a-z]\\\\w{1,23}$\"\"\"\n (listag) -> listag.delete 'a'\n\n\n \"Too long\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id fails ^[a-z]\\\\w{1,23}$\"\"\"\n (listag) -> listag.delete 'aBcDeFgHiJkLmNoPqRsT123_X'\n\n\n \"Underscore is an invalid first character\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id fails ^[a-z]\\\\w{1,23}$\"\"\"\n (listag) -> listag.delete '_abc'\n\n\n \"Number is an invalid first character\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id fails ^[a-z]\\\\w{1,23}$\"\"\"\n (listag) -> listag.delete '1abc'\n\n\n \"Uppercase is an invalid first character\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id fails ^[a-z]\\\\w{1,23}$\"\"\"\n (listag) -> listag.delete 'Abc'\n\n\n \"Must not contain a hyphen\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n argument id fails ^[a-z]\\\\w{1,23}$\"\"\"\n (listag) -> listag.delete 'ab-c'\n\n\n \"Must exist\"\n \"\"\"\n \/listag\/src\/Listag.litcoffee Listag::delete()\n the node with id 'non_existant' does not exist\"\"\"\n (listag) ->\n listag.delete 'non_existant'\n\n\n\n\n ];\n\n","avg_line_length":20.0132450331,"max_line_length":67,"alphanum_fraction":0.5450033091}
{"size":227,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Typical instantiation of the `Tfmm` class\n\n tudor.add [\n \"01 Tfmm Constructor Usage\"\n\n\n\n\n \"The class and instance are expected types\"\n\n\n tudor.is\n\n \"The class is a function\"\n \u00aaF\n -> Main\n\n ]\n","avg_line_length":11.9473684211,"max_line_length":49,"alphanum_fraction":0.577092511}
{"size":372,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":58.0,"content":"Lorg file registry\n\n require?('.\/preamble')\n root = Leisure = ((typeof window != 'undefined') && window.Leisure) || {};\n\n registry = {}\n\n registerFile = (name)->\n if !registry[name] then registry[name] =\n exports: {}\n controls: {}\n views: {}\n css: []\n html: []\n registry[name]\n\n root.registerFile = registerFile\n","avg_line_length":20.6666666667,"max_line_length":78,"alphanum_fraction":0.5295698925}
{"size":4803,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":33.0,"content":" mod = angular.module('vespa.services')\n\n mod.service 'RefPolicy',\n class RefPolicyImpl\n constructor: (@VespaLogger, @SockJSService, @$q, @$timeout, @IDEBackend)->\n\n @uploader_running = false\n @chunks_to_upload = []\n @current = null\n @_deferred_load = null\n\n promise: =>\n if @_deferred_load?\n return @_deferred_load.promise\n @_deferred_load = @$q.defer()\n\n # If promise comes back, no matter what the\n # result, make this variable null\n @_deferred_load.promise['finally'] =>\n @_deferred_load = null\n\n return @_deferred_load.promise\n\n fetch_module_files: (module_id)=>\n unless @current?\n @VespaLogger.log 'refpolicy', 'error',\n \"Cannot view module files without loading policy\"\n return\n\n deferred = @$q.defer()\n\n req = \n domain: 'refpolicy'\n request: 'fetch_module_source'\n payload: \n refpolicy: @current._id\n module: module_id\n\n @SockJSService.send req, (data)=>\n if data.error?\n deferred.reject(data)\n else\n deferred.resolve(data.payload)\n\n return deferred.promise\n\n load: (id)=>\n if @current? and @current.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 @current = null\n deferred.reject(@current)\n else\n @current = data.payload\n @current._id = @current._id.$oid\n\n @VespaLogger.log 'policy', 'info', \"Loaded Reference Policy: #{@current.id}\"\n @IDEBackend.clear_policy()\n\n deferred.resolve(@current)\n\n return deferred.promise\n\n delete: (id)->\n deferred = @_deferred_load || @$q.defer()\n\n req = \n domain: 'refpolicy'\n request: 'delete'\n payload: id\n\n @SockJSService.send req, (data)=>\n if data.error?\n deferred.reject(null)\n else\n @VespaLogger.log 'policy', 'info', \"Deleted Reference Policy: #{id}\"\n @IDEBackend.clear_policy()\n\n deferred.resolve(null)\n\n return deferred.promise\n\n current_as_select2: =>\n return null unless @current?\n ret =\n id: @current._id\n text: @current.id\n\n upload_chunk: (name, chunk, start, len, total)=>\n deferred = @$q.defer()\n\n req = \n domain: 'refpolicy'\n request: 'upload_chunk'\n payload: \n name: name\n data: chunk\n index: start\n length: len\n total: total\n\n @chunks_to_upload.push [req, deferred]\n\nIf this is the only thing in the queue, start the uploader\n\n if not @uploader_running\n @uploader_running = true\n @$timeout =>\n @_upload_chunks()\n\n return deferred.promise\n\n _upload_chunks: =>\n\n chunk = @chunks_to_upload.shift()\n req = chunk[0]\n deferred = chunk[1]\n\n @SockJSService.send req, (data)=>\n if data.error?\n deferred.reject(data.payload)\n @uploader_running = false\n @chunks_to_upload = []\n else\n deferred.resolve(data.payload)\n if @chunks_to_upload.length > 0\n @_upload_chunks()\n else\n @uploader_running = false\n\n\n list_modules: (oid)=>\n deferred = @$q.defer()\n\n req = \n domain: 'refpolicy'\n request: 'find'\n payload: \n criteria:\n _id: oid\n valid: true\n selection:\n id: true\n modules: true\n\n @SockJSService.send req, (data)->\n if data.error?\n deferred.reject(data.payload)\n else\n deferred.resolve(data.payload)\n\n return deferred.promise\n\n\n list: =>\n\n deferred = @$q.defer()\n\n req = \n domain: 'refpolicy'\n request: 'find'\n payload: \n criteria:\n valid: true\n selection:\n id: true\n\n\n @SockJSService.send req, (data)->\n if data.error?\n deferred.reject(data.payload)\n else\n deferred.resolve(data.payload)\n\n return deferred.promise\n\n","avg_line_length":25.8225806452,"max_line_length":90,"alphanum_fraction":0.4834478451}
{"size":1229,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Oopish Constants\n================\n\n#### Define the core Oopish constants\n\nOopish\u2019s constants are visible to all code defined in \u2018src\/\u2019 and \u2018test\/\u2019, but \nhidden from code defined elsewhere in the app. \n\n\n\n\nConstants which help minification\n---------------------------------\n\nThese strings can make `*.min.js` a little shorter and easier to read, and also \nmake the source code less verbose: `O == typeof x` vs `'object' == typeof x`.\n\n A = 'array'\n B = 'boolean'\n # class, not used to avoid confusion with a class\u2019s `C` property\n D = 'document'\n E = 'error'\n F = 'function'\n # global, see build-constants, below\n I = 'integer'\n # method, not used to avoid confusion with a method\u2019s `M` variable\n N = 'number'\n O = 'object'\n R = 'regexp'\n S = 'string'\n # title, see build-constants, below\n U = 'undefined'\n # version, see build-constants, below\n X = 'null'\n\n\n\n\nBuild Constants\n---------------\n\nGenerated during the build-process and injected into app-scope. \n\n G = _oG # global scope, passed into the closure as an argument\n T = _oT # project title, converted from package.json's name\n V = _oV # project version, from package.json\n\n\n\n ;\n\n","avg_line_length":23.6346153846,"max_line_length":80,"alphanum_fraction":0.6037428804}
{"size":1730,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"\n# Application Startup\n\nThis code starts up the application.\n\n## Configure\n\nFirst, include required modules.\n\n express = require 'express'\n exp3hbs = require 'express3-handlebars'\n\nNext, initialize the application.\n\n app = express()\n\nConfigure HBS to glue Express and Handlebars together with HTML file extensions\nfor templates. Also, register a partials directory to pre-load.\n\n app.set 'view engine', 'html'\n exp3hbs_config =\n defaultLayout: 'default',\n extname: '.html'\n app.engine 'html', exp3hbs(exp3hbs_config)\n\nConfigure Express to serve static files.\n\n app.use express.static('public')\n\n## Routes\n\nAdd essential routes.\n\n app.get '\/', (req, res) ->\n res.render 'hello_world', {\n title: 'Hello World'\n }\n \n\n## Startup\n\nFinally, start the server.\n\n app.listen 3000\n\n## Copying\n\nThis software is released under the ISC License.\n\nCopyright (c) 2013, Cameron King <cking@ecc12.com>\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<!-- vim: ts=2 sts=2 sw=2 expandtab\n CoffeeScript-friendly tabstops in vim. -->\n","avg_line_length":26.2121212121,"max_line_length":79,"alphanum_fraction":0.7352601156}
{"size":150,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":" h1 = (text) -> console.log text\n\n# How to Say Hello:\n\n console.log \"3\"\n console.log \"2\"\n console.log \"1\"\n console.log \"Hello, World!\"\n","avg_line_length":16.6666666667,"max_line_length":35,"alphanum_fraction":0.5733333333}
{"size":14278,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Main\n====\n\n@todo describe\n\n\n#### The main class for Develoop\n\n class Main\n C: \u00aaC\n toString: -> \"[object #{@C}]\"\n\n constructor: (config={}) ->\n\n\n\n\nProperties\n----------\n\n\n#### `pegjs <xx>`\nXx. @todo describe\n\n @pegjs = PEG\n\n\n#### `aceGrammar <xx>`\nXx. @todo describe\n\n @aceGrammar = AceGrammar\n\n\n#### `helpers <array of Directories and Files>`\nXx. @todo describe\n\n @helpers = []\n\n\n#### `languages <array of Directories and Files>`\nXx. @todo describe\n\n @languages = []\n\n\n#### `oopish <array of Directories and Files>`\nThe top level of the build and development utilities. \n\n @oopish = []\n\n\n#### `project <array of Directories and Files>`\nThe top level of the developer\u2019s project. \n\n @project = []\n\n\n\n\nInit\n----\n\nInitialize the instance. \n\n @init()\n\n\n\n\nMethods\n-------\n\n\n#### `init()`\n\nXx. @todo describe\n\n init: ->\n @helpers.push new File @,\n title: 'Add'\n label: 'add.js'\n notes: ['Adds two numbers together']\n value: (x, y) -> x+y\n\n @helpers.push new File @,\n title: 'Increment'\n label: 'inc.js'\n notes: ['Adds 1 to a number']\n value: (x) -> x+1\n\n @helpers.push new File @,\n title: 'Foo'\n label: 'foo.js'\n notes: ['Adds 1 to a number']\n value: (x) -> 'foo'\n\n @helpers.push new File @,\n title: 'Bar'\n label: 'bar.js'\n notes: ['Adds 1 to a number']\n editable: true\n value: (x) -> 'bar'\n\n\n##### Languages\n\n @languages.push new Directory @,\n title: 'Markdown'\n label: 'markdown'\n notes: ['Simple text markup']\n files: [\n new File @,\n title: 'Bold'\n label: 'bold.js'\n notes: ['Bold text']\n value: \"\"\"\n function md_bold(input) {\n }\n\n \"\"\"\n new File @,\n title: 'Italic'\n label: 'italic.js'\n notes: ['Italic text']\n value: \"\"\"\n function md_italic(input) {\n }\n\n \"\"\"\n ]\n\n @languages.push new Directory @,\n title: 'Oopish'\n label: 'oopish'\n notes: ['A little language which compiles to ES6']\n files: [\n new File @,\n title: '.Item'\n label: 'Item.js'\n notes: ['The Item class']\n value: \"\"\"\n function item_js(input) {\n }\n\n \"\"\"\n new File @,\n title: '.List'\n label: 'List.js'\n notes: ['The List class']\n editable: true\n value: \"\"\"\n function list_js(input) {\n }\n\n \"\"\"\n ]\n\n\n##### Oopish compiler and highlighter\n\n @oopish.push new Directory @,\n title: 'Build'\n label: 'build'\n notes: ['Destination for compiled development and build utilities, so do not edit these files directly']\n files: [\n new File @,\n title: 'Oopish Compiler'\n label: 'oopish-compiler.js'\n notes: ['A parser and compiler generated by PEG.js from pegjs-helpers.js and pegjs-rules.pegjs']\n value: \"\"\"\n function peg$parse(input) {\n }\n\n \"\"\"\n new File @,\n title: 'Minified Oopish Compiler'\n label: 'oopish-compiler.min.js'\n notes: ['Minified parser and compiler, with no comments or test']\n value: \"\"\"\n function peg$parse(i){};\n \"\"\"\n new File @,\n title: 'Oopish Compiler With Tests'\n label: 'oopish-compiler.test.js'\n notes: ['A parser and compiler generated by PEG.js, with tests']\n value: \"\"\"\n function peg$parse(input) {\n }\n console.assert('abc', 123);\n\n \"\"\"\n new File @,\n title: 'Oopish Highlighter'\n label: 'oopish-highlighter.js'\n notes: ['A parser and syntax highlighter generated by AceGrammar, to be used by ACE']\n value: \"\"\"\n \/\/\/\/ Mode generated by Develoop 0.0.7\n\n modeGrammar = {\n }\n\n \"\"\"\n new File @,\n title: 'Minified Oopish Highlighter'\n label: 'oopish-highlighter.min.js'\n notes: ['Minified parser and syntax highlighter, with no comments or test']\n value: \"\"\"\n modeGrammar={}\n \"\"\"\n new File @,\n title: 'Oopish Highlighter With Tests'\n label: 'oopish-highlighter.test.js'\n notes: ['A parser and syntax highlighter generated by AceGrammar, with tests']\n value: \"\"\"\n \/\/\/\/ Mode generated by Develoop 0.0.7\n\n modeGrammar = {\n }\n\n console.assert('abc', 123);\n\n \"\"\"\n ]\n\n @oopish.push new Directory @,\n title: 'Documentation'\n label: 'doc'\n notes: ['Documentation for the Oopish IDE and programming language, in Markdown format']\n files: [\n new File @,\n title: 'oopish_md'\n label: 'oopish.md'\n notes: ['An introduction to the Oopish programming language']\n value: \"\"\"\n Oopish\n ======\n\n \"\"\"\n ]\n\n @oopish.push new Directory @,\n title: 'Source'\n label: 'src'\n notes: ['Source code for development and build utilities']\n files: [\n new File @,\n title: 'Compiler Helpers'\n label: 'compiler-helpers.js'\n notes: ['Becomes the initializer section at the top of the PEG.js compiler-source']\n editable: true\n value: \"\"\"\n \/\/\/\/ Initializer generated by Develoop\n var someHelper = function () { return 'ok'; };\n\n \"\"\"\n new File @,\n title: 'Compiler Rules'\n label: 'compiler-rules.pegjs'\n notes: ['Becomes the main rules section of the PEG.js compiler-source']\n editable: true\n value: \"\"\"\n \/\/\/\/ Rules generated by Develoop\n string_char 'String Character'\n = \"\\\\\\\\\" char:. { return \"\\\\\\\\\" + char; }\n \/ .\n ;\n\n \"\"\"\n new File @,\n title: 'Highlighter Helpers'\n label: 'highlighter-helpers.js'\n notes: ['Becomes a library section for the AceGrammar highlighter-source']\n editable: true\n value: \"\"\"\n \/\/\/\/ Grammar helpers generated by Develoop 0.0.7\n var someHelper = function () { return 'ok'; };\n\n \"\"\"\n new File @,\n title: 'Highlighter Rules'\n label: 'highlighter-rules.js'\n notes: ['Becomes the main rules section for the AceGrammar highlighter-source']\n editable: true\n value: \"\"\"\n \/\/\/\/ Grammar rules generated by Develoop 0.0.7\n\n modeGrammar = {\n }\n\n \"\"\"\n ]\n\n @oopish.push new Directory @,\n title: 'Test'\n label: 'test'\n notes: ['Source of language unit tests and performance benchmarks']\n files: [\n new File @,\n title: 'Test 01-01: Helper `add()`'\n label: 'test-01-01-add.litcoffee'\n notes: ['Tests for the `add` helper']\n value: \"\"\"\n Test 01-01: Helper `add()`\n ==========================\n\n \"\"\"\n new File @,\n title: 'Test 01-02: Helper `increment()`'\n label: 'test-01-02-inc.litcoffee'\n notes: ['Tests for the `increment` helper']\n value: \"\"\"\n Test 01-02: Helper `increment()`\n ================================\n\n \"\"\"\n new File @,\n title: 'Test 02-01: Language `Markdown`'\n label: 'test-02-01-md.litcoffee'\n notes: ['Tests for the `Markdown` language, as a whole']\n value: \"\"\"\n Test 02-01: Language `Markdown`\n ================================\n\n \"\"\"\n new File @,\n title: 'Test 02-02: Markdown Feature `A`'\n label: 'test-02-02-a.litcoffee'\n notes: ['Tests for the Markdown `A` feature']\n value: \"\"\"\n Test 02-02: Markdown Feature `A`\n ================================\n\n \"\"\"\n ]\n\n @oopish.push new File @,\n title: 'Read Me'\n label: 'README.md'\n notes: ['An introduction to Oopish']\n editable: true\n value: \"\"\"\n Oopish\n ======\n\n A little language which compiles to ES6. \n\n \"\"\"\n\n @oopish.push new File @,\n title: 'Package'\n label: 'package.json'\n notes: ['Metadata about Oopish, in standard NPM format']\n editable: true\n value: \"\"\"\n {\n \"name\": \"oopish\",\n \"version\": \"0.0.1\",\n \"description\": \"A little language which compiles to ES6\",\n \"main\": \"build\/oopish-compiler.js\"\n }\n \"\"\"\n\n\n\n\n##### Example Project\n\n @project.push new Directory @,\n title: 'Build'\n label: 'build'\n notes: ['Destination for compiled project files, so do not edit these files directly']\n files: [\n new File @,\n title: 'My Project'\n label: 'my-project.js'\n notes: ['The standard compiled JavaScript, with comments but no tests']\n value: \"\"\"\n \/\/\/\/ My Project v0.0.1\n\n var abc = 123;\n console.log(abc);\n\n \"\"\"\n new File @,\n title: 'My Project ES6'\n label: 'my-project.es6.js'\n notes: ['Standard compiled ES6 JavaScript, with comments but no tests']\n value: \"\"\"\n \/\/\/\/ My Project v0.0.1\n\n var abc = 123;\n console.log(abc);\n\n \"\"\"\n new File @,\n title: 'Minified My Project'\n label: 'my-project.min.js'\n notes: ['Minified compiled JavaScript, with no comments or test']\n value: \"\"\"\n var abc=123;console.log(abc);\n \"\"\"\n new File @,\n title: 'My Project With Tests'\n label: 'my-project.test.js'\n notes: ['The standard compiled JavaScript, with comments and unit tests']\n value: \"\"\"\n \/\/\/\/ My Project v0.0.1'\n\n var abc = 123;\n console.log(abc);\n\n \/\/\/\/ Some tests in here...\n console.assert(abc, 456);\n\n \"\"\"\n ]\n\n @project.push new Directory @,\n title: 'Documentation'\n label: 'doc'\n notes: ['Project documentation, in Markdown format']\n files: [\n new File @,\n title: 'my_project_md'\n label: 'my-project.md'\n notes: ['An introduction to the MyProject example project']\n value: \"\"\"\n MyProject\n =========\n\n \"\"\"\n ]\n\n @project.push new Directory @,\n title: 'Source'\n label: 'src'\n notes: ['Uncompiled source project files, in the order they should be concatenated']\n files: [\n new File @,\n title: 'Main'\n label: 'Main.oopish.md'\n notes: ['The main point of entry for the program']\n editable: true\n value: \"\"\"\n Main\n ====\n\n abc = 123\n console.log abc\n\n \"\"\"\n new File @,\n title: 'Useful'\n label: 'Useful.oopish.md'\n notes: ['A useful class']\n editable: true\n value: \"\"\"\n Useful\n ======\n\n class Useful\n constructor() ->\n console.log 'The `Useful` class is ok!'\n\n \"\"\"\n ]\n\n @project.push new Directory @,\n title: 'Test'\n label: 'test'\n notes: ['Source of project unit tests and performance benchmarks']\n files: [\n new File @,\n title: 'Test 01: Main'\n label: 'test-01-main.oopish.md'\n notes: ['Tests for the Main class']\n value: \"\"\"\n Test 01: Main\n =============\n\n \"\"\"\n new File @,\n title: 'Test 02: Useful'\n label: 'test-02-useful.oopish.md'\n notes: ['Tests for the Useful class']\n value: \"\"\"\n Test 02: Useful\n ===============\n\n \"\"\"\n ]\n\n @project.push new File @,\n title: 'Read Me'\n label: 'README.md'\n notes: ['An introduction to the project']\n editable: true\n value: \"\"\"\n Example Project\n ===============\n\n An example Develoop project. \n\n \"\"\"\n\n @project.push new File @,\n title: 'Package'\n label: 'package.json'\n notes: ['Metadata about the project, in standard NPM format']\n editable: true\n value: \"\"\"\n {\n \"name\": \"my-project\",\n \"version\": \"0.0.1\",\n \"description\": \"An example Develoop project\",\n \"main\": \"build\/my-project.js\"\n }\n \"\"\"\n\n\nFunctions\n---------\n\n\n#### `xx()`\n- `xx <xx>` Xx \n\nXx. @todo describe\n\n xx = (xx) ->\n\n\n\n","avg_line_length":26.7378277154,"max_line_length":114,"alphanum_fraction":0.4305224821}
{"size":628,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Akaybe Constants\n================\n\n#### Define the core Akaybe constants\n\nAkaybe\u2019s constants are visible to all code defined in \u2018src\/\u2019 and \u2018test\/\u2019, but \nhidden from code defined elsewhere in the app. \n\n\n\n\nConstants which help minification\n---------------------------------\n\nThese strings can make `*.min.js` a little shorter and easier to read, and also \nmake the source code less verbose: `\u00aaO == typeof x` vs `'object' == typeof x`. \n\n \u00aaA = 'array'\n \u00aaB = 'boolean'\n \u00aaE = 'error'\n \u00aaF = 'function'\n \u00aaN = 'number'\n \u00aaO = 'object'\n \u00aaR = 'regexp'\n \u00aaS = 'string'\n \u00aaU = 'undefined'\n \u00aaX = 'null'\n\n\n\n ;\n\n","avg_line_length":19.0303030303,"max_line_length":80,"alphanum_fraction":0.576433121}
{"size":579,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Export Module\n=============\n\n#### The module\u2019s only entry-point is the `Domlet` class\n\nFirst, try defining an AMD module, eg for [RequireJS](http:\/\/requirejs.org\/). \n\n if \u00aaF == typeof define and define.amd\n define -> Domlet\n\nNext, try exporting for CommonJS, eg for [Node.js](http:\/\/goo.gl\/Lf84YI): \n`var Domlet = require('domlet');`\n\n else if \u00aaO == typeof module and module and module.exports\n module.exports = Domlet\n\nOtherwise, add the `Domlet` class to global scope. \nBrowser usage: `var domlet = new window.Domlet();`\n\n else \u00aaG.Domlet = Domlet\n ;\n\n\n\n","avg_line_length":23.16,"max_line_length":78,"alphanum_fraction":0.6580310881}
{"size":14327,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"Node-XLSX-Stream\n================\n\nNode-XLSX-Stream is written in literate coffeescript. The following is the actual source of the \nmodule.\n\n fs = require('fs')\n blobs = require('.\/blobs')\n Archiver = require('archiver')\n numberRegex = \/^[1-9\\.][\\d\\.]+$\/\n\n module.exports = class XlsxWriter\n\n\n\n### Simple writes\n\n##### XlsxWriter.write(out: String, data: Array, cb: Function)\n\nThe simplest way to use Node-XLSX-Stream is to use the write method.\n\nThe callback comes directly from `fs.writeFile` and has the arity `(err)`\n\n # @param {String} out Output file path.\n # @param {Array} data Data to write.\n # @param {Function} cb Callback to call when done. Fed (err).\n @write = (out, data, cb) ->\n writer = new XlsxWriter({out: out})\n writer.addRows(data)\n writer.writeToFile(cb)\n\n### Advanced usage\n\nNode-XLSX-Stream has more advanced features available for better customization\nof spreadsheets.\n\nWhen constructing a writer, pass it an optional file path and customization options.\n\n##### new XlsxWriter([options]: Object) : XlsxWriter\n\n # Build a writer object.\n # @param {Object} [options] Preparation options.\n # @param {String} [options.out] Output file path.\n # @param {Array} [options.columns] Column definition. Must be added in constructor.\n # @example options.columns = [\n # { width: 30 }, \/\/ width is in 'characters'\n # { width: 10 }\n # ]\n constructor: (options = {}) ->\n\n # Support just passing a string path into the constructor.\n if (typeof options == 'string')\n options = {out: options}\n\n # Set options.\n defaults = {\n defaultWidth: 15\n zip: {\n forceUTC: true # this is required, zips will be unreadable without it\n },\n columns: []\n }\n @options = _extend(defaults, options)\n\n # Start sheet.\n @_resetSheet()\n\n # Write column definition.\n @defineColumns(@options.columns)\n\n # Create Zip.\n zipOptions = @options.zip || {}\n zipOptions.forceUTC = true # force this on in all cases for now, otherwise we're useless\n @zip = Archiver('zip', zipOptions)\n\n # Archiver attaches an exit listener on the process, we don't want this,\n # it will fire if this object is never finalized.\n @zip.catchEarlyExitAttached = true\n\n # Hook this passthrough into the zip stream.\n @zip.append(@sheetStream, {name: 'xl\/worksheets\/sheet1.xml'})\n\n#### Adding rows\n\nRows are easy to add one by one or all at once. Data types within the sheet will \nbe inferred from the data types passed to addRow().\n\n##### addRow(row: Object)\n\nAdd a single row.\n\n # @example (javascript)\n # writer.addRow({\n # \"A String Column\" : \"A String Value\",\n # \"A Number Column\" : 12345,\n # \"A Date Column\" : new Date(1999,11,31)\n # })\n addRow: (row) ->\n\n # Values in header are defined by the keys of the object we've passed in.\n # They need to be written the first time they're passed in.\n if !@haveHeader\n @_write(blobs.sheetDataHeader)\n @_startRow()\n col = 1\n for key of row\n @_addCell(key, col)\n @cellMap.push(key)\n col += 1\n @_endRow()\n\n @haveHeader = true\n\n @_startRow()\n for key, col in @cellMap\n @_addCell(row[key] || \"\", col + 1)\n @_endRow()\n\n##### addRows(rows: Array)\n\nRows can be added in batch.\n\n addRows: (rows) ->\n for row in rows\n @addRow(row)\n\n##### defineColumns(columns: Array)\n\nColumn definitions can be easily added, but it *must* be done before rows are added\nto prevent a nasty Excel bug.\n\n # @example (javascript)\n # writer.defineColumns([\n # { width: 30 }, \/\/ width is in 'characters'\n # { width: 10 }\n # ])\n defineColumns: (columns) ->\n if @haveHeader\n throw new Error \"\"\"\n Columns cannot be added after rows! Unfortunately Excel will crash\n if column definitions come after sheet data. Please move your `defineColumns()`\n call before any `addRow()` calls, or define options.columns in the XlsxWriter\n constructor.\n \"\"\"\n @options.columns = columns\n # Write column metadata.\n # Would really like to do this at the end so that we don't have to mandate\n # it comes first, but Excel pukes if <cols> comes before <sheetData>.\n @_write(@_generateColumnDefinition())\n\n\n#### File generation\n\nOnce you are done adding rows & defining columns, you have a few options\nfor generating the file. The `writeToFile` helper is a one-stop-shop for writing\ndirectly to a file using `fs.writeFile`; otherwise, you can pack() manually,\nwhich will return a readable stream.\n\n##### writeToFile([fileName]: String, cb: Function)\n\nWrites data to a file. Convenience method.\n\nIf no filename is specified, will attempt to use the one specified in the\nconstructor as `options.out`.\n\nThe callback is fed directly to `fs.writeFile`.\n\n # @param {String} [fileName] File path to write.\n # @param {Function} cb Callback.\n writeToFile: (fileName, cb) ->\n if fileName instanceof Function\n cb = fileName\n fileName = @options.out\n if !fileName\n throw new Error(\"Filename required. Supply one in writeToFile() or in options.out.\")\n\n # Create zip, pipe it into a file writeStream.\n zip = @createReadStream(fileName)\n fileStream = fs.createWriteStream(fileName)\n fileStream.once 'finish', cb\n zip.pipe(fileStream)\n @finalize()\n\n##### createReadStream() : Stream **Deprecated**\n\n # @return {Stream} Readable stream with ZIP data.\n createReadStream: () ->\n @getReadStream()\n\n##### getReadStream() : Stream\n\nReturns a readable stream from this file. You can pipe this directly to a file\nor response object. Be sure to use 'binary' mode.\n\nYou are responsible for indicating that you have finished\nthe file generation by calling `finalize()`, which will end the sheet stream.\n\n # @return {Stream} Readable stream with ZIP data.\n getReadStream: () ->\n @zip\n\n##### finalize()\n\nFinishes up the sheet & generate shared strings. You must call this manually if\nyou are using `createReadStream`.\n\n finalize: () ->\n\n if @finalized\n throw new Error \"This XLSX was already finalized.\"\n\n # Mark this as finished\n @finalized = true\n\n # If there was data, end sheetData\n if @haveHeader\n @_write(blobs.sheetDataFooter)\n\n # Write relationships data.\n @_write(blobs.worksheetRels(@relationships))\n\n # Generate shared strings\n @_generateStrings()\n\n # Generate external rels\n @_generateRelationships()\n\n # End sheet\n @sheetStream.end(blobs.sheetFooter)\n\n # Add supporting files to zip and finalize it. The readStream (@zip) will soon emit\n # an 'end' event.\n @_finalizeZip()\n\n##### dispose()\n\nCancel use of this writer and close all streams. This is not needed if you've written to a file.\n\n dispose: () ->\n return if @disposed\n\n @sheetStream.end()\n @sheetStream.unpipe()\n @zip.unpipe()\n while(@zip.read()) # drain stream\n 1; # noop\n delete @zip\n delete @sheetStream\n @disposed = true\n\n\n#### Internal methods\n\n\nAdds a cell to the row in progress.\n\n # @param {String|Number|Date} value Value to write.\n # @param {Number} col Column index.\n _addCell: (value = '', col) ->\n row = @currentRow\n cell = @_getCellIdentifier(row, col)\n\n # Hyperlink support\n if Object.prototype.toString.call(value) == '[object Object]'\n if !value.value || !value.hyperlink\n throw new Error(\"A hyperlink cell must have both 'value' and 'hyperlink' keys.\")\n @_addCell(value.value, col)\n @_createRelationship(cell, value.hyperlink)\n return\n\n if typeof value == 'number'\n @rowBuffer += blobs.numberCell(value, cell)\n else if value instanceof Date\n date = @_dateToOADate(value)\n @rowBuffer += blobs.dateCell(date, cell)\n else\n index = @_lookupString(value)\n @rowBuffer += blobs.cell(index, cell)\n\n\n\nBegins a row. Call this before starting any row. Will start a buffer\nfor all proceeding cells, until @_endRow is called.\n\n _startRow: () ->\n @rowBuffer = blobs.startRow(@currentRow)\n @currentRow += 1\n\nEnds a row. Will write the row to the sheet.\n\n _endRow: () ->\n @_write(@rowBuffer + blobs.endRow)\n\n\nGiven row and column indices, returns a cell identifier, e.g. \"E20\"\n\n # @param {Number} row Row index.\n # @param {Number} cell Cell index.\n # @return {String} Cell identifier.\n _getCellIdentifier: (row, col) ->\n colIndex = ''\n if @cellLabelMap[col]\n colIndex = @cellLabelMap[col]\n else\n if col == 0\n # Provide a fallback for empty spreadsheets\n row = 1\n col = 1\n\n input = (+col - 1).toString(26)\n while input.length\n a = input.charCodeAt(input.length - 1)\n colIndex = String.fromCharCode(a + if a >= 48 and a <= 57 then 17 else -22) + colIndex\n input = if input.length > 1 then (parseInt(input.substr(0, input.length - 1), 26) - 1).toString(26) else \"\"\n @cellLabelMap[col] = colIndex\n\n return colIndex + row\n\nCreates column definitions, if any definitions exist.\nThis will write column styles, widths, etc.\n\n # @return {String} Column definition.\n _generateColumnDefinition: () ->\n # <cols\/> tag (empty) crashes excel, weeeeee\n if !@options.columns || !@options.columns.length\n return ''\n\n columnDefinition = ''\n columnDefinition += blobs.startColumns\n\n idx = 1\n for index, column of @options.columns\n columnDefinition += blobs.column(column.width || @options.defaultWidth, idx)\n idx += 1\n\n columnDefinition += blobs.endColumns\n return columnDefinition\n\nGenerates StringMap XML. Used as a finalization step - don't call this while\nbuilding the xlsx is in progress.\n\nSaves string data to this object so it can be written to the zip.\n\n _generateStrings: () ->\n stringTable = ''\n for string in @strings\n stringTable += blobs.string(@escapeXml(string))\n @stringsData = blobs.stringsHeader(@strings.length) + stringTable + blobs.stringsFooter\n\nLooks up a string inside the internal string map. If it doesn't exist, it will be added to the map.\n\n # @param {String} value String to look up.\n # @return {Number} Index within the string map where this string is located.\n _lookupString: (value) ->\n if !@stringMap[value]\n @stringMap[value] = @stringIndex\n @strings.push(value)\n @stringIndex += 1\n return @stringMap[value]\n\nCreate a relationship. For now, this is always a hyperlink. \nThis writes to a array that will later be used define the rels.\n\n _createRelationship: (cell, target) ->\n @relationships.push({cell: cell, target: target})\n\nGenerate external relationships data. This is saved into \"xl\/worksheets\/_rels\/sheet1.xml.rels\".\n\n _generateRelationships: () ->\n @relsData = blobs.externalWorksheetRels(@relationships)\n\nConverts a Date to an OADate.\nSee [this stackoverflow post](http:\/\/stackoverflow.com\/a\/15550284\/2644351)\n\n # @param {Date} date Date to convert.\n # @return {Number} OADate.\n _dateToOADate: (date) ->\n epoch = new Date(1899,11,30)\n msPerDay = 8.64e7\n\n v = -1 * (epoch - date) \/ msPerDay\n\n # Deal with dates prior to 1899-12-30 00:00:00\n dec = v - Math.floor(v)\n\n if v < 0 and dec\n v = Math.floor(v) - dec\n\n return v\n\nConvert an OADate to a Date.\n\n # @param {Number} oaDate OADate.\n # @return {Date} Converted date.\n _OADateToDate: (oaDate) ->\n epoch = new Date(1899,11,30)\n msPerDay = 8.64e7\n\n # Deal with -ve values\n dec = oaDate - Math.floor(oaDate)\n\n if oaDate < 0 and dec\n oaDate = Math.floor(oaDate) - dec\n\n return new Date(oaDate * msPerDay + +epoch)\n\nResets sheet data. Called on initialization.\n\n _resetSheet: () ->\n\n # Sheet data storage.\n @sheetData = ''\n @strings = []\n @stringMap = {}\n @stringIndex = 0\n @stringData = null\n @currentRow = 0\n\n # Cell data storage\n @cellMap = []\n @cellLabelMap = {}\n\n # Column data storage\n @columns = []\n\n # Rels data storage\n @relData = ''\n @relationships = []\n\n # Flags\n @haveHeader = false\n @finalized = false\n\n # Create sheet stream.\n PassThrough = require('stream').PassThrough\n @sheetStream = new PassThrough()\n\n # Start off the sheet.\n @_write(blobs.sheetHeader)\n\nFinalizes this file and adds supporting docs. Should not be called directly.\n\n _finalizeZip: () ->\n @zip\n .append(blobs.contentTypes, {name: '[Content_Types].xml'})\n .append(blobs.rels, {name: '_rels\/.rels'})\n .append(blobs.workbook, {name: 'xl\/workbook.xml'})\n .append(blobs.styles, {name: 'xl\/styles.xml'})\n .append(blobs.workbookRels, {name: 'xl\/_rels\/workbook.xml.rels'})\n .append(@relsData, {name: 'xl\/worksheets\/_rels\/sheet1.xml.rels'})\n .append(@stringsData, {name: 'xl\/sharedStrings.xml'})\n .finalize()\n\nWrapper around writing sheet data.\n\n # @param {String} data Data to write to the sheet.\n _write: (data) ->\n @sheetStream.write(data)\n\nUtility method for escaping XML - used within blobs and can be used manually.\n\n # @param {String} str String to escape.\n escapeXml: (str = '') ->\n return str.replace(\/&\/g, '&amp;')\n .replace(\/<\/g, '&lt;')\n .replace(\/>\/g, '&gt;')\n\nSimple extend helper.\n\n _extend = (dest, src) ->\n for key, val of src\n dest[key] = val\n dest\n","avg_line_length":30.2257383966,"max_line_length":119,"alphanum_fraction":0.6055001047}
{"size":8831,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# Functions\n\nSo, up until now, we've only been able to use basic operations on data. What if we've created a set of statements which performs a useful computation and we want to reuse it? Enter: *functions*.\n\nWith functions we can group statements together into a sort of reusable bundle. To allow functions to operate on different inputs, they are defined using *parameters*. Parameters are simply a set of variables that the function operates on. When you want to use a function you *call* it with a set of *arguments*. The arguments are the values that will be bound to the parameters.\n\nOkay, that was a lot of terminology and probably quite confusing. Let's try to use an existing function, `console.log`.<sup>[1]<\/sup> This function takes a series of strings and outputs them on the *standard output stream*, or `stdout` in short.\n\n console.log 'Hello, World!'\n\nOkay, so that just printed the string right back to us. Seems a lot like just writing the string by itself as a statement, right? No, not at all. As you can see, we also got another response below it: `undefined`. Similar to statements, functions can also return values. In this case the `console.log` function does not have a return value; thus we get `undefined`. So where did the `Hello, World!` output come from?\n\nWhen we're using the REPL we constantly get feedback on what our statements evaluate to. This is not the case if we write our code as a *script*. A script is a file which contains code that can be run by an *interpreter*. The interpreter is the part that is used by the REPL to convert the code that we write into actual instructions that the computer then executes. Actually, this file you're reading right now is a script!\n\nSo, to produce any kind of output from a script, we need to send it somewhere. That is what `stdout` is for! Normally, if you run the script from a terminal, then the text that is sent to `stdout` is printed in the terminal. All other statements will be silent and not result in any output.\n\nMoving on, to fully understand functions, let's create our own. Actually, let's create it in a script. Open a new empty file and save it as `myscript.coffee`. Now, instead of entering the code into the REPL, write it in this file.\n\nSo, say we want a function that calculates the area of a triangle. The function will need to know the width and height of the triangle in order to perform the calculation. We can supply these using parameters. Then it needs to calculate the area and return the result. Here is the function in all its glory:\n\n triangleArea = (width, height) ->\n area = width * height\n area \/= 2\n\nTo understand what's going on, let's break it down a bit. The first part, `triangleArea =`, is just a normal variable assignment. Functions can be used as values and we've chosen to store our function in a variable named `triangleArea`. The rest of the snippet is the actual function definition. The variables within parenthesis, `width` and `height`, are our function parameters. Then comes the `->` symbol that indicates the start of the *function body*.\n\nThe function body is a set of statements, or *code block*, that are executed when the function is called. As you can see, these statements are indented relative to the rest of the code. In most languages, this is done simply to make it easier for the reader to understand which parts of the code belong to the function and which don't. This is *not* the case with CoffeeScript. The indentation here is required for the interpreter to parse the code. Lines that are not indented do not belong to the function, and will not be executed when the function is called.\n\nThe indentation can be accomplished with either tabs or spaces, but be sure to not mix them. Also, if you use spaces, try to use a multiple of 2. If you use different styles of indentation within the same block, the interpreter will fail to parse your code correctly.\n\nThe value that our function returns to the caller is the same as the evaluation of the last statement in the function body. In our case, the last statement is part of the area calculation, so everything is in order. In other cases you might have to write the value that you wish to return on a row by itself at the end of the function. You can also set the return value explicitly with a `return` statement, which causes the function to return to the caller prematurely. This can be very useful when an early abort is desirable to prevent an illegal operation further on in the function.\n\nNow, let's start using our newly created function. We do this by first specifying which function we would like to call, commonly using the variable that refers to the function, and then specifying the arguments that we would like to bind to the function parameters.\n\n triangleArea 10, 20\n\nNote how we separate the arguments with the `,` character. Okay, great! So now we have a reusable function that we can apply to different arguments. Let's try to calculate the area of a few different triangles and print it to the terminal using `console.log`.\n\n area1 = triangleArea 20, 30\n area2 = triangleArea 30, 40\n console.log area1\n console.log area2\n\nTo run the script, first of all, save it, then simply enter the following into your terminal:\n\n```sh\ncoffee myscript.coffee\n```\n\nCool! You've just written your first script! As you can see from the order of the output, the code in the script is executed from the top down. This is the standard flow of execution. But we've already deviated from this flow! When we perform our function calls, we're actually executing code located above the function call itself.\n\nThe function call is the first type of *control flow* statements that we will be introduced to. Later on we will see other types of statements that also modify the execution order of our programs. But, before we move on, there's a few more things you need to know about writing and using functions.\n\nWhat happens when a function doesn't need any arguments? Well, either you just use a pair of empty parenthesis, `()`, in the function definition, or you just skip them completely.\n\n printHello = ->\n console.log 'Hello'\n\nSo how do we call this function then when it doesn't take any arguments? Well, it's done like this:\n\n printHello()\n\nAnd what about when we want to call a function with the result from another function call? Let's try to print both the width, height and area of a triangle with a single statement.\n\n console.log 10, 20, triangleArea 10, 20\n\nOkay, not a problem. But what if we would like to print the area first, followed by the width and height?\n\n console.log triangleArea 10, 20, 10, 20\n\nHmm, that was not really what we intended to do. The problem here is that the inner function call, `triangleArea`, swallowed all of our arguments. The interpreter has no way of knowing which arguments should be passed to the inner function and which should be passed to the outer one. So it ends up sending all of them to the inner one even though it only cares about the two first ones. Yet again, parenthesis solves this disambiguity.\n\n console.log triangleArea(10, 20), 10, 20\n\nAs we mentioned before, functions can be used as values. This allows us to pass a function into another as a *callback*. This can be very useful if you have a function which you do not know how long it takes to complete, but you still want to perform an action upon completion. This situation can arise when we are waiting on user input, or waiting for another process to finish. As always, this concept is easier to grasp when we see it in action.\n\n rest = ->\n console.log 'Phew! That was a lot of work.'\n\n work = (callback) ->\n console.log 'Hard work is HARD.'\n callback()\n\n work rest\n\nOkay, let's break it down. First, we create two functions; `rest` and `work`. The `work` function has a parameter, `callback`, which will be bound to another function. At the end of the `work` function, before returning, we call the function `callback`. Thus, when we call the function `work` with the argument `rest`, we will bind `rest` to the parameter `callback`, resulting in `rest` eventually being called. This can be a bit confusing, so make sure you go through this a few times until you have fully grasped the concept.\n\nWe could, in the last example, also just define the callback function directly, without first storing it in the `rest` variable. Then we would get something like this.\n\n work -> console.log 'Phew! That was a lot of work.'\n\nThat was it for functions. Next up we will learn how to perform different operations under different conditions.\n\n<sub>[1] Actually, console.log is not just a function; it's a method. The difference between functions and methods will be explained in a later chapter, but for now they are pretty much equivalent.<\/sub>\n","avg_line_length":92.9578947368,"max_line_length":587,"alphanum_fraction":0.76559846}
{"size":1946,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"# \/api\/Data Structures\/Batman.Set\/Batman.SetObserver\n\n`Batman.SetObserver` is a utility for observing `Batman.Set`s and their contents (especially if their contents are `Batman.Object`s). It extends `Batman.Object`. In the wild, `Batman.SetProxy` uses a `Batman.SetObserver` to track its base set and `Batman.SetSort` uses item tracking to maintain its order.\n\nA few other points about `Batman.SetObserver`:\n\n- It fires `itemsWereAdded` and `itemsWereRemoved` when its base `Batman.Set` fires those events.\n- When items are added and removed to the base Set, they're automatically observed with `startObservingItems`\/`stopObservingItems` -- you don't have to set that up yourself.\n- Override `observedItemKeys` and `observerForItemAndKey` to track properties of `Batman.Object` members of the set.\n\n## ::constructor(base : Set) : SetObserver\n\nReturns a new `Batman.SetObserver` tracking `base`.\n\n## ::.base : Set\n\nThe set being tracked by the observer.\n\n## ::.observedItemKeys[=[]]: Array\n\nIf you set `observedItemKeys` to an array of strings, those keys will be observed on the members of `base`. When those keys change, the provided observer (see `observerForItemAndKey`) will be called.\n\n## ::observerForItemAndKey(item : Batman.Object, key : String) : Function\n\nWhen you instantiate a `SetObserver`, you should override this function. When the observer starts observing an item, this function will be called for each `key` in `observedItemKeys`. It should return an observer function for `key`. The observer function will be passed `newValue, oldValue`.\n\n## ::startObserving()\n\nStarts observing the `base` and all its members.\n\n## ::stopObserving()\n\nStops observing the `base` and all its members.\n\n## ::startObservingItems(items : Array)\n\nAdds observers for `observedItemKeys` on each item in `items`, calling `observerForItemAndKey` for each key in `observedItemKeys`\n\n## ::stopObservingItems(items : Array)\n\nForgets observers on `items`.\n\n","avg_line_length":45.2558139535,"max_line_length":305,"alphanum_fraction":0.7625899281}
{"size":1430,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"**console.litcoffee** is development console intended to help testing\nPorygonZ.\n\n class exports.Console extends require('events').EventEmitter\n constructor: (@config) ->\n\nI need to call constructor for `EventEmitter`.\n\n super()\n\nStart REPL session with special eval.\n\n connect: ->\n repl = require('repl').start\n eval: (message, context, filename, @callback) =>\n\nI remove parens, because REPL expects JavaScript code, as it was\nintended to be used with JavaScript code. As I still have JavaScript\nmode enabled (because I want tab completion), I have to remove this\nhack from result.\n\n message = message.replace(\/^\\(\/, \"\").replace \/\\n\\)$\/, \"\"\n\nSend the message from REPL to parser.\n\n @emit 'message', user: 'REPL', message: message.replace \/^\\(|\\n\\)$\/g, \"\"\n\nMonkey patch repl in order to have proper tab completion.\n\n repl.complete = (line, callback) =>\n\nIf the command has spaces, don't tab complete.\n\n if line.indexOf(' ') >= 0\n callback null, [[], \"\"]\n return\n\nFilter only commands that begin with actually inserted line.\n\n commands = Object.keys(@container.getCommands()).filter (command) =>\n line is command.substr 0, line.length\n\nUse callback to return results to REPL itself.\n\n callback null, [commands, line]\n\nUse callback to send the message back.\n\n pm: (message) ->\n @callback message\n","avg_line_length":28.0392156863,"max_line_length":84,"alphanum_fraction":0.651048951}
{"size":440,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Param\n=====\n\nA brick which provides a single output, `O`. \n\n\n\n\nDefine the `Param` class\n------------------------\n\n class Param extends Brick\n I: 'Param'\n\n\n\n\nDefine the constructor\n----------------------\n\n constructor: (opt) ->\n super\n @O = 0\n\n\n\n\nDefine public methods\n---------------------\n\n#### `render()`\nXx. \n\n render: -> [\n \".=#{@zeroPad @O, 3}=.\"\n \"| #{@id} O\"\n \"'====='\"\n ]\n\n\n","avg_line_length":10.7317073171,"max_line_length":45,"alphanum_fraction":0.3886363636}
{"size":1284,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"\n# Application Documentation Browser\n\nThis code starts up the application.\n\n## Configure\n\nFirst, include required modules.\n\n express = require 'express'\n\nNext, initialize the application.\n\n app = express()\n\nConfigure Express to serve static files.\n\n app.use express.static('doc')\n app.use express.directory('doc')\n\n## Startup\n\nFinally, start the server.\n\n app.listen 3021\n\n## Copying\n\nThis software is released under the ISC License.\n\nCopyright (c) 2013, Cameron King <cking@ecc12.com>\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<!-- vim: ts=2 sts=2 sw=2 expandtab\n CoffeeScript-friendly tabstops in vim. -->\n","avg_line_length":27.3191489362,"max_line_length":79,"alphanum_fraction":0.7679127726}
{"size":1935,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Pixel\n=====\n\n\n#### An RGB \u2018read point\u2019, used to represent a real-world LED\n\n class Pixel\n C: 'Pixel'\n toString: -> '[object Pixel]'\n\n\n#### `constructor()`\n- `config <object> {}` initial configuration\n - `config.origin <[number]>` @todo describe\n- `<undefined>` does not return anything\n\n@todo describe\n\n constructor: (config={}) ->\n M = '\/shapelydee\/src\/Pixel.litcoffee\n Pixel()\\n '\n\n\nMake `v()`, a function for checking that `config` properties are ok. \n\n v = oo.vObject M, 'config', config\n\n\n\n\nPublic Properties\n-----------------\n\n\n#### `id <string>`\nUnique identifier for this shape. Always begins with 'p', to signify 'pixel'. \n\n @id = 'p' + config.id #@todo validate\n\n\n#### `origin <[number]>`\nCoordinates of the pixel. \n\n @origin = config.origin #@todo validate\n\n\n\n\nPrivate Properties\n------------------\n\nCreate `@[oo._]`, a non-enumerable property with an unguessable name. \n\n oo.define @, oo._, {}, 'private'\n\n\n#### `_x <null>`\n@todo describe\n\n @[oo._]._x = null\n\n\n\n\nPrevent properties being accidentally modified or added to the instance. \n\n if 'Pixel' == @C then oo.lock @\n\n\n\n\nPublic Methods\n--------------\n\n\n#### `xx()`\n- `yy <number> 123` @todo describe\n- `<undefined>` does not return anything\n\n@todo describe\n\n xx: (yy) ->\n M = '\/shapelydee\/src\/Pixel.litcoffee\n Pixel::xx()\\n '\n\nCheck that the arguments are valid, or fallback to defaults if undefined. \n\n yy = oo.vArg M, yy, 'yy <number>', 123\n\n\n\n\nPublic Static Functions\n-----------------------\n\n\n#### `xx()`\n- `yy <number> 123` @todo describe\n- `<undefined>` does not return anything\n\n@todo describe\n\n Pixel.xx = (yy) ->\n M = '\/shapelydee\/src\/Pixel.litcoffee\n Pixel.xx()\\n '\n\nCheck that the arguments are valid, or fallback to defaults if undefined. \n\n yy = oo.vArg M, yy, 'yy <number>', 123\n\n\n\n\n ;\n","avg_line_length":16.8260869565,"max_line_length":78,"alphanum_fraction":0.5689922481}
{"size":1399,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"# The RDB revision controller \n\n 'use strict'\n\n angular.module 'r2rDesignerApp'\n .controller 'RdbReviseCtrl', ($scope, _, Rdb, Rdf) ->\n\n $scope.rdb = Rdb\n $scope.rdf = Rdf\n\n $scope.table = ''\n $scope.columns = []\n\n $scope.$watch 'rdb.selectedTables()', (val) ->\n if val?\n $scope.table = _.first $scope.rdb.selectedTables()\n\n $scope.$watch 'table', (val) ->\n if val?\n $scope.columns = $scope.rdb.selectedColumns()[val]\n\nThe subjectTemplate holds the generator template for the subject URI.\nWith 'insert' you can insert an available column into the template. Curly braces denote columns.\nThis section needs an overhaul.\n\n $scope.selectedColumns = []\n $scope.cursorpos = 0\n $scope.isSelected = (column) -> _.contains $scope.selectedColumns, column\n\n $scope.insert = (column) ->\n if ($scope.isSelected column)\n oldVal = $scope.rdf.subjectTemplate\n $scope.rdf.subjectTemplate = oldVal.replace '{' + column + '}', ''\n $scope.selectedColumns = _.without $scope.selectedColumns, column\n else\n oldVal = $scope.rdf.subjectTemplate\n $scope.rdf.subjectTemplate = (oldVal.slice 0, $scope.cursorpos) + '{' + column + '}' + (oldVal.slice $scope.cursorpos, oldVal.length)\n $scope.selectedColumns.push column\n","avg_line_length":35.8717948718,"max_line_length":145,"alphanum_fraction":0.6054324518}
{"size":2144,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# Types\n\nThe data that a computer uses for its computations is located in memory. Everything in the memory is really just numbers. We can, however, interpret these numbers in different ways. Depending on how you interpret it, the same data might represent a number, a snippet of text or even an image. The most common interpretations can be built into the language itself, as is the case with CoffeeScript. These interpretations are called *types*.\n\nLet's try creating some different types of data. How about we start with some numbers? Open the CoffeeScript REPL with the `coffee` command and type in the following:\n\n 4\n 8\n 15\n 16\n 23\n 42\n\nWe're not just restricted to integers, we can of course represent any real number.<sup>[1]<\/sup>\n\n 0.5\n 123.45\n\nAs you see, after each input the REPL responds by echoing the same number that was entered. Each row you entered is actually a *statement*, a piece of code that the computer executes. The echoed number is actually the result of evaluating the code you just typed. But more on that later, let's create a bit of text, or a *string* as the technical term is.\n\n \"We can write text within double ticks...\"\n '... or single ticks'\n\nAnother type that is very common in programming, but that doesn't have much recognition anywhere else is the *boolean*. Booleans have only two possible values, either `true` or `false`.\n\n true\n false\n\nThese values will come in handy later on when we need our code to react to different circumstances.\n\nThere's one more thing that you will run across, but that's not a data type, and that is *comments*. Comments are not actually part of the code, but simply small pieces of text that the programmer adds to clarify things. The computer will just skip these lines. Comments are created with the `#` charater:\n\n # This is just a comment and will be ignored by the computer\n\nThat's it for data types; next up is operations!\n\n<sub>[1] There are some numbers that can never be represented with [perfect accuracy](http:\/\/en.wikipedia.org\/wiki\/Floating_point#Accuracy_problems) using the standard floating point representation.<\/sub>\n","avg_line_length":56.4210526316,"max_line_length":439,"alphanum_fraction":0.7588619403}
{"size":3022,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# Search and indexing number elements\n\nHandle numbers search queries, extract function and indexing.\n\nThis type of search is specified on http:\/\/hl7-fhir.github.io\/search.html#number.\n\nIn extract_as_number is passed resource, path, element_type and returns\n[numeric](http:\/\/www.postgresql.org\/docs\/9.3\/static\/datatype-numeric.html).\nIn case of multiple elements we return first.\n\nTODO: handle units normalization\nit should be done in an extensible maner\n\n xpath = require('.\/xpath')\n search_common = require('.\/search_common')\n\n TODO = -> throw new Error(\"TODO\")\n\n extract_value = (resource, metas)->\n for meta in metas\n value = xpath.get_in(resource, [meta.path])[0]\n if value\n return {\n value: value\n path: meta.path\n elementType: meta.elementType\n }\n null\n\n exports.fhir_extract_as_number = (plv8, resource, metas)->\n value = extract_value(resource, metas)\n if value\n if value.elementType == 'integer' or value.elementType == 'positiveInt'\n value.value\n else if value.elementType == 'Duration' or value.elementType == 'Quantity'\n value.value.value\n else\n throw new Error(\"extract_as_number: unsupported element type #{value.elementType}\")\n else\n null\n\n exports.fhir_extract_as_number.plv8_signature =\n arguments: ['json', 'json']\n returns: 'numeric'\n immutable: true\n\n SUPPORTED_TYPES = ['integer', 'Quantity', 'positiveInt', 'Duration']\n OPERATORS = ['eq', 'lt', 'le', 'gt', 'ge', 'ne', 'missing']\n\n sf = search_common.get_search_functions({\n extract:'fhir_extract_as_number',\n sort:'fhir_extract_as_number',\n SUPPORTED_TYPES:SUPPORTED_TYPES\n })\n extract_expr = sf.extract_expr\n\n exports.order_expression = sf.order_expression\n exports.index_order = sf.index_order\n\n exports.normalize_operator = (meta, value)->\n if not meta.modifier and not value.prefix\n return 'eq'\n else if meta.modifier == 'missing'\n return 'missing'\n else if OPERATORS.indexOf(value.prefix) > -1\n return value.prefix\n throw new Error(\"Not supported operator #{JSON.stringify(meta)} #{JSON.stringify(value)}\")\n\n exports.handle = (tbl, metas, value)->\n for m in metas\n unless SUPPORTED_TYPES.indexOf(m.elementType) > -1\n throw new Error(\"String Search: unsupported type #{JSON.stringify(m)}\")\n operator = metas[0].operator\n\n op = if operator == 'missing'\n if value.value == 'false' then '$notnull' else '$null'\n else\n \"$#{operator}\"\n\n [op, extract_expr(metas, tbl), value.value]\n\n exports.index = (plv8, metas)->\n meta = metas[0]\n idx_name = \"#{meta.resourceType.toLowerCase()}_#{meta.name.replace('-','_')}_number\"\n\n [\n name: idx_name\n ddl:\n create: 'index'\n name: idx_name\n on: ['$q', meta.resourceType.toLowerCase()]\n expression: [extract_expr(metas)]\n ]\n","avg_line_length":32.1489361702,"max_line_length":96,"alphanum_fraction":0.6369953673}
{"size":277,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":" JsonRenderer = require '.\/json_renderer'\n\n class JsonBlocks extends JsonRenderer\n\n render: (ctx, path, level_name, done) ->\n for step in path\n ctx.push\n x: step.col\n y: step.row\n\n done()\n\n module.exports = JsonBlocks\n","avg_line_length":19.7857142857,"max_line_length":46,"alphanum_fraction":0.5631768953}
{"size":2241,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":26.0,"content":"# GitHub API Example\n\nThis example defines a simple CLI for GitHub. Shred is used to wrap the API in an easy to access client library.\n\nFirst, we require Shred. Since this is an example, we use the relative path to the source. In real life, you'd just do `require \"shred\"`.\n\n {resource} = require \"..\/..\/src\/shred\"\n\nThe only thing Shred exports is the `resource` function, which allows you to define new resources.\n\nLet's define one using the URL for the GitHub API.\n\n module.exports = resource \"https:\/\/api.github.com\/\",\n\nThe second argument to the `resource` function is an object describing the resource. The properties will be the properties or methods of the resulting resource.\n\nIn this case, we're mainly interested in access repositories, so we'll define a property with the name `repo` and pass in an initializer function for it.\n\n repo: (resource) ->\n\nThe `repo` property will give us access to a subresource of our main GitHub API resource. We'll use a URL template to define it.\n\n resource \"repos\/{owner}\/{repo}\/\",\n\nThat will define our `repo` property as a function taking an object with `owner` and `repo` properties. When that function is called it will return the repo subresource. From there, we want to be able to get the `issues` resource, so we'll pass in an interface description accordingly.\n\n issues: (resource) ->\n resource \"issues\",\n\nAt this point, we want to define some request methods for our `issues` resource. So instead of intializer functions to define subresources, we'll pass in an object to describe the request method.\n\n create:\n method: \"post\"\n headers:\n accept: \"application\/vnd.github.v3.raw+json\"\n expect: 201\n\nThis tells Shred that we want to chain a `create` method off our `issues` resource. When called, that method will make a `POST` request with the given headers. We expect a `201 Created` back. Anything else, we'll treat as an error.\n\n list:\n method: \"get\"\n headers:\n accept: \"application\/vnd.github.v3.raw+json\"\n expect: 200\n\nSimilarly, we want to define a `list` method that will make a `GET` request.\n","avg_line_length":47.6808510638,"max_line_length":285,"alphanum_fraction":0.6898705935}
{"size":3327,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":58.0,"content":"GuardedOperation\n================\nCopyright (C) 2015, Bill Burdick, Roy Riggs, TEAM CTHULHU\n\nAn operation with a set of \"guarded\" regions that can fail or cause\nother operations to fail if the guarded regions would be\n\"concurrently\" modified.\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 define ['.\/text-operation', '.\/wrapped-operation'], (OT)->\n {\n TextOperation\n WrappedOperation\n } = OT\n {\n isRetain\n isInsert\n isDelete\n transform\n } = TextOperation\n\n class GuardedOperation extends WrappedOperation\n constructor: (@original, @guards)->\n conflictsWith: (operation)->\n if operation instanceof WrappedOperation then operation = operation.wrapped\n nextGuardStart = @guards[0]\n nextGuardStop = @guards[1]\n guardPos = 2\n cursor = 0\n for op in operation.ops\n if isRetain op\n cursor += op\n while cursor >= nextGuardStop\n if guardPos >= @guards.length then return false\n nextGuardStart = @guards[guardPos++]\n nextGuardStop = @guards[guardPos++]\n else if isDelete op\n cursor -= op\n if nextGuardStart < cursor then return true\n else if nextGuardStart <= cursor < nextGuardStop then return true\n false\n toGuardOp: ->\n op = new TextOperation()\n cursor = 0\n pos = 0\n while pos < @guards.length\n start = @guards[pos++]\n end = @guards[pos++]\n if cursor < start then op.retain start - cursor\n op.insert 'x'\n if cursor < end then op.retain end - cursor\n op.insert 'x'\n if cursor < @baseLength then op.retain @baseLength - cursor\n op\n transform: (refOp)->\n t = WrappedOperation.transform(@original, refOp)[0]\n guardOp = @toGuardOp()\n for conOp in concurrentOperations\n if conOp instanceof WrappedOperation then conOp = conOp.wrapped\n guardOp = transform guardOp, conOp\n new GuardedOperation t, guardsFromOp(guardOp)\n\n guardsFromOp = (op)->\n newGuards = []\n cursor = 0\n pos = 0\n while pos < op.ops.length\n if isRetain op then cursor += op\n else if isInsert op then newGuards.push cursor\n newGuards\n\n OT.GuardedOperation = GuardedOperation\n OT.RejectGuardedOperation = {}\n OT\n","avg_line_length":35.0210526316,"max_line_length":85,"alphanum_fraction":0.6251878569}
{"size":1094,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# Live Changes Manager\n\n Manager = require '.\/Manager'\n\n class LiveChanges extends Manager\n\n register: (resource) -> @subscribe resource if resource.queue is 'live'\n\n subscribe: (resource) ->\n\n { remote, identifier: local, opts } = resource\n\n other = @registry.resources[local]?.find (r) -> r.changes and r.queue is 'live'\n\n return resource.changes = other.changes if other\n\n new Promise (resolve, reject) =>\n\n @queue.add () =>\n\n opts = Object.assign { since: 'now' }, opts, { live: true, include_docs: true }\n\n if resource.seq then opts.since = resource.seq\n\n resource.changes = (new @PouchDB remote).changes opts\n\n resource.changes.on 'change', (info) => @emit 'change', info, local, remote, 'live'\n\n resource.changes.on 'complete', (info) => @emit 'complete', info, local, remote, 'live'\n\n resource.changes.on 'error', (err) => @emit 'error', err, local, remote, 'live'\n\n resolve resource.changes\n\n resource.changes\n\n module.exports = LiveChanges\n","avg_line_length":28.7894736842,"max_line_length":99,"alphanum_fraction":0.6023765996}
{"size":6166,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# `Modules.Account` #\n\n## Usage ##\n\n> ```jsx\n> <Account\n> id=React.PropTypes.number.isRequired\n> myID=React.PropTypes.number.isRequired\n> \/>\n> ```\n> Creates a `Composer` component, which allows a user to compose a post. The accepted properties are:\n> - **`id` [REQUIRED `number`] :**\n> The user id for the account to display.\n> - **`myID` [REQUIRED `number`] :**\n> The user id for the currently logged-in user.\n\n## The Component ##\n\nOur Account only has one property, a number specifying the `id` of the timeline.\n\n Modules.Account = React.createClass\n\n mixins: [ReactPureRenderMixin]\n\n propTypes:\n id: React.PropTypes.number.isRequired\n myID: React.PropTypes.number.isRequired\n\n getInitialState: ->\n account: null\n \n request: null\n\n### Handling the event callback:\n\nWhen we receive a response from Laboratory, we have to handle it with respect to our state.\n\n handleResponse: (event) -> @setState {account: event.detail.response}\n\n### Property change:\n\nIf our `id` property changes then we need to request the new data.\nEssentially we remove our old request and send a new one.\n\n componentWillReceiveProps: (nextProps) ->\n return unless @props.id isnt nextProps.id\n do @request.stop\n @request.removeEventListener \"response\", @handleResponse\n @request = new Laboratory.Profile.Request {id: nextProps.id}\n @request.addEventListener \"response\", @handleResponse\n do @request.start\n\n### Loading:\n\nWhen our account first loads, we should request its data.\n\n componentWillMount: ->\n @request = new Laboratory.Profile.Request {id: @props.id}\n @request.addEventListener \"response\", @handleResponse\n do @request.start\n\n### Unloading:\n\nWhen our account unloads, we should signal that we no longer need its data.\n\n componentWillUnmount: ->\n do @request.stop\n @request.removeEventListener \"response\", @handleResponse\n\n### Rendering:\n\nOur account state is managed by our handlers.\nWe can check to see if they have succeeded in retreiving our data by comparing the `id` of our properties to the `account.id` of our state.\nIf these aren't the same, then our request hasn't yet gone through.\nHowever, we will only prevent rendering if our state `account` is `null`\u2014that is, if no request has gone through.\nOtherwise, we will let the old data stay until our new information is loaded.\n\n render: ->\n return null unless @state.account?\n \u5f41 Modules.Module, {attributes: {id: \"labcoat-account\"}},\n \u5f41 \"header\", {style: {backgroundImage: \"url(#{@state.account.header})\"}},\n \u5f41 \"a\", {src: @state.account.header, target: \"_blank\"}\n \u5f41 Shared.IDCard, {account: @state.account, externalLinks: true}\n switch\n when @state.account.relationship & Laboratory.Profile.Relationship.SELF then null\n when @state.account.relationship & Laboratory.Profile.Relationship.FOLLOWING\n \u5f41 Shared.Button,\n label: \u5f41 ReactIntl.FormattedMessage,\n id: \"account.unfollow\"\n defaultMessage: \"Unfollow\"\n icon: \"icon.unfollow\"\n when @state.account.relationship & Laboratory.Profile.Relationship.BLOCKING\n \u5f41 Shared.Button,\n label: \u5f41 ReactIntl.FormattedMessage,\n id: \"account.blocked\"\n defaultMessage: \"Blocked\"\n icon: \"icon.blocked\"\n disabled: true\n when @state.account.relationship & Laboratory.Profile.Relationship.REQUESTED\n \u5f41 Shared.Button,\n label: \u5f41 ReactIntl.FormattedMessage,\n id: \"account.requested\"\n defaultMessage: \"Request Sent\"\n icon: \"icon.requested\"\n disabled: true\n else\n if @state.account.locked\n \u5f41 Shared.Button,\n label: \u5f41 ReactIntl.FormattedMessage,\n id: \"account.request\"\n defaultMessage: \"Request Follow\"\n icon: \"icon.request\"\n else\n \u5f41 Shared.Button,\n label: \u5f41 ReactIntl.FormattedMessage,\n id: \"account.follow\"\n defaultMessage: \"Follow\"\n icon: \"icon.follow\"\n \u5f41 \"p\",\n dangerouslySetInnerHTML:\n __html: @state.account.bio\n \u5f41 \"footer\", null,\n \u5f41 \"table\", null,\n \u5f41 \"tbody\", null,\n \u5f41 \"tr\", null,\n \u5f41 \"td\", null,\n \u5f41 \"b\", null, @state.account.statusCount\n \u5f41 ReactIntl.FormattedMessage,\n id: \"account.statuses\"\n defaultMessage: \"Posts\"\n \u5f41 \"td\", null,\n \u5f41 \"b\", null, @state.account.followingCount\n \u5f41 ReactIntl.FormattedMessage,\n id: \"account.following\"\n defaultMessage: \"Follows\"\n \u5f41 \"td\", null,\n \u5f41 \"b\", null, @state.account.followerCount\n \u5f41 ReactIntl.FormattedMessage,\n id: \"account.followers\"\n defaultMessage: \"Followers\"\n","avg_line_length":43.7304964539,"max_line_length":139,"alphanum_fraction":0.5038923127}
{"size":245,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# PFM\n\nLoad modules\n\n marked = require 'marked'\n Renderer = require '.\/Renderer'\n\n## Renderer\n\n renderer = new Renderer\n\n### Use the new renderer\n\n marked.setOptions\n renderer: renderer\n\n## Expose\n\n module.exports = marked\n","avg_line_length":12.25,"max_line_length":35,"alphanum_fraction":0.6408163265}
{"size":1095,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"93 Robust Location methods\n==========================\n\n if oo.ROBUSTABLE\n tudor.add [\n \"93 Robust Location methods\"\n tudor.is\n\n\n\n\n \"`browse()` is immutable\"\n\nPrepare a test-instance. \n\n -> [new Location { nestag:new Nestag, coord:'a' }]\n\n\n \"`browse()` is not writable\"\n oo.F\n (location) ->\n location.browse = 123\n location.browse\n\n\n \"`browse()` is not configurable\"\n oo.F\n (location) ->\n try\n Object.defineProperty location, 'browse', { writable:true }\n catch e\n location.browse = 'nope'\n location.browse\n\n\n \"`browse()` cannot be replaced by another method using `prototype`\"\n oo.S\n ->\n Location::browse = -> false\n (new Location { nestag:new Nestag, coord:'a'}).browse() # `new Location` in case `browse='nope'` succeeded\n\n\n \"`browse()` cannot be replaced by another method using direct-access\"\n oo.S\n (location) ->\n location.browse = -> []\n location.browse()\n\n\n\n ];\n\n","avg_line_length":20.6603773585,"max_line_length":116,"alphanum_fraction":0.5168949772}
{"size":9126,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"# \/api\/App Components\/Batman.StorageAdapter\n\n`Batman.StorageAdapter`s handle persistence of [`Batman.Model`s](\/docs\/api\/batman.model.html). Any `Batman.Model` which will be created, read, updated or deleted must have a storage adapter, which is declared with [`Batman.Model@persist`](\/docs\/api\/batman.model.html#class_function_persist):\n\n```coffeescript\nclass App.Superhero extends Batman.Model\n @persist Batman.RestStorage # a StorageAdapter subclass\n```\n\n__Note:__ `@persist` instantiates a StorageAdapter instance during model definition, so it will use `@storageKey` and `@resourceName` from the model where it was instantiated, but it won't play well with inheritance. For example:\n\n```coffeescript\nclass App.Model extends Batman.Model\n @storageKey: 'model'\n @persist Batman.LocalStorage\n\nclass App.Superhero extends App.Model\n # have to do it again here, or else it will use @storageKey of 'model'\n @storageKey: 'superhero'\n @persist Batman.LocalStorage\n```\n\n### Batman's Included StorageAdapters\n\nBatman ships with a few storage adapters to get you up and coding quickly:\n\n- `Batman.LocalStorage` uses [`window.localStorage`](https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Guide\/API\/DOM\/Storage#localStorage) to persist records.\n- `Batman.SessionStorage` extends `Batman.LocalStorage` and uses [`window.sessionStorage`](https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Guide\/API\/DOM\/Storage#sessionStorage) to persist records.\n- `Batman.RestStorage` uses [HTTP REST](http:\/\/en.wikipedia.org\/wiki\/REST) to persist records, mapping HTTP verbs to storage operations and handling HTTP response codes appropriately. _Note: Because `Batman.RestStorage` depends on [`Batman.Request`](\/docs\/api\/batman.request.html), you'll need a [platform library](\/docs\/api\/batman.request.html#platform_request_implementation_libraries) to implement `Batman.Request`._\n- `Batman.RailsStorage` is available as an extra.\n\n\n_Note: Like `Batman.RestStorage`, `Batman.RailsStorage` depends on [`Batman.Request`](\/docs\/api\/batman.request.html), so you'll need a [platform library](\/docs\/api\/batman.request.html#platform_request_implementation_libraries) to implement `Batman.Request`._\n\nIf you're using Batman and Rails, be sure to check out the [batman-rails](https:\/\/github.com\/batmanjs\/batman-rails) gem.\n\n## Storage Errors\n\n`Batman.StorageAdapter` throws [storage errors](\/docs\/api\/batman.storageadapter_errors.html) when its operations fail. You can catch these errors with [`Batman.Controller.catchError`](\/docs\/api\/batman.controller.html#class_function_catcherror).\n\n## Subclassing Batman.StorageAdapter\n\nYou may want to customize Batman's storage operations for your own app, for example:\n\n- Adding before- and after-operation callbacks\n- Overriding default storage operations\n\nTo do this, extend `Batman.StorageAdapter` (or one of the provided subclasses), then use your storage adapter to persist your models.\n```\nclass App.HeroicStorageAdapter extends Batman.LocalStorage\n # filters, overrides\n\nclass App.Superhero extends Batman.Model\n @persist App.HeroicStorageAdapter\n```\n\n## ModelMixin and RecordMixin\n\nA storage adapter may also have a class property called `ModelMixin`. If that property exists, in will be mixed into model classes that are persisted with that adapter. `RecordMixin` works the same way: it will be mixed into the prototype of models that are persisted with this adapter.\n\nFor example, this is how `Batman.RestStorage` provides URL-related functions to models that use it for persistence.\n\n### `env` and `next`\n\nStorage operations and callbacks each take two arguments: `env` and `next`.\n\n`env` is a vanilla JS object which is passed to each function in the chain. `Batman.StorageAdapter` sets these attributes on `env`:\n\n- `env.subject` is the `Batman.Model` record which had the storage operation called on it.\n- `env.options` contains the options passed to the operation on the subject.\n- `env.action` is the storage operation that will be executed by the storage adapter.\n- `env.error` stores any errors that occur during the chain. It becomes the first argument to the operation callback.\n- `env.result` contains the record(s) returned by the operation and should be set by the storage adapter implementation. It becomes the second argument to the operation's callback.\n\nStorage adapters may use `env` to collect any extra information needed by their operations. For example, `Batman.RestStorage` adds some attributes to `env` and `env.options`:\n\n- `env.request` is the `Batman.Request` which implements the storage operation.\n- `env.options.method` is the HTTP method used by `Batman.Request` to implement the storage operation.\n- `env.options.url` is the URL used by `Batman.Request` to implement the storage operation.\n\n`next` is a reference to the next function in the call chain for the current storage operation. `Batman.StorageAdapter` uses this to execute before-filters, storage operations and after-filters in the correct sequence.\n\n\n`next` should be called (`next()`) when the current function has completed. This indicates that the operation should proceed with the next function in its call chain. To ensure the completion of the call chain, consider wrapping your function in [`@skipIfError`](\/docs\/api\/batman.storageadapter.html#class_function_skipiferror).\n\n\n### Adding Callbacks\n\nCallbacks can be registered with [`before`](\/docs\/api\/batman.storageadapter.html#prototype_function_before) and [`after`](\/docs\/api\/batman.storageadapter.html#prototype_function_after) on any storage operation (listed below) or `'all'` (which runs the callback before or after any operation). Callbacks accept two arguments, `env` and `next`, discussed below.\n\n```coffeescript\nclass App.SpecificHeaderStorageAdapter extends Batman.RestStorage\n # include a specific header in all requests:\n @::before 'all', (env, next) ->\n headers = env.options.headers ||= {}\n headers[\"App-Specific-Header\"] = App.getSpecificHeader()\n next()\n\n @::after 'create', (env, next) ->\n console.log \"A #{env.subject.constructor.name} was created!\"\n next()\n```\n\n## Storage Operations\n\nAny `StorageAdapter` must implement these operations as instance methods, for example:\n\n\n```\nclass App.ModifiedStorageAdapter extends Batman.RestStorage\n destroy: (env, next) ->\n # your custom destroy operation\n next()\n```\n\nWhen a record is saved, destroyed or loaded, `Batman.StorageAdapter` invokes these methods. Although you may reimplement them, you probably don't need to call them in your application code.\n\n## ::create(env : Object, next : Function)\nCalled to save a new record. When `save` is called on a record and `isNew` returns `true`, the storage adapter's `create` method is called.\n\n## ::read(env : Object, next : Function)\nCalled to load a record from storage.\n\n## ::update(env : Object, next : Function)\nCalled to update an existing record. When `save` is called on a record and `isNew` returns `false`, the storage adapter's `update` method is called.\n\n## ::destroy(env : Object, next : Function)\nCalled to destroy an existing record.\n\n## ::readAll(env : Object, next : Function)\nCalled to load all records of a particular type from storage.\n\n## Other Useful Methods\n\n## @skipIfError(wrappedFunction : Function )\n\nWraps a function, bypassing the function body and calling next() if an error has already occurred.\n\n test \"StorageAdapter@skipIfError doesn't call the function if env.error?\", ->\n insideFunction = createSpy()\n nextFunction = createSpy()\n\n functionWithWrapper = Batman.LocalStorage.skipIfError (env, next) ->\n insideFunction()\n\n dummyEnv = {error: true}\n\n functionWithWrapper(dummyEnv, nextFunction)\n\n equal dummyEnv.error?, true, 'an error is present'\n equal insideFunction.called, false, 'insideFunction was skipped'\n equal nextFunction.called, true, 'nextFunction was called'\n\nInside a storage adapter definition, this function is referenced as `@skipIfError`, for example:\n\n```\nclass App.SpecialStorageAdapter extends Batman.RestStorage\n @::before 'create', @skipIfError (env, next) ->\n console.log(\"This will be skipped if env.error? is true!\")\n next()\n```\n## ::constructor(model: Function) : StorageAdapter\n\nReturns a `StorageAdapter` attached to `model`, which should be a subclass of `Batman.Model`.\n\n## ::.model : Function\n\nReturns the `Batman.Model` passed to the constructor.\n\n## ::before (keys... : Strings, filter : Function)\nRegisters `filter` as a before-operation callback for the storage operations named by `keys...`.\n\n## ::after (keys... : Strings, filter : Function)\nRegisters `filter` as a after-operation callback for the storage operations named by `keys...`.\n\n## ::getRecordFromData(attributes: Object, constructor[=@model] : Function) : Model\n\nFinds or creates an instance of `constructor` with `attributes` and returns it. Delegated to `Model.createFromJSON`.\n\n## ::getRecordsFromData(attributesArray: Array, constructor[=@model] : Function) : Array\n\nFinds or creates instances of `constructor` for each item in `attributesArray` and returns the resulting records. Delegated to `Model.createMultipleFromJSON`.\n","avg_line_length":49.868852459,"max_line_length":419,"alphanum_fraction":0.7635327635}
{"size":6192,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":"Source maps allow JavaScript runtimes to match running JavaScript back to\nthe original source code that corresponds to it. This can be minified\nJavaScript, but in our case, we're concerned with mapping pretty-printed\nJavaScript back to CoffeeScript.\n\nIn order to produce maps, we must keep track of positions (line number, column number)\nthat originated every node in the syntax tree, and be able to generate a\n[map file](https:\/\/docs.google.com\/document\/d\/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k\/edit)\n\u2014 which is a compact, VLQ-encoded representation of the JSON serialization\nof this information \u2014 to write out alongside the generated JavaScript.\n\n\nLineMap\n-------\n\nA **LineMap** object keeps track of information about original line and column\npositions for a single line of output JavaScript code.\n**SourceMaps** are implemented in terms of **LineMaps**.\n\n class LineMap\n constructor: (@line) ->\n @columns = []\n\n add: (column, [sourceLine, sourceColumn], options={}) ->\n return if @columns[column] and options.noReplace\n @columns[column] = {line: @line, column, sourceLine, sourceColumn}\n\n sourceLocation: (column) ->\n column-- until (mapping = @columns[column]) or (column <= 0)\n mapping and [mapping.sourceLine, mapping.sourceColumn]\n\n\nSourceMap\n---------\n\nMaps locations in a single generated JavaScript file back to locations in\nthe original CoffeeScript source file.\n\nThis is intentionally agnostic towards how a source map might be represented on\ndisk. Once the compiler is ready to produce a \"v3\"-style source map, we can walk\nthrough the arrays of line and column buffer to produce it.\n\n class SourceMap\n constructor: ->\n @lines = []\n\nAdds a mapping to this SourceMap. `sourceLocation` and `generatedLocation`\nare both `[line, column]` arrays. If `options.noReplace` is true, then if there\nis already a mapping for the specified `line` and `column`, this will have no\neffect.\n\n add: (sourceLocation, generatedLocation, options = {}) ->\n [line, column] = generatedLocation\n lineMap = (@lines[line] or= new LineMap(line))\n lineMap.add column, sourceLocation, options\n\nLook up the original position of a given `line` and `column` in the generated\ncode.\n\n sourceLocation: ([line, column]) ->\n line-- until (lineMap = @lines[line]) or (line <= 0)\n lineMap and lineMap.sourceLocation column\n\n\nV3 SourceMap Generation\n-----------------------\n\nBuilds up a V3 source map, returning the generated JSON as a string.\n`options.sourceRoot` may be used to specify the sourceRoot written to the source\nmap. Also, `options.sourceFiles` and `options.generatedFile` may be passed to\nset \"sources\" and \"file\", respectively.\n\n generate: (options = {}, code = null) ->\n writingline = 0\n lastColumn = 0\n lastSourceLine = 0\n lastSourceColumn = 0\n needComma = no\n buffer = \"\"\n\n for lineMap, lineNumber in @lines when lineMap\n for mapping in lineMap.columns when mapping\n while writingline < mapping.line\n lastColumn = 0\n needComma = no\n buffer += \";\"\n writingline++\n\nWrite a comma if we've already written a segment on this line.\n\n if needComma\n buffer += \",\"\n needComma = no\n\nWrite the next segment. Segments can be 1, 4, or 5 values. If just one, then it\nis a generated column which doesn't match anything in the source code.\n\nThe starting column in the generated source, relative to any previous recorded\ncolumn for the current line:\n\n buffer += @encodeVlq mapping.column - lastColumn\n lastColumn = mapping.column\n\nThe index into the list of sources:\n\n buffer += @encodeVlq 0\n\nThe starting line in the original source, relative to the previous source line.\n\n buffer += @encodeVlq mapping.sourceLine - lastSourceLine\n lastSourceLine = mapping.sourceLine\n\nThe starting column in the original source, relative to the previous column.\n\n buffer += @encodeVlq mapping.sourceColumn - lastSourceColumn\n lastSourceColumn = mapping.sourceColumn\n needComma = yes\n\nProduce the canonical JSON object format for a \"v3\" source map.\n\n v3 =\n version: 3\n file: options.generatedFile or ''\n sourceRoot: options.sourceRoot or ''\n sources: options.sourceFiles or ['']\n names: []\n mappings: buffer\n\n v3.sourcesContent = [code] if options.inlineMap\n\n v3\n\n\nBase64 VLQ Encoding\n-------------------\n\nNote that SourceMap VLQ encoding is \"backwards\". MIDI-style VLQ encoding puts\nthe most-significant-bit (MSB) from the original value into the MSB of the VLQ\nencoded value (see [Wikipedia](https:\/\/en.wikipedia.org\/wiki\/File:Uintvar_coding.svg)).\nSourceMap VLQ does things the other way around, with the least significat four\nbits of the original value encoded into the first byte of the VLQ encoded value.\n\n VLQ_SHIFT = 5\n VLQ_CONTINUATION_BIT = 1 << VLQ_SHIFT # 0010 0000\n VLQ_VALUE_MASK = VLQ_CONTINUATION_BIT - 1 # 0001 1111\n\n encodeVlq: (value) ->\n answer = ''\n\n # Least significant bit represents the sign.\n signBit = if value < 0 then 1 else 0\n\n # The next bits are the actual value.\n valueToEncode = (Math.abs(value) << 1) + signBit\n\n # Make sure we encode at least one character, even if valueToEncode is 0.\n while valueToEncode or not answer\n nextChunk = valueToEncode & VLQ_VALUE_MASK\n valueToEncode = valueToEncode >> VLQ_SHIFT\n nextChunk |= VLQ_CONTINUATION_BIT if valueToEncode\n answer += @encodeBase64 nextChunk\n\n answer\n\n\nRegular Base64 Encoding\n-----------------------\n\n BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/'\n\n encodeBase64: (value) ->\n BASE64_CHARS[value] or throw new Error \"Cannot Base64 encode value: #{value}\"\n\n\nOur API for source maps is just the `SourceMap` class.\n\n module.exports = SourceMap\n\n\n\n","avg_line_length":34.2099447514,"max_line_length":96,"alphanum_fraction":0.6690891473}
{"size":8512,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":"YANG Parser\n===========\n\nThis is the CoffeeScript source of a parser for the\n[YANG](http:\/\/tools.ietf.org\/html\/rfc7950 \"RFC 7950\") data modelling\nlanguage.\n\n:exclamation: NOTE: The current implementation only parses\ntext snippets that follow the general YANG lexical structure and turns them into\nJavaScript\/CoffeeScript objects. Additional syntactic and semantic\nvalidation will be implemented later.\n\nThe parser is based on the\n[Comparse](https:\/\/www.npmjs.org\/package\/comparse) library.\n\n P = require('comparse')\n\nFirst, we define a class for YANG statements. The instance variables\nare:\n\n* `prf`: prefix of the keyword (non-empty for extension keywords)\n\n* `kw`: statement keyword\n\n* `arg`: argument\n\n* `substmts`: array of substatements\n\nClass definition\n----------------\n\n class YangStatement\n constructor: (@prf, @kw, @arg, @substmts) ->\n\nComments\n--------\n\nYANG allows two types of comments in C++ style. Line comments start\nwith `\/\/` and extend to the end of line.\n\n lineComment =\n (P.string '\/\/').bind ->\n P.anyChar.manyTill(P.char '\\n').bind (cs) ->\n P.unit cs.join ''\n\nBlock comments are enclosed in `\/*` and `*\/`. They cannot be nested.\n\n blockComment =\n (P.string '\/*').bind ->\n P.anyChar.manyTill(P.string '*\/').bind (cs) ->\n P.unit cs.join ''\n \n comment = lineComment.orElse blockComment\n\nParsers should treat comments as equivalent to a single space\n(RFC\u00a07950,\n[Sec.\u00a014](http:\/\/tools.ietf.org\/html\/rfc7950#section-14)). Hence, we\ndefine two scanners for separators, mandatory and optional, that\npermit any combination of whitespace characters and comments.\n\n # Mandatory separator\n sep = (P.space.orElse comment).skipMany 1\n\n # Optional separator\n optSep = (P.space.orElse comment).skipMany()\n\nKeywords\n--------\n\nIdentifiers in YANG must start with a letter or underline (`_`), other\ncharacters may also be numbers, dash (`-`) or period (`.`). As a\nspecial exception, an identifier must not start with the string whose\nlowercase version matches `xml`.\n\n identifier =\n (P.letter.orElse P.char '_').bind (fst) ->\n (P.alphanum.orElse P.oneOf '.-').many().bind (tail) ->\n res = fst + tail.join ''\n P.unit if res[..2].toLowerCase() is 'xml' then null else res\n\nA keyword is normally an identifier such as `module` or\n`container`. Keywords of extension statements (RFC\u00a07950,\n[Sec. 7.19](http:\/\/tools.ietf.org\/html\/rfc7950#section-7.19)) must\nhave a prefix separated from the statement name with a colon\n(':'). Lexically, a prefix is also an identifier.\n\n keyword =\n (identifier.bind (prf) -> P.char(':').bind ->\n P.unit prf).option().bind (pon) ->\n identifier.bind (kw) ->\n P.unit [pon, kw]\n\nArguments\n---------\n\nBy far, the most difficult task for a YANG lexer is the parsing of\narguments because they can be unquoted, single- or\ndouble-quoted. Moreover, double-quoted strings also follow several\nspecial rules. See\n[Sec.\u00a06.1.3](http:\/\/tools.ietf.org\/html\/rfc7950#section-6.1.3) of\nRFC\u00a07950 for details.\n\nAn unquoted argument must not contain whitespace, semicolon (`;`),\nbraces (`{` or `}`) and opening comment sequences (`\/\/` or `\/*`).\n\n uArg =\n (P.noneOf(\" '\\\"\\n\\t\\r;{}\/\").orElse \\\n P.char('\/').notFollowedBy(P.oneOf '\/*')).concat(1)\n\nOtherwise, an argument is a single- or double-quoted literal strings, or\nmultiple single- or double-quoted strings concatenated with `+`.\n\nA single-quoted literal string is simple\u00a0\u2013 it may contain arbitrary\ncharacters except single quote (`'`). No escape sequences are possible.\n\n sqLit =\n P.sat((c) -> c != \"'\").concat().between(\n P.char(\"'\"), P.char(\"'\"))\n\nA double-quoted string is considerably more complicated. First, it may\ncontain one of four escape sequences representing special characters.\n\n escape = P.char('\\\\').bind ->\n esc =\n 't': '\\t'\n 'n': '\\n'\n '\"': '\"'\n '\\\\': '\\\\'\n P.oneOf('tn\"\\\\').bind((c) -> P.unit esc[c]).orElse fallback\n\nHowever, earlier RFC was underspecified on the escape rules so we\nallow for fallback of accepting any escape sequence unless we detect\nthat the module in question is explicitly 1.1 version.\n\n strict = false\n fallback = P.anyChar.bind (c) ->\n P.unit if strict then null else \"\\\\#{c}\"\n\nThen, a double-quoted string may contain any character except double\nquote (`\"`) or backslash (`\\`), or an escape sequence:\n\n dqChar = P.noneOf('\"\\\\').orElse escape\n\nA double-quoted literal string consisting of multiple lines is subject\nto the following whitespace trimming rules:\n\n* Spaces and tabs immediately preceding a newline character are\n removed.\n\n* In the second and subsequent lines, the leading spaces and tabs are\n are removed up to and including the column of the opening double\n quote character in the first line, or to the first non-whitespace\n character, whichever comes first. In this process, a tab character\n is treated as 8 spaces.\n\nSo, upon encountering the opening double quote, we use the\npredefined `coordinates` parser to find out the\ncolumn in which the double quote occurs.\n\n dqLit =\n P.char('\"').bind -> P.coordinates.bind (col) ->\n dqString col[1]\n\nThen we process the rest of the string up to the next unquoted `\"`\ncharacter and perform whitespace trimming. The column of the opening\ndouble quote is passed to the `dqString` in the `lim` argument.\n\n dqString = (lim) ->\n # This helper function trims the leading whitespace\n trimLead = (str) ->\n left = lim\n sptab = ' '\n i = 0\n while left > 0\n c = str[i++]\n if c == ' '\n left -= 1\n else if c == '\\t'\n return sptab[...8-left] + str[i..] if left < 8\n left -= 8\n else\n return str[(i-1)..]\n str[i..]\n dqChar.manyTill(P.char '\"').bind (cs) ->\n lines = cs.join('').split('\\n')\n # all but first: trim leading whitespace \n tlines = [lines[0]]\n for ln in lines[1..]\n tlines.push trimLead ln\n # all but last: trim trailing whitespace\n res = []\n for ln in tlines[..-2]\n mo = ln.match \/(.*\\S)?\\s*\/\n res.push mo[1]\n res.push tlines.pop()\n P.unit res.join('\\n')\n \nA quoted argument consists of one or more single- or double-quoted\nliteral strings concatenated using the operator `+` (which may be\nsurrounded by whitespace or comments).\n \n qArg = dqLit.orElse(sqLit).bind (lft) ->\n (P.char('+').between(optSep, optSep).bind -> qArg).option().bind (rt) ->\n P.unit lft + rt\n\nAll in all, an argument is unquoted or quoted.\n\n argument = uArg.orElse(qArg)\n\nStatements\n----------\n\nEquipped with the above parsers, we can now easily define a recursive\nparser for a YANG statement, which consists of a keyword, argument,\nand then either a semicolon or a block of substatements. If an\nargument is present, it must be separated from the keyword by\nwhitespace or comment. A separator preceding the semicolon or block is\noptional.\n\nThe result of the `statement` parser is an initialized `YangStatement`\nobject. If no argument is present, the object's `arg` property is set\nto `false`.\n\n statement = keyword.bind (kw) ->\n (sep.bind -> argument).option(false).bind (arg) ->\n strict = true if kw[1] is 'yang-version' and arg is '1.1'\n optSep.bind -> semiOrBlock.bind (sst) ->\n P.unit new YangStatement kw[0], kw[1], arg, sst\n\nA statement block is a sequence of statements enclosed in\nbraces. Whitespace or comments are permitted before or after any\nstatement in the block.\n\n stmtBlock = P.char('{').bind ->\n (optSep.bind -> statement).manyTill optSep.bind -> P.char('}')\n \n semiOrBlock = (P.char(';').bind -> P.unit []).orElse stmtBlock\n\nParsing Function\n----------------\n\nThe public API of this module consists of a single parsing\nfunction named `parse`. It can parse either an entire YANG module or\njust a single statement.\n\nIts arguments are:\n\n* `text`: text to parse,\n\n* `top` (optional): keyword of the top-level statement. If it is not given or has the value of `null`, then any statement is accepted.\n\nThis function is installed in the `module.exports` object so that it\ncan be imported from other modules.\n\n parse = (text, top=null) ->\n yst = statement.between(optSep, optSep).parse text\n if top? and yst.kw != top\n throw P.error \"Wrong top-level statement\", 0\n yst\n \n module.exports = {parse}\n\n","avg_line_length":32.3650190114,"max_line_length":134,"alphanum_fraction":0.6581296992}
{"size":3724,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":2.0,"content":"\nGapiSparql - Main class for GAPI SPARQL component\n\n\n restify = require('restify')\n sparql = require('..\/lib\/sparql')\n #FormatterHtml = require('..\/lib\/formatter_html')\n self = null\n\n class GapiSparql\n\n constructor: (options) ->\n self = @\n @options = options || {}\n @options.debug ?= options.debug || 1\n @options.mode = options.mode || 'simple' # simple | strict\n @options.name = 'gapi-sparql'\n @options.version = '0.0.1'\n @options.host ?= options.host || 'localhost'\n @options.listenPort ?= process.env.PORT || options.port || 5000\n @options.accept = [\n 'text\/html',\n 'text\/csv',\n 'text\/tab-separated-values',\n 'application\/sparql-results+xml',\n 'application\/sparql-results+json'\n ]\n \n @options.formatters = {\n # defaults\n #'text\/plain': (new (require('..\/lib\/formatter_csv'))(@options)).output,\n #'application\/javascript': @errorFormat,\n #'application\/json': @errorFormat,\n #'application\/octet-stream': @errorFormat,\n ##'*\/*': @errorFormat,\n # supported output\n 'text\/html': (new (require('..\/lib\/formatter_html'))(@options)).output,\n 'text\/csv': (new (require('..\/lib\/formatter_csv'))(@options)).output,\n 'text\/tab-separated-values': (new (require('..\/lib\/formatter_tab'))(@options)).output,\n 'application\/sparql-results+xml': (new (require('..\/lib\/formatter_xml'))(@options)).output,\n 'application\/sparql-results+json': (new (require('..\/lib\/formatter_json'))(@options)).output,\n # unsupported output\n '*\/*': (new (require('..\/lib\/formatter_error'))(@options)).output\n }\n\n server = restify.createServer(@options)\n #server.use(restify.acceptParser(server.acceptable));\n #server.pre(restify.pre.sanitizePath())\n server.use(restify.bodyParser())\n server.use(restify.queryParser())\n server.use(restify.urlEncodedBodyParser())\n @server = server\n\n @run: (@argv, @exit) ->\n gapisparql = new GapiSparql(@argv)\n gapisparql.start()\n gapisparql.server.get('\/.*\/', (req, res, next) -> return gapisparql.query('GET', req, res, next))\n gapisparql.server.post('\/.*\/', (req, res, next) -> return gapisparql.query('POST', req, res, next))\n gapisparql.server.put('\/.*\/', (req, res, next) -> return gapisparql.query('PUT', req, res, next))\n gapisparql.server.del('\/.*\/', (req, res, next) -> return gapisparql.query('DELETE', req, res, next))\n \n start: (callback) ->\n @server.listen(@options.listenPort, @options.host, () =>\n console.log('%s listening at %s', @server.name, @server.url) if @options.debug>0\n callback() if callback\n )\n \n stop: (callback) ->\n @server.close( () ->\n callback() if callback\n )\n \n query: (method, req, res, next) ->\n console.log(method+': '+req.url)\n accept = req.accepts(@options.accept)\n if(accept == undefined)\n (new (require('..\/lib\/formatter_error'))(@options)).output(req, res)\n else\n # sparql_query = sparql.parser(@options)\n res.send(404, new restify.ResourceNotFoundError())\n return next()\n \n use: (pluginName) -> \n \n module.exports = GapiSparql","avg_line_length":43.8117647059,"max_line_length":112,"alphanum_fraction":0.5228249194}
{"size":6320,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# Loops\n\nNow we've learnt how to bundle operations and data together with functions and data structures. This allows us to work with computations in a convenient way. But what happens when you have to perform the same computation ten times? Well, we could just write out the same function call ten times over. But what if we it weren't ten times, but a million times? Obviously, there must be a better way to do this.\n\n### Comprehensions\n\nLuckily, performing the same task over and over in rapid succession is something computers really excel at. The construct that is used to repeat a task is called a *loop*. The first type of loop we will try out is the *comprehension*. A comprehension iterates over a given data structure and performs a task for each element. We can create a comprehension with the `for` keyword in combination with either `in` or `of`, depending on the data structure.\n\n eat = (food) ->\n console.log \"Wow! This #{food} is delicious!\"\n\n dishes = ['taco', 'boeuf bourguignon', 'lentil soup']\n eat dish for dish in dishes\n\nThe `for dish in dishes` part is the actual comprehension. We're binding each element of the array `dishes` to a variable, which in this case we chose to call `dish`. The rest of the row, `eat dish`, is the statement which we wish to perform for each element. This uses the postfix form of `for`, but we can also write comprehensions that use code blocks instead, such as in the following snippet.\n\n for dish in dishes\n eat dish\n console.log '*burp*'\n\nSimilarily, we can iterate over objects and their properties the same way by exchanging the `in` for an `of`.\n\n listen = (genre, like) ->\n console.log \"\u266a #{genre} \u266a\"\n if like\n console.log 'I love this song!'\n else\n console.log 'Urgh. What garbage is this?'\n\n genres =\n 'Rock': true\n 'Hip Hop': true\n 'Dubstep': false\n listen genre, like for genre, like of genres\n\nIf you're only interested in the name of the property, and not the value, you can simplify it a bit.\n\n console.log \"I listen to #{genre} music\" for genre of genres\n\nWith comprehensions you can even filter out unwanted elements using the `when` keyword.\n\n console.log \"I like #{genre}\" for genre, like of genres when like\n\nOkay, but what if we just want to repeat something a fixed amount of times instead of iterating an existing data structure? Well, we could use a *range*.\n\n### Ranges\n\nA range in CoffeeScript is the same thing as an interval in mathematics. It is a set of numbers that lie between two endpoints. Ranges are created with square brackets, like arrays, and can be either *inclusive* or *exclusive*. An inclusive range includes the last endpoint while an exclusive range excludes it.\n\n console.log i for i in [10..1]\n console.log i for i in [20...25]\n\nAs you can see, we can start the iteration from either endpoint. Inclusive and exclusive ranges are denoted by `..` and `...` respectively. If we want to change our stride, i.e. the distance between each discrete step of our range, we can do that with the help of the `by` keyword. We don't even need to use integers!\n\n console.log i for i in [0...0.3] by 0.1\n\n### While loops\n\nComprehensions are all well and good when we know beforehand how many times we need to perform an action. But what if this is unknown? When we need to repeat something based on some general condition we can use a `while` loop instead.\n\n haystack = [2, 13, 7, 33, 6, 11]\n needle = 7\n pos = 0\n pos++ while haystack[pos] isnt needle\n console.log \"The number #{needle} was found in position #{pos}\"\n\nThe syntax is simple. After the `while` keyword comes the condition statement. So long as this statement evaluates to `true`, the loop keeps on going. Just like comprehensions, `while` loops can be written with code blocks as well. Similar to `unless`, we also have `until`, which is short for `while not`.\n\n cmds = ['do stuff', 'do stuff', 'quit', 'do stuff']\n pos = 0\n until cmds[pos++] is 'quit'\n console.log 'Work, work!'\n\n### Breaking and skipping\n\nWe've previously mentioned how we can use a `return` statement to prematurely jump out of a function. Similarily, we can use a `break` statement to prematurely jump out of a loop.\n\n for i in [0..5]\n break if i is 3\n console.log i\n\nThis can be useful if we want to abort the processing done in our loop, but still want to execute some cleanup code located further down in our function.\n\nMuch like the `break` statement we can also use the `continue` keyword to skip a single iteration within a loop.\n\n for i in [0..5]\n continue if i is 3\n console.log i\n\n### Caveats\n\nOne thing that we need to be careful of is using asynchronous functions within loops and comprehensions. An example of an asynchronous function is the `setTimeout` function, which takes two parameters; `callback` and `delay`. It will call the `callback` function after approximately `delay` milliseconds. Let's see what happens if we use this in a naive way.\n\n work = (task, callback) ->\n console.log \"Starting task: #{task}\"\n setTimeout callback, 1\n\n tasks = ['rake', 'plant', 'mow']\n for task in tasks\n work task, ->\n console.log \"Completed task: #{task}\"\n\nHuh? We just got three `Completed task: mow` in a row. That is because the `callback` function uses the variable `task` in the comprehension. Since the function `setTimeout` is asynchronous, the comprehension will move to the next element of the array before `callback` can be invoked. In this case, the comprehension managed to finish and therefore the `task` variable got stuck on the last element of the array, `'mow'`, resulting in three identical outputs.\n\nWe can resolve this situation quite easily by binding each iteration to the current value of the `task` variable. The `do` statement helps us with just that by directly invoking the function that is passed to it. The function will then bind its arguments to its parameters and thus the `callback` function will use the correct value of the `task` variable.\n\n for task in tasks\n do (task) ->\n work task, ->\n console.log \"Completed task: #{task}\"\n\nWe've now walked through the last types of control flow statements that we will encounter. Next, we will learn about classes.\n","avg_line_length":55.9292035398,"max_line_length":460,"alphanum_fraction":0.7234177215}
{"size":836,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Helper\n======\n\n@todo describe\n\n\n#### Defines a helpful function, object or value\n\n class Helper\n C: 'Helper'\n toString: -> \"[object Helper]\"\n\n constructor: (@main, config={}) ->\n\n\n#### `label <string>`\nXx. @todo describe\n\n @label = config.label\n\n\n#### `title <string>`\nXx. @todo describe\n\n @title = config.title\n\n\n#### `notes <array of strings>`\nXx. @todo describe\n\n @notes = config.notes\n\n\n#### `value <any>`\nXx. @todo describe\n\n @value = config.value\n\n\n\n\nProperties\n----------\n\n\n#### `xx <xx>`\nXx. @todo describe\n\n @xx = null\n\n\n\n\nInit\n----\n\nInitialize the instance. \n\n @init()\n\n\n\n\nMethods\n-------\n\n\n#### `init()`\n- `xx <xx>` Xx \n\nXx. @todo describe\n\n init: (xx) ->\n\n\n\n\nFunctions\n---------\n\n\n#### `xx()`\n- `xx <xx>` Xx \n\nXx. @todo describe\n\n xx = (xx) ->\n\n\n\n\n ;\n","avg_line_length":8.9892473118,"max_line_length":48,"alphanum_fraction":0.4988038278}
{"size":5904,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":3.0,"content":" MongoQS = require 'mongo-querystring'\n Document = require '.\/model\/Document'\n stringify = require('JSONStream').stringify\n\n collections = require('.\/helper\/schema').types\n sentry = require '.\/db\/sentry'\n mongo = require '@turbasen\/db-mongo'\n\n qs = new MongoQS\n alias:\n tag: 'tags.0'\n gruppe: 'grupper'\n endret: 'after'\n order: 'sort'\n blacklist:\n api_key: true # other use\n sort: true # other use\n limit: true # other use\n skip: true # other use\n fields: true # other use\n expand: true # other use\n _id: true # use API endpoint\n custom:\n bbox: 'geojson'\n near: 'geojson'\n after: 'endret'\n\n## PARAM {collection}\n\n exports.param = (req, res, next, col) ->\n col = decodeURIComponent col\n\n if col not in collections\n return res.status(404).json message: \"Type #{col} not found\"\n\n req.type = col\n req.db = col: mongo[col], query: {}\n\n next()\n\n exports.paramCol2 = (req, res, next, col2) ->\n if col not in collections\n return res.status(404).json message: \"Type #{col2} not found\"\n\n req.type = col2\n req.db.col = mongo[col2]\n req.db.query = [{ status: 'Offentlig' }, { tilbyder: req.user.provider }]\n\n next()\n\n\n## HEAD \/{collection}\n## GET \/{collection}\n\n exports.get = (req, res, next) ->\n\n### Query\n\n req.db.query = req.user.query qs.parse req.query\n\n### Fields\n\nAlways return `endret`, `lisens`, `navn`, `status`, `tilbyder`, and `tags` in\naddition to `\\_id` ObjectID which is always returned by MongoDB.\n\n fields =\n endret: true\n lisens: true\n navn: true\n status: true\n tags: true\n tilbyder: true\n\nParse user specified fields to be returned.\n\n if typeof req.query.fields is 'string' and req.query.fields\n for field in req.query.fields.split ','\n fields[field] = true\n\nIf any private fields are to be returned we need to limit the query to documents\nowner by the API user to prevent exposing private data publicly.\n\n if field.substr(0, 6) is 'privat'\n req.db.query.tilbyder = req.user.provider\n\n### Sort\n\nLimit sort to ascending or descending on `\\_id`, `endret`, and `navn` since they\nare indexed. Non-indexed fields will be slower. Also, don't allow ordering of\ngeospatial queries to prevent performance bottlenecks. From the [MongoDB\nrefference](http:\/\/docs.mongodb.org\/manual\/reference\/operator\/query\/near):\n\n> $near always returns the documents sorted by distance. Any other sort order\n> requires to sort the documents in memory, which can be inefficient.\n\n if not req.db.query.geojson\n sort = switch req.query.sort\n when '_id' then [['_id', 1]]\n when '-_id' then [['_id', -1]]\n when 'endret' then [['endret', 1]]\n when '-endret' then [['endret', -1]]\n when 'navn' then [['navn', 1]]\n when '-navn' then [['navn', -1]]\n else 'endret'\n\n### Execute\n\nMake new cursor object with the correct query, fields, and other options (limit,\nskip, and sort).\n\n cursor = req.db.col.find req.db.query, fields,\n limit: Math.min (parseInt(req.query.limit, 10) or 20), 100\n skip: parseInt(req.query.skip, 10) or 0\n sort: sort\n .maxTimeMS parseInt(process.env.DATABASE_TIMEOUT_MS, 10)\n\nCount number of matching documents in MongoDB database. Ignore limit and skip\nsettings by passing `false` as the first argument to `cursor.count()`.\n\n cursor.count false, (err, total) ->\n if err?.code == 50\n return next code: 503, message: 'Database timeout'\n else if err\n return next err\n\nCalculate the total number of documents that will eventually be returned (not\nthe total number of matching documents) since we don't know that in advanced\n(due to the nature of streaming).\n\n count = Math.min cursor.cmd.limit, Math.max total - cursor.cmd.skip, 0\n\nSet `Count-Return` and `Count-Total` headers so that one can use a `HEAD` query\nto look up the number of matched documents for a query without the documents\nthem selves. This may be useful for statistics purposes.\n\n res.set 'Count-Return', count\n res.set 'Count-Total', total\n\nReturn to the user if this is a `HEAD` query or there are no matching documents.\n\n return res.sendStatus 204 if req.method is 'HEAD'\n return res.json documents: [], count: 0, total: 0 if total is 0\n\nStream matching documents in order to prevent loading them into memory.\n\n res.set 'Content-Type', 'application\/json; charset=utf-8'\n\n op = '{\"documents\":['\n cl = '],\"count\":' + count + ',\"total\":' + total + '}'\n\n cursor.stream().pipe(stringify(op, ',', cl)).pipe(res)\n\n## POST \/{collection}\n\n exports.post = (req, res, next) ->\n if Object.keys(req.body).length is 0\n return res.status(400).json message: 'Body is missing'\n\n if req.body instanceof Array\n return res.status(422).json message: 'Body should be a JSON Hash'\n\n req.body.tilbyder = req.user.provider\n\n new Document(req.type, null).once('error', next).once 'ready', ->\n @insert req.body, (err, warn, data) ->\n if err\n return next(err) if err.name isnt 'ValidationError'\n\n sentry.captureDocumentError req, err\n\n return res.status(422).json\n document: req.body\n message: 'Validation Failed'\n errors: err.details #TODO(starefossen) document this\n\n res.set 'ETag', \"\\\"#{data.checksum}\\\"\"\n res.set 'Last-Modified', new Date(data.endret).toUTCString()\n # res.set 'Location', req.get 'host'\n\n return res.status(201).json\n document: data\n message: 'Validation Warnings' if warn.length > 0\n warnings: warn if warn.length > 0\n","avg_line_length":32.0869565217,"max_line_length":80,"alphanum_fraction":0.6212737127}
{"size":13697,"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 <style>\n body { font-family: sans-serif; }\n a { outline: 0; }\n b { display: inline-block; width: .7em }\n\n b.pass { color: #393 }\n b.fail { color: #bbb }\n article.fail b.pass { color: #bbb }\n section.fail b.pass { color: #bbb }\n\n pre { padding: .5em; margin: .2em 0; border-radius: 4px; }\n pre.fn { background-color: #fde }\n pre.pass { background-color: #cfc }\n pre.fail { background-color: #d8e0e8 }\n\n article { margin-bottom: .5rem }\n article h2 { padding-left:.5rem; margin:0; font-weight:normal }\n article.pass { border-left: 5px solid #9c9 }\n article.fail { border-left: 5px solid #9bf }\n article.fail h2 { margin-bottom: .5rem }\n article.pass >div { display: none }\n\n section { margin-bottom: .5rem }\n section h3 { padding-left: .5rem; margin: 0; }\n section.pass { border-left: 3px solid #9c9 }\n section.fail { border-left: 3px solid #9bf }\n section.fail h3 { margin-bottom: .5rem }\n section.pass >div { display: none }\n\n article.fail section.pass { border-left-color: #ccc }\n\n div { padding-left: .5em; }\n div.fail { border-left: 3px solid #9bf; font-size: .8rem }\n div h4 { margin: 0 }\n div h4 { font: normal .8rem\/1.2rem monaco, monospace }\n div.fail, div.fail h4 { margin: .5rem 0 }\n\n <\/style>\n <h4><a href=\"#end\" id=\"top\">\\u2b07<\/a> #{summary}<\/h4>\n \"\"\"\n @pageFoot = (summary) -> \"\"\"\n <h4><a href=\"#top\" id=\"end\">\\u2b06<\/a> #{summary}<\/h4>\n <script>\n document.title='#{summary.replace \/<\\\/?[^>]+>\/g,''}';\n <\/script>\n \"\"\"\n @articleHead = (heading, fail) ->\n \"<article class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h2>#{if fail then @cross else @tick}#{heading}<\/h2><div>\"\n @articleFoot = '<\/div><\/article>'\n @sectionHead = (heading, fail) ->\n \"<section class=\\\"#{if fail then 'fail' else 'pass'}\\\">\" +\n \"<h3>#{if fail then @cross else @tick}#{heading}<\/h3><div>\"\n @sectionFoot = '<\/div><\/section>'\n @jobFormat = (heading, result) ->\n \"<div class=\\\"#{if result then 'fail' else 'pass'}\\\">\" +\n \"<h4>#{if result then @cross else @tick}#{heading}<\/h4>\" + \n \"#{if result then @formatError result else ''}\" +\n \"<\/div>\"\n @tick = '<b class=\"pass\">\\u2713<\/b> ' # Unicode CHECK MARK\n @cross = '<b class=\"fail\">\\u2718<\/b> ' # Unicode HEAVY BALLOT X\n else\n @pageHead = (summary) -> \"#{summary}\"\n @pageFoot = (summary) -> \"\\n#{summary}\"\n @articleHead = (heading, fail) -> \"\"\"\n \n #{if fail then @cross else @tick} #{heading}\n ===#{new Array(heading.length).join '='}\n\n \"\"\"\n @articleFoot = ''\n @sectionHead = (heading, fail) -> \"\"\"\n\n #{if fail then @cross else @tick} #{heading}\n ---#{new Array(heading.length).join '-'}\n\n \"\"\"\n @sectionFoot = ''\n @jobFormat = (heading, result) ->\n \"#{if result then @cross else @tick} #{heading}\" +\n \"#{if result then '\\n' + @formatError result else ''}\"\n @jobFoot = ''\n @tick = '\\u2713' # Unicode CHECK MARK\n @cross = '\\u2718' # Unicode HEAVY BALLOT X\n\n\n\n\nDefine public methods\n---------------------\n\n#### `add()`\nAdd a new article to the page. An article must contain at least one section. \n\n add: (lines) ->\n\nCreate the `article` object and initialize `runner` and `section`. \n\n article = { sections:[] }\n runner = null\n section = null\n\nRun some basic validation on the `lines` array. \n\n if \u00aaA != \u00aatype lines then throw new Error \"`lines` isn\u2019t an array\"\n if 0 == lines.length then throw new Error \"`lines` has no elements\"\n if \u00aaS != \u00aatype lines[0] then throw new Error \"`lines[0]` isn\u2019t a string\"\n\nAdd the article heading. \n\n article.heading = lines.shift()\n\nStep through each line, populating the `article` object as we go. \n\n i = 0\n while i < lines.length\n line = lines[i]\n switch \u00aatype line\n\nChange the current assertion-runner. \n\n when \u00aaO\n if ! line.runner then throw new Error \"Errant object\" #@todo better error message\n runner = line.runner\n\nRecord a mock-modifier. \n\n when \u00aaF\n section.jobs.push line\n\n when \u00aaS\n\nA string might signify a new assertion in the current section... \n\n if @isAssertion lines[i+1], lines[i+2]\n if ! section then throw new Error \"Cannot add an assertion here\"\n section.jobs.push [\n runner # <function> runner Function to run the assertion\n line # <string> name A short description\n lines[++i] # <mixed> expect Defines success\n lines[++i] # <function> actual Produces the result to test\n ]\n\n...or the beginning of a new section. \n\n else\n section = {\n heading: line\n jobs: []\n }\n article.sections.push section\n\n i++\n\nAppend the article to the `articles` array.\n\n @articles.push article\n\n\n\n\n#### `do()`\nRun the test and return the result. \n\n do: =>\n\nInitialize the output array, as well as `mock` and the page pass\/fail tallies. \n\n pge = []\n mock = null\n pgePass = pgeFail = mockFail = 0\n\n for article in @articles\n art = []\n artPass = artFail = 0\n\n for section in article.sections\n sec = []\n secPass = secFail = 0\n\n for job in section.jobs\n switch \u00aatype job\n when \u00aaF # a mock-modifier\n try mock = job.apply @, mock catch e then error = e.message\n if error\n mockFail++\n secFail++ #@todo does this interfere with proper pass\/fail tally?\n sec.push @formatMockModifierError job, error\n when \u00aaA # in the form `[ runner, heading, expect, actual ]`\n [ runner, heading, expect, actual ] = job # dereference\n result = runner expect, actual, mock # run the test\n if ! result\n sec.push @jobFormat \"#{@sanitize heading}\" \n pgePass++\n artPass++\n secPass++\n else\n sec.push @jobFormat \"#{@sanitize heading}\", result\n pgeFail++\n artFail++\n secFail++\n\n sec.unshift @sectionHead \"#{@sanitize section.heading}\", secFail\n sec.push @sectionFoot\n art = art.concat sec\n\nXx. \n\n art.unshift @articleHead \"#{@sanitize article.heading}\", artFail\n art.push @articleFoot\n pge = pge.concat art\n\nGenerate a page summary message. \n\n summary = if pgeFail\n \"#{@cross} FAILED #{pgeFail}\/#{pgePass + pgeFail}\"\n else\n \"#{@tick} Passed #{pgePass}\/#{pgePass + pgeFail}\"\n if mockFail\n summary = \"\\n#{@cross} (MOCK FAILS)\"\n\nReturn the result as a string, with summary at the start and end. \n\n pge.unshift @pageHead summary\n pge.push @pageFoot summary\n pge.join '\\n'\n\n\n\n\n#### `formatError()`\nFormat an exception or fail result. `result` should be an array with two, three \nor four elements. \n\n formatError: (result) ->\n switch \"#{result.length}-#{@opt.format}\"\n\nTo format an exception, the elements are intro text and an error object. \n\n when '2-html' then \"\"\"\n #{result[0]}\n <pre class=\"fail\">#{@sanitize result[1].message}<\/pre>\n \"\"\"\n when '2-plain' then \"\"\"\n #{result[0]}\n #{@sanitize result[1].message}\n \"\"\"\n\nTo format an normal fail, the elements are 'actual', 'delivery' and 'expected'. \n\n when '3-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]}<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]}<\/pre>\n \"\"\"\n when '3-plain' then \"\"\"\n #{@sanitize @reveal result[0]}\n ...#{result[1]}...\n #{@sanitize @reveal result[2]}\n \"\"\"\n\nA fourth element (of any kind) signifies the fail is just a type-difference. \n\n when '4-html' then \"\"\"\n <pre class=\"fail\">#{@sanitize @reveal result[0]} (#{\u00aatype result[0]})<\/pre>\n ...#{result[1]}...\n <pre class=\"pass\">#{@sanitize @reveal result[2]} (#{\u00aatype result[2]})<\/pre>\n \"\"\"\n when '4-plain' then \"\"\"\n #{@sanitize @reveal result[0]} (#{\u00aatype result[0]})\n ...#{result[1]}...\n #{@sanitize @reveal result[2]} (#{\u00aatype result[2]})\n \"\"\"\n\nAny other number of elements is invalid. \n\n else\n throw new Error \"Cannot process '#{result.length}-#{@opt.format}'\"\n\n\n\n\n#### `formatMockModifierError()`\nFormat an exception message encountered by a mock-modifier function. \n\n formatMockModifierError: (fn, error) ->\n switch @opt.format\n when 'html' then \"\"\"\n <pre class=\"fn\">#{@sanitize fn+''}<\/pre>\n ...encountered an exception:\n <pre class=\"fail\">#{@sanitize error}<\/pre>\n \"\"\"\n else \"\"\"\n #{@sanitize fn+''}\n ...encountered an exception:\n #{@sanitize error}\n \"\"\"\n\n\n\n\n#### `reveal()`\nConvert to string and reveal invisibles. @todo deal with very long strings, reveal [null] etc, ++more\n\n reveal: (value) ->\n value?.toString().replace \/^\\s+|\\s+$\/g, (match) ->\n '\\u00b7' + (new Array match.length).join '\\u00b7'\n\n\n\n\n#### `sanitize()`\nEscape a string for display, depending on the current `format` option.\n\n sanitize: (value) ->\n switch @opt.format\n when 'html'\n value?.toString().replace \/<\/g, '&lt;'\n else\n value\n\n\n\n\n#### `throw()`\nAn assertion-runner which expects `actual()` to throw an exception. \n\n throw:\n runner: (expect, actual, mock) ->\n error = false\n try actual.apply @, mock catch e then error = e\n if ! error\n [ 'No exception thrown, expected', { message:expect } ]\n else if expect != error.message\n [ error.message, 'was thrown, but expected', expect ]\n\n\n\n\n#### `equal()`\nAn assertion-runner which expects `actual()` and `expect` to be equal. \n\n equal: \n runner: (expect, actual, mock) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != result\n if result+'' == expect+''\n [ result, 'was returned, but expected', expect, true ]\n else\n [ result, 'was returned, but expected', expect ]\n\n\n\n\n#### `is()`\nAn assertion-runner which expects `\u00aatype( actual() )` and `expect` to be equal. \n\n is: \n runner: (expect, actual, mock) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if expect != \u00aatype result\n [ \"type #{\u00aatype result}\", 'was returned, but expected', \"type #{expect}\" ]\n\n\n\n\n#### `match()`\nAn assertion-runner where `expect` is a regexp, or an object containing a \n`test()` method. \n\n match: \n runner: (expect, actual, mock) ->\n error = false\n try result = actual.apply @, mock catch e then error = e\n if error\n [ 'Unexpected exception', error ]\n else if \u00aaF != typeof expect.test\n [ '`test()` is not a function', { message:expect } ]\n else if ! expect.test ''+result\n [ ''+result, 'failed test', expect ]\n\n\n\n\n#### `isAssertion()`\nXx. @todo\nNote brackets around `\u00aaO == \u00aatype line1`, which makes this conditional behave \nas expected! \n\n isAssertion: (line1, line2) ->\n if \u00aaF != \u00aatype line2 then return false\n if (\u00aaO == \u00aatype line1) && \u00aaF == \u00aatype line1.runner then return false\n true\n\n\n\n\nInstantiate the `tudor` object\n------------------------------\n\nCreate an instance of `Tudor`, to add assertions to. \n\n tudor = new Tudor\n format: if \u00aaO == typeof window then 'html' else 'plain'\n\n\nExpose Tudor\u2019s `do()` function as a module method, so that any consumer of \nthis module can run its assertions. In Node.js, for example: \n`require('winlet').runTest();`\n\n Winlet.runTest = tudor.do\n ;\n\n\n\n","avg_line_length":30.5055679287,"max_line_length":101,"alphanum_fraction":0.5043440169}
{"size":14952,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Node-XLSX-Stream\n================\n\nNode-XLSX-Stream is written in literate coffeescript. The following is the actual source of the\nmodule.\n\n fs = require('fs')\n blobs = require('.\/blobs')\n Archiver = require('archiver')\n\n module.exports = class XlsxWriter\n\n\n\n### Simple writes\n\n##### XlsxWriter.write(out: String, data: Array, cb: Function)\n\nThe simplest way to use Node-XLSX-Stream is to use the write method.\n\nThe callback comes directly from `fs.writeFile` and has the arity `(err)`\n\n # @param {String} out Output file path.\n # @param {Array} data Data to write.\n # @param {Function} cb Callback to call when done. Fed (err).\n @write = (out, data, cb) ->\n writer = new XlsxWriter({out: out})\n writer.addRows(data)\n writer.writeToFile(cb)\n\n### Advanced usage\n\nNode-XLSX-Stream has more advanced features available for better customization\nof spreadsheets.\n\nWhen constructing a writer, pass it an optional file path and customization options.\n\n##### new XlsxWriter([options]: Object) : XlsxWriter\n\n # Build a writer object.\n # @param {Object} [options] Preparation options.\n # @param {String} [options.out] Output file path.\n # @param {Array} [options.columns] Column definition. Must be added in constructor.\n # @example options.columns = [\n # { width: 30 }, \/\/ width is in 'characters'\n # { width: 10 }\n # ]\n constructor: (options = {}) ->\n\n # Support just passing a string path into the constructor.\n if (typeof options == 'string')\n options = {out: options}\n\n # Set options.\n defaults = {\n defaultWidth: 15\n zip: {\n forceUTC: true # this is required, zips will be unreadable without it\n },\n columns: []\n }\n @options = _extend(defaults, options)\n\n # Start sheet.\n @_resetSheet()\n\n # Write column definition.\n @defineColumns(@options.columns)\n\n # Create Zip.\n zipOptions = @options.zip || {}\n zipOptions.forceUTC = true # force this on in all cases for now, otherwise we're useless\n @zip = Archiver('zip', zipOptions)\n\n # Archiver attaches an exit listener on the process, we don't want this,\n # it will fire if this object is never finalized.\n @zip.catchEarlyExitAttached = true\n\n # Hook this passthrough into the zip stream.\n @zip.append(@sheetStream, {name: 'xl\/worksheets\/sheet1.xml'})\n\n#### Add SheetDataHeader\n\nSimply add known header to resulting stream.\nShould be used in conjunction with low-level api: _startRow, _addCell, endRow\n\n##### _addSheetDataHeader: ()\n\nAdd SheetDataHeader to resulting stream.\n\n # @example (javascript)\n # writer._addSheetDataHeader()\n _addSheetDataHeader: () ->\n if !@haveHeader\n @_write(blobs.sheetDataHeader)\n @haveHeader = true\n\n\n#### Adding rows\n\nRows are easy to add one by one or all at once. Data types within the sheet will\nbe inferred from the data types passed to addRow().\n\n##### addRow(row: Object)\n\nAdd a single row.\n\n # @example (javascript)\n # writer.addRow({\n # \"A String Column\" : \"A String Value\",\n # \"A Number Column\" : 12345,\n # \"A Date Column\" : new Date(1999,11,31)\n # \"A DateTime Column\": {value: new Date(), formatAsDateTime: true},\n # })\n addRow: (row) ->\n\n # Values in header are defined by the keys of the object we've passed in.\n # They need to be written the first time they're passed in.\n if !@haveHeader\n @_write(blobs.sheetDataHeader)\n @_startRow()\n col = 1\n for key of row\n @_addCell(key, col)\n @cellMap.push(key)\n col += 1\n @_endRow()\n\n @haveHeader = true\n\n @_startRow()\n for key, col in @cellMap\n @_addCell(row[key] || \"\", col + 1)\n @_endRow()\n\n\n\n##### addRows(rows: Array)\n\nRows can be added in batch.\n\n addRows: (rows) ->\n for row in rows\n @addRow(row)\n\n##### defineColumns(columns: Array)\n\nColumn definitions can be easily added, but it *must* be done before rows are added\nto prevent a nasty Excel bug.\n\n # @example (javascript)\n # writer.defineColumns([\n # { width: 30 }, \/\/ width is in 'characters'\n # { width: 10 }\n # ])\n defineColumns: (columns) ->\n if @haveHeader\n throw new Error \"\"\"\n Columns cannot be added after rows! Unfortunately Excel will crash\n if column definitions come after sheet data. Please move your `defineColumns()`\n call before any `addRow()` calls, or define options.columns in the XlsxWriter\n constructor.\n \"\"\"\n @options.columns = columns\n # Write column metadata.\n # Would really like to do this at the end so that we don't have to mandate\n # it comes first, but Excel pukes if <cols> comes before <sheetData>.\n @_write(@_generateColumnDefinition())\n\n\n#### File generation\n\nOnce you are done adding rows & defining columns, you have a few options\nfor generating the file. The `writeToFile` helper is a one-stop-shop for writing\ndirectly to a file using `fs.writeFile`; otherwise, you can pack() manually,\nwhich will return a readable stream.\n\n##### writeToFile([fileName]: String, cb: Function)\n\nWrites data to a file. Convenience method.\n\nIf no filename is specified, will attempt to use the one specified in the\nconstructor as `options.out`.\n\nThe callback is fed directly to `fs.writeFile`.\n\n # @param {String} [fileName] File path to write.\n # @param {Function} cb Callback.\n writeToFile: (fileName, cb) ->\n if fileName instanceof Function\n cb = fileName\n fileName = @options.out\n if !fileName\n throw new Error(\"Filename required. Supply one in writeToFile() or in options.out.\")\n\n # Create zip, pipe it into a file writeStream.\n zip = @createReadStream(fileName)\n fileStream = fs.createWriteStream(fileName)\n fileStream.once 'finish', cb\n zip.pipe(fileStream)\n @finalize()\n\n##### createReadStream() : Stream **Deprecated**\n\n # @return {Stream} Readable stream with ZIP data.\n createReadStream: () ->\n @getReadStream()\n\n##### getReadStream() : Stream\n\nReturns a readable stream from this file. You can pipe this directly to a file\nor response object. Be sure to use 'binary' mode.\n\nYou are responsible for indicating that you have finished\nthe file generation by calling `finalize()`, which will end the sheet stream.\n\n # @return {Stream} Readable stream with ZIP data.\n getReadStream: () ->\n @zip\n\n##### finalize()\n\nFinishes up the sheet & generate shared strings. You must call this manually if\nyou are using `createReadStream`.\n\n finalize: () ->\n\n if @finalized\n throw new Error \"This XLSX was already finalized.\"\n\n # Mark this as finished\n @finalized = true\n\n # If there was data, end sheetData\n if @haveHeader\n @_write(blobs.sheetDataFooter)\n\n # Write relationships data.\n @_write(blobs.worksheetRels(@relationships))\n\n # Generate shared strings\n @_generateStrings()\n\n # Generate external rels\n @_generateRelationships()\n\n # End sheet\n @sheetStream.end(blobs.sheetFooter)\n\n # Add supporting files to zip and finalize it. The readStream (@zip) will soon emit\n # an 'end' event.\n @_finalizeZip()\n\n##### dispose()\n\nCancel use of this writer and close all streams. This is not needed if you've written to a file.\n\n dispose: () ->\n return if @disposed\n\n @sheetStream.end()\n @sheetStream.unpipe()\n @zip.unpipe()\n while(@zip.read()) # drain stream\n 1; # noop\n delete @zip\n delete @sheetStream\n @disposed = true\n\n\n#### Internal methods\n\n\nAdds a cell to the row in progress.\n\n # @param {String|Number|Date} value Value to write.\n # @param {Number} col Column index.\n _addCell: (value = '', col) ->\n row = @currentRow\n cell = @_getCellIdentifier(row, col)\n\n # Hyperlink support\n if Object.prototype.toString.call(value) == '[object Object]'\n if value.formatAsDateTime\n date = @_dateToOADate(value.value)\n @rowBuffer += blobs.dateTimeCell(date, cell)\n return\n\n if !value.value || !value.hyperlink\n throw new Error(\"A hyperlink cell must have both 'value' and 'hyperlink' keys.\")\n @_addCell(value.value, col)\n @_createRelationship(cell, value.hyperlink)\n return\n\n if typeof value == 'number'\n @rowBuffer += blobs.numberCell(value, cell)\n else if value instanceof Date\n date = @_dateToOADate(value)\n @rowBuffer += blobs.dateCell(date, cell)\n else\n index = @_lookupString(value)\n @rowBuffer += blobs.cell(index, cell)\n\n\n\nBegins a row. Call this before starting any row. Will start a buffer\nfor all proceeding cells, until @_endRow is called.\n\n _startRow: (ht) ->\n @rowBuffer = blobs.startRow(@currentRow, ht)\n @currentRow += 1\n\nEnds a row. Will write the row to the sheet.\n\n _endRow: () ->\n @_write(@rowBuffer + blobs.endRow)\n\n\nGiven row and column indices, returns a cell identifier, e.g. \"E20\"\n\n # @param {Number} row Row index.\n # @param {Number} cell Cell index.\n # @return {String} Cell identifier.\n _getCellIdentifier: (row, col) ->\n colIndex = ''\n if @cellLabelMap[col]\n colIndex = @cellLabelMap[col]\n else\n if col == 0\n # Provide a fallback for empty spreadsheets\n row = 1\n col = 1\n\n input = (+col - 1).toString(26)\n while input.length\n a = input.charCodeAt(input.length - 1)\n colIndex = String.fromCharCode(a + if a >= 48 and a <= 57 then 17 else -22) + colIndex\n input = if input.length > 1 then (parseInt(input.substr(0, input.length - 1), 26) - 1).toString(26) else \"\"\n @cellLabelMap[col] = colIndex\n\n return colIndex + row\n\nCreates column definitions, if any definitions exist.\nThis will write column styles, widths, etc.\n\n # @return {String} Column definition.\n _generateColumnDefinition: () ->\n # <cols\/> tag (empty) crashes excel, weeeeee\n if !@options.columns || !@options.columns.length\n return ''\n\n columnDefinition = ''\n columnDefinition += blobs.startColumns\n\n idx = 1\n for index, column of @options.columns\n columnDefinition += blobs.column(column.width || @options.defaultWidth, idx)\n idx += 1\n\n columnDefinition += blobs.endColumns\n return columnDefinition\n\nGenerates StringMap XML. Used as a finalization step - don't call this while\nbuilding the xlsx is in progress.\n\nSaves string data to this object so it can be written to the zip.\n\n _generateStrings: () ->\n stringTable = ''\n for string in @strings\n stringTable += blobs.string(@escapeXml(string))\n @stringsData = blobs.stringsHeader(@strings.length) + stringTable + blobs.stringsFooter\n\nLooks up a string inside the internal string map. If it doesn't exist, it will be added to the map.\n\n # @param {String} value String to look up.\n # @return {Number} Index within the string map where this string is located.\n _lookupString: (value) ->\n if !@stringMap[value]\n @stringMap[value] = @stringIndex\n @strings.push(value)\n @stringIndex += 1\n return @stringMap[value]\n\nCreate a relationship. For now, this is always a hyperlink.\nThis writes to a array that will later be used define the rels.\n\n _createRelationship: (cell, target) ->\n @relationships.push({cell: cell, target: target})\n\nGenerate external relationships data. This is saved into \"xl\/worksheets\/_rels\/sheet1.xml.rels\".\n\n _generateRelationships: () ->\n @relsData = blobs.externalWorksheetRels(@relationships)\n\nConverts a Date to an OADate.\nSee [this stackoverflow post](http:\/\/stackoverflow.com\/a\/15550284\/2644351)\n\n # @param {Date} date Date to convert.\n # @return {Number} OADate.\n _dateToOADate: (date) ->\n epoch = new Date(1899,11,30)\n msPerDay = 8.64e7\n\n v = -1 * (epoch - date) \/ msPerDay\n\n # Deal with dates prior to 1899-12-30 00:00:00\n dec = v - Math.floor(v)\n\n if v < 0 and dec\n v = Math.floor(v) - dec\n\n return v\n\nConvert an OADate to a Date.\n\n # @param {Number} oaDate OADate.\n # @return {Date} Converted date.\n _OADateToDate: (oaDate) ->\n epoch = new Date(1899,11,30)\n msPerDay = 8.64e7\n\n # Deal with -ve values\n dec = oaDate - Math.floor(oaDate)\n\n if oaDate < 0 and dec\n oaDate = Math.floor(oaDate) - dec\n\n return new Date(oaDate * msPerDay + +epoch)\n\nResets sheet data. Called on initialization.\n\n _resetSheet: () ->\n\n # Sheet data storage.\n @sheetData = ''\n @strings = []\n @stringMap = {}\n @stringIndex = 0\n @stringData = null\n @currentRow = 0\n\n # Cell data storage\n @cellMap = []\n @cellLabelMap = {}\n\n # Column data storage\n @columns = []\n\n # Rels data storage\n @relData = ''\n @relationships = []\n\n # Flags\n @haveHeader = false\n @finalized = false\n\n # Create sheet stream.\n PassThrough = require('stream').PassThrough\n @sheetStream = new PassThrough()\n\n # Start off the sheet.\n @_write(blobs.sheetHeader)\n\nFinalizes this file and adds supporting docs. Should not be called directly.\n\n _finalizeZip: () ->\n @zip\n .append(blobs.contentTypes, {name: '[Content_Types].xml'})\n .append(blobs.rels, {name: '_rels\/.rels'})\n .append(blobs.workbook, {name: 'xl\/workbook.xml'})\n .append(blobs.styles, {name: 'xl\/styles.xml'})\n .append(blobs.workbookRels, {name: 'xl\/_rels\/workbook.xml.rels'})\n .append(@relsData, {name: 'xl\/worksheets\/_rels\/sheet1.xml.rels'})\n .append(@stringsData, {name: 'xl\/sharedStrings.xml'})\n .finalize()\n\nWrapper around writing sheet data.\n\n # @param {String} data Data to write to the sheet.\n _write: (data) ->\n @sheetStream.write(data)\n\nUtility method for escaping XML - used within blobs and can be used manually.\n\n # @param {String} str String to escape.\n escapeXml: (str = '') ->\n return str.replace(\/&\/g, '&amp;')\n .replace(\/<\/g, '&lt;')\n .replace(\/>\/g, '&gt;')\n\nSimple extend helper.\n\n _extend = (dest, src) ->\n for key, val of src\n dest[key] = val\n dest\n","avg_line_length":30.0240963855,"max_line_length":119,"alphanum_fraction":0.6077447833}
{"size":64,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"## Messages\n\n- sender, caller, definer, this, methodName, args\n\n","avg_line_length":12.8,"max_line_length":49,"alphanum_fraction":0.703125}
{"size":1661,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"# plane\n\nA plane is an object containing:\n\n- normal: A vector specifying the facing direction of the plane.\n- distance: A number specifying how far from 0, 0, 0 along the normal the plane \n is.\n\n vector = require \".\/vector.litcoffee\"\n tempA = []\n tempB = []\n\n## fromTriangle\n\n- A vector specifying the location of the first vertex.\n- A vector specifying the location of the second vertex.\n- A vector specifying the location of the third vertex.\n- An existing object to populate, else, falsy.\n\nThe populated object is returned.\n\n fromTriangle = (a, b, c, output) ->\n output = output or {}\n output.normal = output.normal or []\n vector.subtract.vector a, b, tempA\n vector.subtract.vector a, c, tempB\n vector.cross tempB, tempA, output.normal\n vector.normalize output.normal, output.normal\n output.distance = vector.dot output.normal, a\n output\n \n## distance\n\n- A plane.\n- A vector.\n\nReturns the distance between the plane and the vector. Negative when behind the\nplane.\n\n distance = (plane, input) -> (vector.dot plane.normal, input) - plane.distance\n \n## project\n\n- A plane.\n- An input vector.\n- An output vector.\n\nProjects the input vector onto the surface of the plane, travelling along its\nnormal to find the closest point, and writes that point to the output vector.\n \n project = (plane, input, output) ->\n dist = distance plane, input\n vector.multiply.scalarBy dist, plane.normal, tempA\n vector.subtract.vector input, tempA, output\n return\n \n module.exports = {\n fromTriangle\n distance\n project\n }","avg_line_length":27.2295081967,"max_line_length":82,"alphanum_fraction":0.6634557495}
{"size":912,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":" initialAccounts = [['bill', 'bill.png'], ['gilan', 'gilan.png'], ['roy'], ['rotem'], ['shlomi']]\n\n init = ->\n maze = new Meteor.Collection 'maze'\n # for now, always toast the database on start\n maze.remove {}\n map = JSON.parse Assets.getText 'map2.json'\n map._id = 'world'\n maze.insert map\n if !(maze.findOne 'master')\n for [n, image] in initialAccounts\n console.log \"creating account:\", n\n try\n profile = name: n\n if image? then profile.image = image\n Accounts.createUser\n username: n\n password: n\n email: \"#{n}@#{n}\"\n profile: profile\n catch\n maze.insert\n _id: 'master'\n #players seems to be obsolete\n players: []\n else console.log \"Maze already exists\"\n Meteor.publish 'maze', -> maze.find()\n\n init()\n","avg_line_length":30.4,"max_line_length":100,"alphanum_fraction":0.5175438596}
{"size":123,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"Which of the following variable names are valid?\n\n* `abc`\n* `ABC`\n* `abc123`\n* `abc_123`\n* `123abc`\n* `a1b2c3`\n","avg_line_length":13.6666666667,"max_line_length":48,"alphanum_fraction":0.5772357724}
{"size":6191,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":27.0,"content":"Source maps allow JavaScript runtimes to match running JavaScript back to\nthe original source code that corresponds to it. This can be minified\nJavaScript, but in our case, we're concerned with mapping pretty-printed\nJavaScript back to CoffeeScript.\n\nIn order to produce maps, we must keep track of positions (line number, column number)\nthat originated every node in the syntax tree, and be able to generate a\n[map file](https:\/\/docs.google.com\/document\/d\/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k\/edit)\n\u2014 which is a compact, VLQ-encoded representation of the JSON serialization\nof this information \u2014 to write out alongside the generated JavaScript.\n\n\nLineMap\n-------\n\nA **LineMap** object keeps track of information about original line and column\npositions for a single line of output JavaScript code.\n**SourceMaps** are implemented in terms of **LineMaps**.\n\n class LineMap\n constructor: (@line) ->\n @columns = []\n\n add: (column, [sourceLine, sourceColumn], options={}) ->\n return if @columns[column] and options.noReplace\n @columns[column] = {line: @line, column, sourceLine, sourceColumn}\n\n sourceLocation: (column) ->\n column-- until (mapping = @columns[column]) or (column <= 0)\n mapping and [mapping.sourceLine, mapping.sourceColumn]\n\n\nSourceMap\n---------\n\nMaps locations in a single generated JavaScript file back to locations in\nthe original CoffeeScript source file.\n\nThis is intentionally agnostic towards how a source map might be represented on\ndisk. Once the compiler is ready to produce a \"v3\"-style source map, we can walk\nthrough the arrays of line and column buffer to produce it.\n\n class SourceMap\n constructor: ->\n @lines = []\n\nAdds a mapping to this SourceMap. `sourceLocation` and `generatedLocation`\nare both `[line, column]` arrays. If `options.noReplace` is true, then if there\nis already a mapping for the specified `line` and `column`, this will have no\neffect.\n\n add: (sourceLocation, generatedLocation, options = {}) ->\n [line, column] = generatedLocation\n lineMap = (@lines[line] or= new LineMap(line))\n lineMap.add column, sourceLocation, options\n\nLook up the original position of a given `line` and `column` in the generated\ncode.\n\n sourceLocation: ([line, column]) ->\n line-- until (lineMap = @lines[line]) or (line <= 0)\n lineMap and lineMap.sourceLocation column\n\n\nV3 SourceMap Generation\n-----------------------\n\nBuilds up a V3 source map, returning the generated JSON as a string.\n`options.sourceRoot` may be used to specify the sourceRoot written to the source\nmap. Also, `options.sourceFiles` and `options.generatedFile` may be passed to\nset \"sources\" and \"file\", respectively.\n\n generate: (options = {}, code = null) ->\n writingline = 0\n lastColumn = 0\n lastSourceLine = 0\n lastSourceColumn = 0\n needComma = no\n buffer = \"\"\n\n for lineMap, lineNumber in @lines when lineMap\n for mapping in lineMap.columns when mapping\n while writingline < mapping.line\n lastColumn = 0\n needComma = no\n buffer += \";\"\n writingline++\n\nWrite a comma if we've already written a segment on this line.\n\n if needComma\n buffer += \",\"\n needComma = no\n\nWrite the next segment. Segments can be 1, 4, or 5 values. If just one, then it\nis a generated column which doesn't match anything in the source code.\n\nThe starting column in the generated source, relative to any previous recorded\ncolumn for the current line:\n\n buffer += @encodeVlq mapping.column - lastColumn\n lastColumn = mapping.column\n\nThe index into the list of sources:\n\n buffer += @encodeVlq 0\n\nThe starting line in the original source, relative to the previous source line.\n\n buffer += @encodeVlq mapping.sourceLine - lastSourceLine\n lastSourceLine = mapping.sourceLine\n\nThe starting column in the original source, relative to the previous column.\n\n buffer += @encodeVlq mapping.sourceColumn - lastSourceColumn\n lastSourceColumn = mapping.sourceColumn\n needComma = yes\n\nProduce the canonical JSON object format for a \"v3\" source map.\n\n v3 =\n version: 3\n file: options.generatedFile or ''\n sourceRoot: options.sourceRoot or ''\n sources: options.sourceFiles or ['']\n names: []\n mappings: buffer\n\n v3.sourcesContent = [code] if options.inlineMap\n\n v3\n\n\nBase64 VLQ Encoding\n-------------------\n\nNote that SourceMap VLQ encoding is \"backwards\". MIDI-style VLQ encoding puts\nthe most-significant-bit (MSB) from the original value into the MSB of the VLQ\nencoded value (see [Wikipedia](http:\/\/en.wikipedia.org\/wiki\/File:Uintvar_coding.svg)).\nSourceMap VLQ does things the other way around, with the least significat four\nbits of the original value encoded into the first byte of the VLQ encoded value.\n\n VLQ_SHIFT = 5\n VLQ_CONTINUATION_BIT = 1 << VLQ_SHIFT # 0010 0000\n VLQ_VALUE_MASK = VLQ_CONTINUATION_BIT - 1 # 0001 1111\n\n encodeVlq: (value) ->\n answer = ''\n\n # Least significant bit represents the sign.\n signBit = if value < 0 then 1 else 0\n\n # The next bits are the actual value.\n valueToEncode = (Math.abs(value) << 1) + signBit\n\n # Make sure we encode at least one character, even if valueToEncode is 0.\n while valueToEncode or not answer\n nextChunk = valueToEncode & VLQ_VALUE_MASK\n valueToEncode = valueToEncode >> VLQ_SHIFT\n nextChunk |= VLQ_CONTINUATION_BIT if valueToEncode\n answer += @encodeBase64 nextChunk\n\n answer\n\n\nRegular Base64 Encoding\n-----------------------\n\n BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/'\n\n encodeBase64: (value) ->\n BASE64_CHARS[value] or throw new Error \"Cannot Base64 encode value: #{value}\"\n\n\nOur API for source maps is just the `SourceMap` class.\n\n module.exports = SourceMap\n\n\n\n","avg_line_length":34.2044198895,"max_line_length":96,"alphanum_fraction":0.669035697}
{"size":544,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"Config\n======\n\n\tpkg = require '..\/package.json'\n\trandomToken = require 'random-token'\n\n\tmodule.exports = {\n\t\tsessionSecret: randomToken 16\n\n\t\tapp_id: pkg.name\n\n\t\tapp_url: 'http:\/\/\u00c9NV:app_host'\n\n\t\tdata: {\n\n\t\t\tadapters: {\n\t\t\t\tdefault: require 'sails-mongo'\n\t\t\t\tmongo: require 'sails-mongo'\n\t\t\t}\n\n\t\t\tconnections: {\n\t\t\t\tmongo: {\n\t\t\t\t\tadapter: 'mongo'\n\t\t\t\t\thost: \"\u00c9NV:mongo_host\",\n\t\t\t\t\tport: 27017,\n\t\t\t\t\tuser: \"\u00c9NV:mongo_user\",\n\t\t\t\t\tpassword: \"\u00c9NV:mongo_password\",\n\t\t\t\t\tdatabase: pkg.name\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdefaults: {\n\t\t\t\tmigrate: 'alter'\n\t\t\t}\n\t\t}\n\n\t}","avg_line_length":14.7027027027,"max_line_length":37,"alphanum_fraction":0.5863970588}
{"size":3051,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"# node-http-status\n\n**Reference:** \nhttp:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html \nhttp:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec6.html#sec6.1.1\n\n module.exports =\n\n## Informational 1xx\nRequest received, continuing process\n\n 100: 'Continue'\n 101: 'Switching Protocols'\n\n## Successful 2xx\nThe action was successfully received, understood, and accepted\n\n 200: 'OK'\n 201: 'Created'\n 202: 'Accepted'\n 203: 'Non-Authoritative Information'\n 204: 'No Content'\n 205: 'Reset Content'\n 206: 'Partial Content'\n\n## Redirection 3xx\nFurther action must be taken in order to complete the request\n\n 300: 'Multiple Choices'\n 301: 'Moved Permanently'\n 302: 'Found'\n 303: 'See Other'\n 304: 'Not Modified'\n 305: 'Use Proxy'\n 307: 'Temporary Redirect'\n\n## Client Error 4xx\nThe request contains bad syntax or cannot be fulfilled\n\n 400: 'Bad Request'\n 401: 'Unauthorized'\n 402: 'Payment Required'\n 403: 'Forbidden'\n 404: 'Not Found'\n 405: 'Method Not Allowed'\n 406: 'Not Acceptable'\n 407: 'Proxy Authentication Required'\n 408: 'Request Time-out'\n 409: 'Conflict'\n 410: 'Gone'\n 411: 'Length Required'\n 412: 'Precondition Failed'\n 413: 'Request Entity Too Large'\n 414: 'Request-URI Too Large'\n 415: 'Unsupported Media Type'\n 416: 'Requested range not satisfiable'\n 417: 'Expectation Failed'\n\n## Server Error 5xx\nThe server failed to fulfill an apparently valid request\n\n 500: 'Internal Server Error'\n 501: 'Not Implemented'\n 502: 'Bad Gateway'\n 503: 'Service Unavailable'\n 504: 'Gateway Time-out'\n 505: 'HTTP Version not supported'\n\n## Informational 1xx\nRequest received, continuing process\n\n CONTINUE: 100\n SWITCHING_PROTOCOLS: 101\n\n## Successful 2xx\nThe action was successfully received, understood, and accepted\n\n OK: 200\n CREATED: 201\n ACCEPTED: 202\n NON_AUTHORITATIVE_INFORMATION: 203\n NO_CONTENT: 204\n RESET_CONTENT: 205\n PARTIAL_CONTENT: 206\n\n## Redirection 3xx\nFurther action must be taken in order to complete the request\n\n MULTIPLE_CHOICES: 300\n MOVED_PERMANENTLY: 301\n FOUND: 302\n SEE_OTHER: 303\n NOT_MODIFIED: 304\n USE_PROXY: 305\n # Unused: 306 (reserved)\n TEMPORARY_REDIRECT: 307\n\n## Client Error 4xx\nThe request contains bad syntax or cannot be fulfilled\n\n BAD_REQUEST: 400\n UNAUTHORIZED: 401\n PAYMENT_REQUIRED: 402\n FORBIDDEN: 403\n NOT_FOUND: 404\n METHOD_NOT_ALLOWED: 405\n NOT_ACCEPTABLE: 406\n PROXY_AUTHENTICATION_REQUIRED: 407\n REQUEST_TIMEOUT: 408\n CONFLICT: 409\n GONE: 410\n LENGTH_REQUIRED: 411\n PRECONDITION_FAILED: 412\n REQUEST_ENTITY_TOO_LARGE: 413\n REQUEST_URI_TOO_LONG: 414\n UNSUPPORTED_MEDIA_TYPE: 415\n REQUESTED_RANGE_NOT_SATISFIABLE: 416\n EXPECTATION_FAILED: 417\n\n## Server Error 5xx\nThe server failed to fulfill an apparently valid request\n\n INTERNAL_SERVER_ERROR: 500\n NOT_IMPLEMENTED: 501\n BAD_GATEWAY: 502\n SERVICE_UNAVAILABLE: 503\n GATEWAY_TIMEOUT: 504\n HTTP_VERSION_NOT_SUPPORTED: 505\n","avg_line_length":23.6511627907,"max_line_length":62,"alphanum_fraction":0.7017371354}
{"size":2214,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":1.0,"content":"The plugin that can be used for telling others stuff, when they are\naway. Because it needs to have persistent state, it requires any sort\nof database.\n\n tell = (message) ->\n\nLoad prepared schema from database.\n\n {TellMessage} = @database.models\n\nIf the message contains just command, it's just useless, because it\ndoesn't even mention the target.\n\n unless message\n @respond \"You need to specify target and content\"\n\nI need to use external module in order to split, because otherwise\ntoo much would be split. The split limits in JavaScript, while\nexisting, are completely broken, because they simple eat what you\ndon't need.\n\n [target, content] = require('strsplit') message, \/\\s+\/, 2\n\nIf there is no content specified, automatically write something.\n\n content or= \"You know what I mean.\"\n\n TellMessage.findOne where: {user: @response.user, target}, (err, message) =>\n\nThe message could either exist or not. If it exists, then modify its\ninstance, instead of creating new message.\n\n message or= new TellMessage\n message.user = @response.user\n message.target = target\n message.content = content\n message.save()\n\n @respond \"I will tell #{target} about this.\"\n\n tell.help = \"Tells somebody about something. The first argument is\" +\n \" user name, second is what you want to say him.\"\n\nDefine schemas for initial processing.\n\n tell.schemas =\n TellMessage:\n user:\n type: String\n index: yes\n target:\n type: String\n index: yes\n content:\n type: String\n date:\n type: Date\n default: Date.now\n\n exports.tell = ->\n tell\n\n exports.tellCheck = -> (type, {user}) ->\n return unless user? and type in ['message', 'channel', 'join']\n\nCheck if the message exists, and respond if it does. Because this remembers\nthe context, it's safe to use it in event.\n\n @database.models.TellMessage.findOne where: target: user, (err, message) =>\n return unless message?\n {user, target, content, date} = message\n @respond \"<#{user}> #{target}, #{content}\"\n\nRemove the message if it was mentioned.\n\n message.destroy()\n","avg_line_length":28.7532467532,"max_line_length":82,"alphanum_fraction":0.6558265583}
{"size":2060,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Akaybe Helpers\n==============\n\n#### Define the core Akaybe helper functions\n\nAkaybe\u2019s helper functions are visible to all code defined in \u2018src\/\u2019 and \u2018test\/\u2019 \nbut are hidden from code defined elsewhere in the runtime environment. \n\n- Helpers are \u2018pure\u2019 (they return the same output for a given set of arguments)\n- They have no side-effects, other than throwing exceptions\n- They run identically in all modern environments (browser, server, desktop, \u2026)\n- Each Akaybe helper function minifies to 1024 bytes or less\n\n\n\n\n#### `\u00aa()`\nA handy shortcut for `console.log()`. Note [`bind()`](http:\/\/goo.gl\/66ffgl). \n\n \u00aa = console.log.bind console\n\n\n\n\n#### `\u00aaex()`\nExchanges a character from one set for its equivalent in another. To decompose \nan accent, use `\u00aaex(c, '\u00e0\u00e1\u00e4\u00e2\u00e8\u00e9\u00eb\u00ea\u00ec\u00ed\u00ef\u00ee\u00f2\u00f3\u00f6\u00f4\u00f9\u00fa\u00fc\u00fb\u00f1\u00e7', 'aaaaeeeeiiiioooouuuunc')`\n\n \u00aaex = (x, a, b) ->\n if -1 == pos = a.indexOf x then x else b.charAt pos\n\n\n\n\n#### `\u00aahas()`\nDetermines whether haystack contains a given needle. @todo arrays and objects\n\n \u00aahas = (h, n, t=true, f=false) ->\n if -1 != h.indexOf n then t else f\n\n\n\n\n#### `\u00aatype()`\nTo detect the difference between 'null', 'array', 'regexp' and 'object' types, \nwe use [Angus Croll\u2019s one-liner](http:\/\/goo.gl\/WlpBEx). This can be used in \nplace of JavaScript\u2019s familiar `typeof` operator, with one important exception: \nwhen the variable being tested does not exist, `typeof foobar` will return \n`undefined`, whereas `\u00aatype(foobar)` will throw an error. \n\n \u00aatype = (x) ->\n ({}).toString.call(x).match(\/\\s([a-z0-9]+)\/i)[1].toLowerCase()\n\n\n\n\n#### `\u00aauid()`\nXx optional prefix. @todo description\n\n \u00aauid = (p) ->\n p + '_' + (Math.random()+'1111111111111111').slice 2, 18\n\n\n\n\n#### `\u00aaredefine()`\nConvert a property to one of XX kinds:\n\n- `'constant'` Enumerable but immutable\n\n \u00aaredefine = (obj, name, value, kind) ->\n switch kind\n when 'constant'\n Object.defineProperty obj, name, { value:value, enumerable:true }\n when 'private'\n Object.defineProperty obj, name, { value:value, enumerable:false }\n\n\n\n\n\n","avg_line_length":25.1219512195,"max_line_length":80,"alphanum_fraction":0.6621359223}
{"size":9732,"ext":"litcoffee","lang":"Literate CoffeeScript","max_stars_count":null,"content":"Context menu for cytoscape\n==========================\n\n# Features\n1. context sensitive menu\n2. can customize menu filter\n3. add dynamic menu item\n4. support nested menu\n5. self contained. no other dependencies\n\n### (if you want see diagram(or uml) in this document on chrome browser. you must install https:\/\/github.com\/callin2\/plantUML_everywhere )\n\ncss\n\n #require('.\/CxtMenu.css');\n\nmodule name\n\n MODULE_NAME = \"cyto-cxt-menu\"\n\n# Option\n```uml\n@startsalt\n{\n{T\n + Option\n ++ menuSelectHandler : [Function]\n ++ menu : [Menu]\n +++ name : [String]\n +++ viewWhen : [Boolean\\|String\\|Function] optional default true\n +++ onselect : [Function] optional\n +++ submenu : [Array<Menu>] optional\n}\n}\n@endsalt\n```\n\n## menuSelectHandler:\n- type : `(event: {menuName: string, target: element}) => void`\n- \uba54\ub274\ub97c \uc120\ud0dd\ud588\uc744\ub54c \ud638\ucd9c\ub418\ub294 event handler. \uc5b4\ub5a4 \uba54\ub274\ub97c \uc120\ud0dd\ud574\ub3c4 \ud56d\uc0c1 \ud638\ucd9c\ub41c\ub2e4. \uadf8\ub798\uc11c event\uc5d0 `menuName`\uc744 \ud3ec\ud568\ud558\uace0 \uc788\ub2e4.\n\n## menu:\n- type `string` | `object` | `promise<menu>` | `(cy)=>menu`\n - `string`\n - string\uc778 \uacbd\uc6b0 `menuSelectHandler`\ub97c \ubc18\ub4dc\uc2dc \uc124\uc815\ud574\uc57c \ud55c\ub2e4. \uadf8\ub807\uc9c0 \uc54a\uc73c\uba74 \uba54\ub274\ub9cc \ud45c\uc2dc\ub418\uace0 \uba54\ub274\ub97c \uc120\ud0dd\ud574\ub3c4 \uc544\ubb34\uc77c\ub3c4 \uc77c\uc5b4\ub098\uc9c0 \uc54a\ub294\ub2e4.\n \uac12\uc774 4\uc790\ub9ac \uc774\uc0c1 \uc5f0\uc18d\ub41c `-` \uc778 \uacbd\uc6b0 divider\ub97c \ud45c\uc2dc\ud55c\ub2e4. `object` type\uc73c\ub85c \ud45c\ud604\ud560 \uacbd\uc6b0 `{ name: string}` \uacfc \ub3d9\uc77c\ud558\ub2e4\n - `object`\n - \uae30\ubcf8\uc801\uc778 \uba54\ub274 \ub370\uc774\ud0c0\uad6c\uc870\uc774\ub2e4. `name`\ub9cc \ud544\uc218\uc774\uace0 \ub098\uba38\uc9c0\ub294 \uc0dd\ub7b5 \uac00\ub2a5\ud558\ub2e4.\n - `.name`: `string` \uba54\ub274\uc774\ub984 \ud544\uc218\ud56d\ubaa9\n - `.viewWhen`: `boolean|string|({target, cy})=>boolean` \uc6b0\ud074\ub9ad \ud588\uc744\ub54c \uba54\ub274\uac00 \ud45c\uc2dc\ub420\uc9c0 \ub9d0\uc9c0 \uacb0\uc815\n - `boolean` : true\uba74 \uba54\ub274\ub97c \ud45c\uc2dc false\uba74 \ud45c\uc2dc\ud558\uc9c0 \uc54a\uc74c\n - `string` : cytoscape selector \ub85c \uc0ac\uc6a9. \uc774\ubca4\ud2b8\uac00 \ubc1c\uc0dd\ud55c target element\uac00 selector \ud45c\ud604\uc5d0 \ud574\ub2f9\ud558\uba74 \uba54\ub274\ud45c\uc2dc \uc544\ub2c8\uba74 \ud45c\uc2dc\uc548\ud568.\n - `({target, cy})=>boolean` : function\ud638\ucd9c \uacb0\uacfc\uac00 true \uc774\uba74 \uba54\ub274\ud45c\uc2dc \uc544\ub2c8\uba74 \ud45c\uc2dc\uc548\ud568.\n - `.onselect`: `(event)=>void` optional\n - \uba54\ub274\uac00 \uc120\ud0dd\ub418\uc5c8\uc744\ub54c onselect\uc5d0 \uc124\uc815\ub41c \ud568\uc218\ub97c \ud638\ucd9c\ud574 \uc900\ub2e4.\n - `.submenu` : `menu[] | promise<menu[]> | (event)=>menu[] ` optional\n - ``\n - `promise<menu>`\n - menu \ub97c resolve \ud558\ub294 promise. ajax \ud638\ucd9c \uacb0\uacfc\ub97c \uac00\uc9c0\uace0 menu\ub97c \ud45c\uc2dc\ub97c \ud558\ub294\uacbd\uc6b0 \uc720\uc6a9\ud558\ub2e4.\n - `(cy)=>menu`\n - `menu`\ub97c return \ud558\ub294 \ud568\uc218. \ub3d9\uc801\uc73c\ub85c menu\ub97c \ud45c\uc2dc\ud574\uc57c \ud560\uacbd\uc6b0 \uc720\uc6a9\ud558\ub2e4.\n\n# Option \uae30\ubcf8\uac12\n\n defaultOption = {\n menuSelectHandler: (evt) -> console.log 'context menu selected!',evt\n menu: {\n name: \"----\",\n submenu: [\n \"menu #1\"\n \"----\"\n {name: \"menu #2\", onselect: (evt)-> console.log evt, 'hello from menu #2'}\n {\n name: \"node\", viewWhen: 'node', submenu: [\n \"node submenu #1\"\n \"node submenu #2\"\n ]\n }\n {\n name: \"edge\", viewWhen: ((evt)-> evt.target.isEdge?() ), submenu: -> [\n \"edge submenu #1\"\n \"edge submenu #2\"\n ]\n }\n ]\n }\n }\n\nutility functions from http:\/\/youmightnotneedjquery.com\/\n\n removeDomElem = (el) -> el.parentNode.removeChild(el)\n hasClass = (el, clsName) -> el.classList.contains(clsName)\n toggleClass = (el, clsName) -> el.classList.toggle(clsName)\n addClass = (el, clsName) -> el.classList.add clsName\n removeClass = (el, clsName) -> el.classList.remove(clsName)\n show = (el) -> el.style.display = ''\n hide = (el) -> el.style.display = 'none'\n parents = (el, selector) -> if el.parentNode?.matches(selector) then el.parentNode else parents(el.parentNode, selector)\n offset = (el) ->\n rect = el.getBoundingClientRect();\n {\n top: rect.top + document.body.scrollTop,\n left: rect.left + document.body.scrollLeft\n }\n\n isPromise = (obj)->!!obj && (typeof obj == 'object' || typeof obj == 'function') && typeof obj.then == 'function'\n\nfor UMD. borrowed from https:\/\/gist.github.com\/bcherny\/6567138\n\n UMD = (fn) ->\n if typeof exports is 'object'\n module.exports = fn\n else if typeof define is 'function' and define.amd\n define(MODULE_NAME, -> fn)\n else\n @[MODULE_NAME] = fn(cytoscape ? null)\n\ncytoscape\uc5d0 \uc775\uc2a4\ud150\uc158\uc744 \ub4f1\ub85d\ud558\ub294\ub370 \uc0ac\uc6a9\ub418\ub294 \ud568\uc218\n\n register = (cytoscape)->\n return if not cytoscape\n\n cytoscape 'core', \"cxtMenu\", (options = null) ->\n cy = @\n if options\n cy.scratch(MODULE_NAME)?.destroy?()\n cy.scratch(MODULE_NAME, new CxtMenu(cy, options))\n return cy.scratch(MODULE_NAME)\n\n\ub808\uc9c0\uc2a4\ud130 \ud568\uc218\ub97c UMD \ubaa8\ub4c8\ub85c \ub4f1\ub85d\n\n UMD register\n\ncontext menu class\n\n class CxtMenu\n\n constructor: (@cy, options) ->\n @options = Object.assign({}, defaultOption, options)\n @options.menuTemplate ?= @_mkMenuContent\n #console.log(\"@cy.container().parentNode\", @cy.container().parentNode)\n\n @cxtMenuRootElem = document.createElement('div')\n document.body.appendChild(@cxtMenuRootElem)\n addClass @cxtMenuRootElem , 'menu'\n addClass @cxtMenuRootElem , 'root'\n @initEventHandler()\n\n destroy: ->\n @cy = null\n @options = null\n removeDomElem @cxtMenuRootElem\n @cxtMenuRootElem = null\n\n\uba54\ub274 \ud558\ub098\ub97c \ucd08\uae30\ud654 \ud558\ub294 \ud568\uc218. \uc11c\ube0c \uba54\ub274\ub97c \ud3ec\ud568\ud558\ub294 \uacbd\uc6b0 \uc11c\ube0c \uba54\ub274\uc758 \uac1c\uac1c \ud56d\ubaa9\uc5d0 \ub300\ud574 \uc774 \ud568\uc218\ub97c \uc7ac\uadc0\uc801\uc73c\ub85c \ud638\ucd9c\ud55c\ub2e4.\nmenu \uc815\ubcf4\ub97c \ubc14\ud0d5\uc73c\ub85c dom \uc744 \ub9cc\ub4e4\uace0 parentElem \uc5d0 \ucd94\uac00 \ud55c\ub2e4.\n\n- `parentElem` [DomElement]\n- `menu` [Menu]\n- `menuDepth` [Number] default 1\n- `noNeedNewElem` [Boolean]\n\n initMenu: (parentElem, menu, menuDepth = 1, noNeedNewElem = false) ->\n if noNeedNewElem\n _rootEl = parentElem\n else\n _rootEl = document.createElement('div')\n addClass(_rootEl, \"menu\")\n parentElem.appendChild _rootEl\n\n console.log('_rootEl', _rootEl)\n\n #-------------------------------------------------------------\n\n menu = {name:menu, viewWhen:true} if typeof menu == 'string'\n\n if typeof menu == 'function'\n @initMenu(_rootEl, menu(@cy), menuDepth, true)\n else if isPromise(menu)\n menu\n .then (mnu)=> @initMenu(_rootEl, mnu, menuDepth, true)\n .catch (err)-> console.error \"error in menu info!\", err\n else if menu instanceof Object\n viewWhen = @_checkViewWhen(menu)\n return removeDomElem(_rootEl) if not viewWhen\n\n _rootEl.innerHTML = @options.menuTemplate.call(@, menu)\n addClass(_rootEl, \"depth_\" + menuDepth)\n\n _rootEl.__menu = menu\n\n if menu.submenu\n addClass(_rootEl, \"menugroup\")\n addClass(_rootEl, \"fold\")\n\n if isPromise(menu.submenu)\n menu.submenu\n .then (mlist)=> @initMenu(_rootEl, m, menuDepth + 1) for m in mlist\n .catch (err)-> console.error \"error in menu info!\", err\n else if typeof menu.submenu == 'function'\n @initMenu(_rootEl, m, menuDepth + 1) for m in menu.submenu(@cy)\n else if menu.submenu instanceof Array\n @initMenu(_rootEl, m, menuDepth + 1) for m in menu.submenu\n else\n console.error('unsupported submenu type', menu.submenu)\n\n return _rootEl\n\n initEventHandler: ->\n @cy.on('cxttap', @_cxtTapHandler.bind(@))\n @cy.on('tapstart', @_hideCxtMenu.bind(@))\n @cxtMenuRootElem.addEventListener('click', => @_menuSelectHandler(window.event))\n\n _checkViewWhen: (menu) ->\n return true if menu.viewWhen == undefined\n return menu.viewWhen if typeof menu.viewWhen == 'boolean'\n\n if typeof menu.viewWhen == 'function'\n return menu.viewWhen @cy.scratch('cxtEvent')\n else if typeof menu.viewWhen == 'string'\n evt = @cy.scratch('cxtEvent')\n return (evt.cy == evt.target) if menu.viewWhen == 'core'\n return evt.target.filter(menu.viewWhen).size() == 1\n else\n console.error '.viewWhen type error', menu.viewWhen\n\n _hideCxtMenu: ->\n hide @cxtMenuRootElem\n removeDomElem(@_tmp_menu_root) if @_tmp_menu_root\n @_tmp_menu_root = null\n\n _cxtTapHandler: (event) ->\n console.log event\n @cy.scratch('cxtEvent', event)\n\n removeDomElem(@_tmp_menu_root) if @_tmp_menu_root\n @_tmp_menu_root = @initMenu(@cxtMenuRootElem, @options.menu)\n removeClass(@_tmp_menu_root, 'fold')\n\n containerPos = offset @cy.container()\n renderedPos = event.renderedPosition\n\n left = containerPos.left + renderedPos.x\n top = containerPos.top + renderedPos.y\n\n @cxtMenuRootElem.style.left = left + 'px'\n @cxtMenuRootElem.style.top = top + 'px'\n\n show @cxtMenuRootElem\n\n _menuSelectHandler: (event)->\n if hasClass(event.target, 'groupname')\n toggleClass(event.target.parentElement, 'fold')\n else if hasClass(event.target, 'item')\n @options.menuSelectHandler({\n menuName: event.target.textContent\n target: @cy.scratch('cxtEvent').target\n })\n\n menuItemParent = parents(event.target, '.menu')\n menuItemParent.__menu.onselect?({\n menuName: event.target.textContent\n target: @cy.scratch('cxtEvent').target\n })\n\n hide @cxtMenuRootElem\n\n`menuInfo`\ub97c \uac00\uc9c0\uace0 html string \ub9cc\ub4dc\ub4e0 template \ud568\uc218\n\n _mkMenuContent: (menuInfo) ->\n if menuInfo.name.startsWith('----')\n \"<div class='divider'><\/div>\"\n else\n \"<button class='item #{if menuInfo.submenu then 'groupname' else ''}'>#{menuInfo.name}<\/button>\"\n","avg_line_length":35.3890909091,"max_line_length":138,"alphanum_fraction":0.5527127004}