<commit_before>var createCamera = require('3d-view-controls')
var getBounds    = require('bound-points')
var perspective  = require('gl-mat4/perspective')
var createAxes   = require('gl-axes3d')
var createSpikes = require('gl-spikes3d')
var createSelect = require('gl-select-static')
var getBounds    = require('bound-points')
var mouseChange  = require('mouse-change')
var createMesh   = require('gl-mesh3d')
var createConePlot = require('../cone')

var bounds = []

var wind = require('./dataset-wind')
var conePlot = createConePlot(wind, bounds)

var canvas = document.createElement('canvas')
document.body.appendChild(canvas)
window.addEventListener('resize', require('canvas-fit')(canvas))
var gl = canvas.getContext('webgl')

var camera = createCamera(canvas, {
  eye:    bounds[0],
  center: [0.5*(bounds[0][0]+bounds[1][0]),
           0.5*(bounds[0][1]+bounds[1][1]),
           0.5*(bounds[0][2]+bounds[1][2])],
  zoomMax: 500,
  mode: 'turntable'
})

conePlot.colormap = 'jet'
var mesh = createMesh(gl, conePlot)

var select = createSelect(gl, [canvas.width, canvas.height])
var tickSpacing = 5;
var ticks = bounds[0].map((v,i) => {
  var arr = [];
  var firstTick = Math.ceil(bounds[0][i] / tickSpacing) * tickSpacing;
  var lastTick = Math.floor(bounds[1][i] / tickSpacing) * tickSpacing;
  for (var tick = firstTick; tick <= lastTick; tick += tickSpacing) {
    if (tick === -0) tick = 0;
    arr.push({x: tick, text: tick.toString()});
  }
  return arr;
});
var axes = createAxes(gl, { bounds: bounds, ticks: ticks })
var spikes = createSpikes(gl, {
  bounds: bounds
})
var spikeChanged = false

mouseChange(canvas, function(buttons, x, y) {
  var pickData = select.query(x, canvas.height - y, 10)
  var pickResult = mesh.pick(pickData)
  if(pickResult) {
    spikes.update({
      position: pickResult.position,
      enabled: [true, true, true]
    })
    spikeChanged = true
  } else {
    spikeChanged = spikes.enabled[0]
    spikes.update({
      enabled: [false, false, false]
    })
  }
})

function render() {
  requestAnimationFrame(render)

  gl.enable(gl.DEPTH_TEST)

  var needsUpdate = camera.tick()
  var cameraParams = {
    projection: perspective([], Math.PI/4, canvas.width/canvas.height, 0.01, 1000),
    view: camera.matrix
  }

  if(needsUpdate || spikeChanged) {
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.viewport(0, 0, canvas.width, canvas.height)
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
    axes.draw(cameraParams)
    spikes.draw(cameraParams)
    mesh.draw(cameraParams)
    spikeChanged = false
  }

  if(needsUpdate) {
    select.shape = [canvas.width, canvas.height]
    select.begin()
    mesh.drawPick(cameraParams)
    select.end()
  }
}
render()
<commit_msg>Use portland colormap<commit_after>var createCamera = require('3d-view-controls')
var getBounds    = require('bound-points')
var perspective  = require('gl-mat4/perspective')
var createAxes   = require('gl-axes3d')
var createSpikes = require('gl-spikes3d')
var createSelect = require('gl-select-static')
var getBounds    = require('bound-points')
var mouseChange  = require('mouse-change')
var createMesh   = require('gl-mesh3d')
var createConePlot = require('../cone')

var bounds = []

var wind = require('./dataset-wind')
var conePlot = createConePlot(wind, bounds)

var canvas = document.createElement('canvas')
document.body.appendChild(canvas)
window.addEventListener('resize', require('canvas-fit')(canvas))
var gl = canvas.getContext('webgl')

var camera = createCamera(canvas, {
  eye:    bounds[0],
  center: [0.5*(bounds[0][0]+bounds[1][0]),
           0.5*(bounds[0][1]+bounds[1][1]),
           0.5*(bounds[0][2]+bounds[1][2])],
  zoomMax: 500,
  mode: 'turntable'
})

conePlot.colormap = 'portland'
var mesh = createMesh(gl, conePlot)

var select = createSelect(gl, [canvas.width, canvas.height])
var tickSpacing = 5;
var ticks = bounds[0].map((v,i) => {
  var arr = [];
  var firstTick = Math.ceil(bounds[0][i] / tickSpacing) * tickSpacing;
  var lastTick = Math.floor(bounds[1][i] / tickSpacing) * tickSpacing;
  for (var tick = firstTick; tick <= lastTick; tick += tickSpacing) {
    if (tick === -0) tick = 0;
    arr.push({x: tick, text: tick.toString()});
  }
  return arr;
});
var axes = createAxes(gl, { bounds: bounds, ticks: ticks })
var spikes = createSpikes(gl, {
  bounds: bounds
})
var spikeChanged = false

mouseChange(canvas, function(buttons, x, y) {
  var pickData = select.query(x, canvas.height - y, 10)
  var pickResult = mesh.pick(pickData)
  if(pickResult) {
    spikes.update({
      position: pickResult.position,
      enabled: [true, true, true]
    })
    spikeChanged = true
  } else {
    spikeChanged = spikes.enabled[0]
    spikes.update({
      enabled: [false, false, false]
    })
  }
})

function render() {
  requestAnimationFrame(render)

  gl.enable(gl.DEPTH_TEST)

  var needsUpdate = camera.tick()
  var cameraParams = {
    projection: perspective([], Math.PI/4, canvas.width/canvas.height, 0.01, 1000),
    view: camera.matrix
  }

  if(needsUpdate || spikeChanged) {
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.viewport(0, 0, canvas.width, canvas.height)
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
    axes.draw(cameraParams)
    spikes.draw(cameraParams)
    mesh.draw(cameraParams)
    spikeChanged = false
  }

  if(needsUpdate) {
    select.shape = [canvas.width, canvas.height]
    select.begin()
    mesh.drawPick(cameraParams)
    select.end()
  }
}
render()
<|endoftext|>


<commit_before>'use strict'

let utf8 = require('./util').utf8

module.exports = {
  broker: null,
  configuration: null,

  create: function (broker, configuration) {
    this.broker = broker
    this.configuration = configuration
    return true
  },

  receive: function (message) {
    console.log(message.properties.type == "sentinel-message" ? "\nSENTINEL MESSAGE" : "\nMESSAGE");
      console.log(`Header: ${JSON.stringify(message.properties)}`);
      console.log(`Content: ${utf8.decode(message.content)}`)
  },

  destroy: function () { }
}
<commit_msg>change "header" to "properties" in printer<commit_after>'use strict'

let utf8 = require('./util').utf8

module.exports = {
  broker: null,
  configuration: null,

  create: function (broker, configuration) {
    this.broker = broker
    this.configuration = configuration
    return true
  },

  receive: function (message) {
    console.log(message.properties.type == "sentinel-message" ? "\nSENTINEL MESSAGE" : "\nMESSAGE");
      console.log(`Properties: ${JSON.stringify(message.properties)}`);
      console.log(`Content: ${utf8.decode(message.content)}`)
  },

  destroy: function () { }
}
<|endoftext|>


<commit_before>import _ from 'lodash'
import selectorParser from 'postcss-selector-parser'
import postcss from 'postcss'
import substituteTailwindAtRules from '../lib/substituteTailwindAtRules'
import evaluateTailwindFunctions from '../lib/evaluateTailwindFunctions'
import substituteVariantsAtRules from '../lib/substituteVariantsAtRules'
import substituteResponsiveAtRules from '../lib/substituteResponsiveAtRules'
import convertLayerAtRulesToControlComments from '../lib/convertLayerAtRulesToControlComments'
import substituteScreenAtRules from '../lib/substituteScreenAtRules'
import prefixSelector from '../util/prefixSelector'
import { useMemo } from '../util/useMemo'

function hasAtRule(css, atRule) {
  let foundAtRule = false

  css.walkAtRules(atRule, () => {
    foundAtRule = true
    return false
  })

  return foundAtRule
}

function cloneWithoutChildren(node) {
  if (node.type === 'atrule') {
    return postcss.atRule({ name: node.name, params: node.params })
  }

  if (node.type === 'rule') {
    return postcss.rule({ name: node.name, selectors: node.selectors })
  }

  const clone = node.clone()
  clone.removeAll()
  return clone
}

const tailwindApplyPlaceholder = selectorParser.attribute({
  attribute: '__TAILWIND-APPLY-PLACEHOLDER__',
})

function generateRulesFromApply({ rule, utilityName: className, classPosition }, replaceWith) {
  const parser = selectorParser(selectors => {
    let i = 0
    selectors.walkClasses(c => {
      if (classPosition === i++ && c.value === className) {
        c.replaceWith(tailwindApplyPlaceholder)
      }
    })
  })

  const processedSelectors = rule.selectors.map(selector => {
    // You could argue we should make this replacement at the AST level, but if we believe
    // the placeholder string is safe from collisions then it is safe to do this is a simple
    // string replacement, and much, much faster.
    return parser.processSync(selector).replace('[__TAILWIND-APPLY-PLACEHOLDER__]', replaceWith)
  })

  const cloned = rule.clone()
  let current = cloned
  let parent = rule.parent

  while (parent && parent.type !== 'root') {
    const parentClone = cloneWithoutChildren(parent)

    parentClone.append(current)
    current.parent = parentClone
    current = parentClone
    parent = parent.parent
  }

  cloned.selectors = processedSelectors
  return current
}

const extractUtilityNamesParser = selectorParser(selectors => {
  let classes = []
  selectors.walkClasses(c => classes.push(c.value))
  return classes
})

const extractUtilityNames = useMemo(
  selector => extractUtilityNamesParser.transformSync(selector),
  selector => selector
)

function buildUtilityMap(css) {
  let index = 0
  const utilityMap = {}

  css.walkRules(rule => {
    const utilityNames = extractUtilityNames(rule.selector)

    utilityNames.forEach((utilityName, i) => {
      if (utilityMap[utilityName] === undefined) {
        utilityMap[utilityName] = []
      }

      utilityMap[utilityName].push({
        index,
        utilityName,
        classPosition: i,
        get rule() {
          // TODO: #perf every time we "read" this value we will create a copy.
          // Is this an issue?
          return rule.clone({ parent: rule.parent })
        },
      })
      index++
    })
  })

  return utilityMap
}

function mergeAdjacentRules(initialRule, rulesToInsert) {
  let previousRule = initialRule

  rulesToInsert.forEach(toInsert => {
    if (
      toInsert.type === 'rule' &&
      previousRule.type === 'rule' &&
      toInsert.selector === previousRule.selector
    ) {
      previousRule.append(toInsert.nodes)
    } else if (
      toInsert.type === 'atrule' &&
      previousRule.type === 'atrule' &&
      toInsert.params === previousRule.params
    ) {
      const merged = mergeAdjacentRules(
        previousRule.nodes[previousRule.nodes.length - 1],
        toInsert.nodes
      )

      previousRule.append(merged)
    } else {
      previousRule = toInsert
    }

    toInsert.walk(n => {
      if (n.nodes && n.nodes.length === 0) {
        n.remove()
      }
    })
  })

  return rulesToInsert.filter(r => r.nodes.length > 0)
}

function makeExtractUtilityRules(css, config) {
  const utilityMap = buildUtilityMap(css)

  return function extractUtilityRules(utilityNames, rule) {
    const combined = []

    utilityNames.forEach(utilityName => {
      if (utilityMap[utilityName] === undefined) {
        // Look for prefixed utility in case the user has goofed
        const prefixedUtility = prefixSelector(config.prefix, `.${utilityName}`).slice(1)

        if (utilityMap[prefixedUtility] !== undefined) {
          throw rule.error(
            `The \`${utilityName}\` class does not exist, but \`${prefixedUtility}\` does. Did you forget the prefix?`
          )
        }

        throw rule.error(
          `The \`${utilityName}\` class does not exist. If you're sure that \`${utilityName}\` exists, make sure that any \`@import\` statements are being properly processed before Tailwind CSS sees your CSS, as \`@apply\` can only be used for classes in the same CSS tree.`,
          { word: utilityName }
        )
      }

      combined.push(...utilityMap[utilityName])
    })

    return combined.sort((a, b) => a.index - b.index)
  }
}

function processApplyAtRules(css, lookupTree, config) {
  const extractUtilityRules = makeExtractUtilityRules(lookupTree, config)

  do {
    css.walkRules(rule => {
      const applyRules = []

      // Only walk direct children to avoid issues with nesting plugins
      rule.each(child => {
        if (child.type === 'atrule' && child.name === 'apply') {
          applyRules.unshift(child)
        }
      })

      applyRules.forEach(applyRule => {
        const [
          importantEntries,
          applyUtilityNames,
          important = importantEntries.length > 0,
        ] = _.partition(applyRule.params.split(' '), n => n === '!important')

        const currentUtilityNames = extractUtilityNames(rule.selector)

        if (_.intersection(applyUtilityNames, currentUtilityNames).length > 0) {
          const currentUtilityName = _.intersection(applyUtilityNames, currentUtilityNames)[0]
          throw rule.error(
            `You cannot \`@apply\` the \`${currentUtilityName}\` utility here because it creates a circular dependency.`
          )
        }

        // Extract any post-apply declarations and re-insert them after apply rules
        const afterRule = rule.clone({ raws: {} })
        afterRule.nodes = afterRule.nodes.slice(rule.index(applyRule) + 1)
        rule.nodes = rule.nodes.slice(0, rule.index(applyRule) + 1)

        // Sort applys to match CSS source order
        const applys = extractUtilityRules(applyUtilityNames, applyRule)

        // Get new rules with the utility portion of the selector replaced with the new selector
        const rulesToInsert = [
          ...applys.map(applyUtility => {
            return generateRulesFromApply(applyUtility, rule.selector)
          }),
          afterRule,
        ]

        const { nodes } = _.tap(postcss.root({ nodes: rulesToInsert }), root =>
          root.walkDecls(d => (d.important = important))
        )

        const mergedRules = mergeAdjacentRules(rule, nodes)

        applyRule.remove()
        rule.after(mergedRules)
      })

      // If the base rule has nothing in it (all applys were pseudo or responsive variants),
      // remove the rule fuggit.
      if (rule.nodes.length === 0) {
        rule.remove()
      }
    })

    // We already know that we have at least 1 @apply rule. Otherwise this
    // function would not have been called. Therefore we can execute this code
    // at least once. This also means that in the best case scenario we only
    // call this 2 times, instead of 3 times.
    // 1st time -> before we call this function
    // 2nd time -> when we check if we have to do this loop again (because do {} while (check))
    // .. instead of
    // 1st time -> before we call this function
    // 2nd time -> when we check the first time (because while (check) do {})
    // 3rd time -> when we re-check to see if we should do this loop again
  } while (hasAtRule(css, 'apply'))

  return css
}

export default function applyComplexClasses(config, getProcessedPlugins) {
  return function(css) {
    // We can stop already when we don't have any @apply rules. Vue users: you're welcome!
    if (!hasAtRule(css, 'apply')) {
      return css
    }

    // Tree already contains @tailwind rules, don't prepend default Tailwind tree
    if (hasAtRule(css, 'tailwind')) {
      return processApplyAtRules(css, css, config)
    }

    // Tree contains no @tailwind rules, so generate all of Tailwind's styles and
    // prepend them to the user's CSS. Important for <style> blocks in Vue components.
    return postcss([
      substituteTailwindAtRules(config, getProcessedPlugins()),
      evaluateTailwindFunctions(config),
      substituteVariantsAtRules(config, getProcessedPlugins()),
      substituteResponsiveAtRules(config),
      convertLayerAtRulesToControlComments(config),
      substituteScreenAtRules(config),
    ])
      .process(
        `
        @tailwind base;
        @tailwind components;
        @tailwind utilities;
        `,
        { from: undefined }
      )
      .then(result => {
        // Prepend Tailwind's generated classes to the tree so they are available for `@apply`
        const lookupTree = _.tap(css.clone(), tree => tree.prepend(result.root))
        return processApplyAtRules(css, lookupTree, config)
      })
  }
}
<commit_msg>cache clone rule<commit_after>import _ from 'lodash'
import selectorParser from 'postcss-selector-parser'
import postcss from 'postcss'
import substituteTailwindAtRules from '../lib/substituteTailwindAtRules'
import evaluateTailwindFunctions from '../lib/evaluateTailwindFunctions'
import substituteVariantsAtRules from '../lib/substituteVariantsAtRules'
import substituteResponsiveAtRules from '../lib/substituteResponsiveAtRules'
import convertLayerAtRulesToControlComments from '../lib/convertLayerAtRulesToControlComments'
import substituteScreenAtRules from '../lib/substituteScreenAtRules'
import prefixSelector from '../util/prefixSelector'
import { useMemo } from '../util/useMemo'

function hasAtRule(css, atRule) {
  let foundAtRule = false

  css.walkAtRules(atRule, () => {
    foundAtRule = true
    return false
  })

  return foundAtRule
}

function cloneWithoutChildren(node) {
  if (node.type === 'atrule') {
    return postcss.atRule({ name: node.name, params: node.params })
  }

  if (node.type === 'rule') {
    return postcss.rule({ name: node.name, selectors: node.selectors })
  }

  const clone = node.clone()
  clone.removeAll()
  return clone
}

const tailwindApplyPlaceholder = selectorParser.attribute({
  attribute: '__TAILWIND-APPLY-PLACEHOLDER__',
})

function generateRulesFromApply({ rule, utilityName: className, classPosition }, replaceWith) {
  const parser = selectorParser(selectors => {
    let i = 0
    selectors.walkClasses(c => {
      if (classPosition === i++ && c.value === className) {
        c.replaceWith(tailwindApplyPlaceholder)
      }
    })
  })

  const processedSelectors = rule.selectors.map(selector => {
    // You could argue we should make this replacement at the AST level, but if we believe
    // the placeholder string is safe from collisions then it is safe to do this is a simple
    // string replacement, and much, much faster.
    return parser.processSync(selector).replace('[__TAILWIND-APPLY-PLACEHOLDER__]', replaceWith)
  })

  const cloned = rule.clone()
  let current = cloned
  let parent = rule.parent

  while (parent && parent.type !== 'root') {
    const parentClone = cloneWithoutChildren(parent)

    parentClone.append(current)
    current.parent = parentClone
    current = parentClone
    parent = parent.parent
  }

  cloned.selectors = processedSelectors
  return current
}

const extractUtilityNamesParser = selectorParser(selectors => {
  let classes = []
  selectors.walkClasses(c => classes.push(c.value))
  return classes
})

const extractUtilityNames = useMemo(
  selector => extractUtilityNamesParser.transformSync(selector),
  selector => selector
)

const cloneRuleWithParent = useMemo(
  rule => rule.clone({ parent: rule.parent }),
  rule => rule
)

function buildUtilityMap(css) {
  let index = 0
  const utilityMap = {}

  css.walkRules(rule => {
    const utilityNames = extractUtilityNames(rule.selector)

    utilityNames.forEach((utilityName, i) => {
      if (utilityMap[utilityName] === undefined) {
        utilityMap[utilityName] = []
      }

      utilityMap[utilityName].push({
        index,
        utilityName,
        classPosition: i,
        get rule() {
          return cloneRuleWithParent(rule)
        },
      })
      index++
    })
  })

  return utilityMap
}

function mergeAdjacentRules(initialRule, rulesToInsert) {
  let previousRule = initialRule

  rulesToInsert.forEach(toInsert => {
    if (
      toInsert.type === 'rule' &&
      previousRule.type === 'rule' &&
      toInsert.selector === previousRule.selector
    ) {
      previousRule.append(toInsert.nodes)
    } else if (
      toInsert.type === 'atrule' &&
      previousRule.type === 'atrule' &&
      toInsert.params === previousRule.params
    ) {
      const merged = mergeAdjacentRules(
        previousRule.nodes[previousRule.nodes.length - 1],
        toInsert.nodes
      )

      previousRule.append(merged)
    } else {
      previousRule = toInsert
    }

    toInsert.walk(n => {
      if (n.nodes && n.nodes.length === 0) {
        n.remove()
      }
    })
  })

  return rulesToInsert.filter(r => r.nodes.length > 0)
}

function makeExtractUtilityRules(css, config) {
  const utilityMap = buildUtilityMap(css)

  return function extractUtilityRules(utilityNames, rule) {
    const combined = []

    utilityNames.forEach(utilityName => {
      if (utilityMap[utilityName] === undefined) {
        // Look for prefixed utility in case the user has goofed
        const prefixedUtility = prefixSelector(config.prefix, `.${utilityName}`).slice(1)

        if (utilityMap[prefixedUtility] !== undefined) {
          throw rule.error(
            `The \`${utilityName}\` class does not exist, but \`${prefixedUtility}\` does. Did you forget the prefix?`
          )
        }

        throw rule.error(
          `The \`${utilityName}\` class does not exist. If you're sure that \`${utilityName}\` exists, make sure that any \`@import\` statements are being properly processed before Tailwind CSS sees your CSS, as \`@apply\` can only be used for classes in the same CSS tree.`,
          { word: utilityName }
        )
      }

      combined.push(...utilityMap[utilityName])
    })

    return combined.sort((a, b) => a.index - b.index)
  }
}

function processApplyAtRules(css, lookupTree, config) {
  const extractUtilityRules = makeExtractUtilityRules(lookupTree, config)

  do {
    css.walkRules(rule => {
      const applyRules = []

      // Only walk direct children to avoid issues with nesting plugins
      rule.each(child => {
        if (child.type === 'atrule' && child.name === 'apply') {
          applyRules.unshift(child)
        }
      })

      applyRules.forEach(applyRule => {
        const [
          importantEntries,
          applyUtilityNames,
          important = importantEntries.length > 0,
        ] = _.partition(applyRule.params.split(' '), n => n === '!important')

        const currentUtilityNames = extractUtilityNames(rule.selector)

        if (_.intersection(applyUtilityNames, currentUtilityNames).length > 0) {
          const currentUtilityName = _.intersection(applyUtilityNames, currentUtilityNames)[0]
          throw rule.error(
            `You cannot \`@apply\` the \`${currentUtilityName}\` utility here because it creates a circular dependency.`
          )
        }

        // Extract any post-apply declarations and re-insert them after apply rules
        const afterRule = rule.clone({ raws: {} })
        afterRule.nodes = afterRule.nodes.slice(rule.index(applyRule) + 1)
        rule.nodes = rule.nodes.slice(0, rule.index(applyRule) + 1)

        // Sort applys to match CSS source order
        const applys = extractUtilityRules(applyUtilityNames, applyRule)

        // Get new rules with the utility portion of the selector replaced with the new selector
        const rulesToInsert = [
          ...applys.map(applyUtility => {
            return generateRulesFromApply(applyUtility, rule.selector)
          }),
          afterRule,
        ]

        const { nodes } = _.tap(postcss.root({ nodes: rulesToInsert }), root =>
          root.walkDecls(d => (d.important = important))
        )

        const mergedRules = mergeAdjacentRules(rule, nodes)

        applyRule.remove()
        rule.after(mergedRules)
      })

      // If the base rule has nothing in it (all applys were pseudo or responsive variants),
      // remove the rule fuggit.
      if (rule.nodes.length === 0) {
        rule.remove()
      }
    })

    // We already know that we have at least 1 @apply rule. Otherwise this
    // function would not have been called. Therefore we can execute this code
    // at least once. This also means that in the best case scenario we only
    // call this 2 times, instead of 3 times.
    // 1st time -> before we call this function
    // 2nd time -> when we check if we have to do this loop again (because do {} while (check))
    // .. instead of
    // 1st time -> before we call this function
    // 2nd time -> when we check the first time (because while (check) do {})
    // 3rd time -> when we re-check to see if we should do this loop again
  } while (hasAtRule(css, 'apply'))

  return css
}

export default function applyComplexClasses(config, getProcessedPlugins) {
  return function(css) {
    // We can stop already when we don't have any @apply rules. Vue users: you're welcome!
    if (!hasAtRule(css, 'apply')) {
      return css
    }

    // Tree already contains @tailwind rules, don't prepend default Tailwind tree
    if (hasAtRule(css, 'tailwind')) {
      return processApplyAtRules(css, css, config)
    }

    // Tree contains no @tailwind rules, so generate all of Tailwind's styles and
    // prepend them to the user's CSS. Important for <style> blocks in Vue components.
    return postcss([
      substituteTailwindAtRules(config, getProcessedPlugins()),
      evaluateTailwindFunctions(config),
      substituteVariantsAtRules(config, getProcessedPlugins()),
      substituteResponsiveAtRules(config),
      convertLayerAtRulesToControlComments(config),
      substituteScreenAtRules(config),
    ])
      .process(
        `
        @tailwind base;
        @tailwind components;
        @tailwind utilities;
        `,
        { from: undefined }
      )
      .then(result => {
        // Prepend Tailwind's generated classes to the tree so they are available for `@apply`
        const lookupTree = _.tap(css.clone(), tree => tree.prepend(result.root))
        return processApplyAtRules(css, lookupTree, config)
      })
  }
}
<|endoftext|>


<commit_before>var google = require("googleapis");
var ga = google.analytics("v3");

var moment = require("moment");

module.exports = function (app) {
    var gaQuery = function (req, res, options) {
        var jwt = new google.auth.JWT(
          options.serviceEmail,
          options.pemFilename,
          null,
          ["https://www.googleapis.com/auth/analytics.readonly"],
          null);

        if (app.get("env") !== "development") {
            res.header("Access-Control-Allow-Origin", options.origin);
        }

        jwt.authorize(function (err, tokens) { // eslint-disable-line no-unused-vars
            if (err) {
                console.log("jwt error", err);
                return;
            }

            ga.data.ga.get({
                auth: jwt,
                ids: options.accountId,
                "start-date": "2014-01-01",
                "end-date": moment().format("YYYY-MM-DD"),
                "metrics": "ga:pageviews",
                "filters": "ga:pagePath==/" + options.pathRoot + "/" + (req.query.path || "")
            }, function (err, result) {
                if (err) {
                    console.log("api error", err, result);
                }

                res.send(result && result.rows && result.rows[0] ? result.rows[0][0] : "(unknown)");
            });
        });
    };

    app.get("/ga", function (req, res) {
        gaQuery(req, res, {
            serviceEmail: process.env.SERVICE_EMAIL,
            pemFilename: "grnsight.pem",
            origin: "http://dondi.github.io",
            accountId: "ga:91279024",
            pathRoot: "GRNsight"
        });
    });

    app.get("/grnmap", function (req, res) {
        gaQuery(req, res, {
            serviceEmail: process.env.GRNMAP_SERVICE_EMAIL,
            pemFilename: "grnmap.pem",
            origin: "http://kdahlquist.github.io",
            accountId: "ga:97014398",
            pathRoot: "GRNmap"
        });
    });
};
<commit_msg>change CORS header to HTTPS<commit_after>var google = require("googleapis");
var ga = google.analytics("v3");

var moment = require("moment");

module.exports = function (app) {
    var gaQuery = function (req, res, options) {
        var jwt = new google.auth.JWT(
          options.serviceEmail,
          options.pemFilename,
          null,
          ["https://www.googleapis.com/auth/analytics.readonly"],
          null);

        if (app.get("env") !== "development") {
            res.header("Access-Control-Allow-Origin", options.origin);
        }

        jwt.authorize(function (err, tokens) { // eslint-disable-line no-unused-vars
            if (err) {
                console.log("jwt error", err);
                return;
            }

            ga.data.ga.get({
                auth: jwt,
                ids: options.accountId,
                "start-date": "2014-01-01",
                "end-date": moment().format("YYYY-MM-DD"),
                "metrics": "ga:pageviews",
                "filters": "ga:pagePath==/" + options.pathRoot + "/" + (req.query.path || "")
            }, function (err, result) {
                if (err) {
                    console.log("api error", err, result);
                }

                res.send(result && result.rows && result.rows[0] ? result.rows[0][0] : "(unknown)");
            });
        });
    };

    app.get("/ga", function (req, res) {
        gaQuery(req, res, {
            serviceEmail: process.env.SERVICE_EMAIL,
            pemFilename: "grnsight.pem",
            origin: "https://dondi.github.io",
            accountId: "ga:91279024",
            pathRoot: "GRNsight"
        });
    });

    app.get("/grnmap", function (req, res) {
        gaQuery(req, res, {
            serviceEmail: process.env.GRNMAP_SERVICE_EMAIL,
            pemFilename: "grnmap.pem",
            origin: "http://kdahlquist.github.io",
            accountId: "ga:97014398",
            pathRoot: "GRNmap"
        });
    });
};
<|endoftext|>


<commit_before>module.exports = (sequelize, DataTypes) => {
  const UserGroup = sequelize.define('UserGroup', {
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    groupId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
  }, {
    timestamps: false
  });
  return UserGroup;
};

<commit_msg>Modify Server side model to work well with client<commit_after>module.exports = (sequelize, DataTypes) => {
  const UserGroup = sequelize.define('UserGroup', {
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    groupId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
  }, {
    classMethods: {
      associate: (models) => {
        UserGroup.belongsTo(models.Group, { foreignKey: 'groupId' });
        UserGroup.belongsTo(models.User, { foreignKey: 'userId' });
      }
    },
    timestamps: false
  });
  return UserGroup;
};

<|endoftext|>


<commit_before>'use strict';

const requireFromString = require('require-from-string');

// Parses a JavaScript file
const parse = function ({ content, path }) {
  if (typeof path === 'string') {
    // eslint-disable-next-line import/no-dynamic-require
    return require(path);
  }

  return requireFromString(content);
};

// Serializes a JavaScript file
const serialize = function ({ content }) {
  const json = JSON.stringify(content, null, 2);
  return `module.exports = ${json}`;
};

module.exports = {
  name: 'javascript',
  title: 'JavaScript',
  types: ['conf'],
  extNames: ['js', 'mjs'],
  mimes: [
    'application/javascript',
    'application/x-javascript',
    'application/ecmascript',
    'text/javascript',
    'text/ecmascript',
  ],
  mimeExtensions: ['+js', '+mjs'],
  charsets: ['utf-8'],
  jsonCompat: ['superset'],
  parse,
  serialize,
};
<commit_msg>Fix JavaScript format loading<commit_after>'use strict';

const requireFromString = require('require-from-string');

// Parses a JavaScript file
const parse = function ({ content, path }) {
  if (content !== undefined) {
    return requireFromString(content);
  }

  // eslint-disable-next-line import/no-dynamic-require
  return require(path);
};

// Serializes a JavaScript file
const serialize = function ({ content }) {
  const json = JSON.stringify(content, null, 2);
  return `module.exports = ${json}`;
};

module.exports = {
  name: 'javascript',
  title: 'JavaScript',
  types: ['conf'],
  extNames: ['js', 'mjs'],
  mimes: [
    'application/javascript',
    'application/x-javascript',
    'application/ecmascript',
    'text/javascript',
    'text/ecmascript',
  ],
  mimeExtensions: ['+js', '+mjs'],
  charsets: ['utf-8'],
  jsonCompat: ['superset'],
  parse,
  serialize,
};
<|endoftext|>


<commit_before>import models from '../../models';
import * as errors from '../errors';
import { mustHaveRole } from '../../lib/auth';
import { get } from 'lodash';
import { strip_tags } from '../../lib/utils';

function require(args, path) {
  if (!get(args, path)) throw new errors.ValidationFailed({ message: `${path} required` });
}

export async function createUpdate(_, args, req) {
  const CollectiveId = get(args, 'update.collective.id');
  mustHaveRole(req.remoteUser, 'ADMIN', CollectiveId, "create an update");
  require(args, 'update.title');

  const markdown = args.update.markdown
        ? strip_tags(args.update.markdown)
        : '';

  const update = await models.Update.create({
    title: args.update.title,
    markdown,
    html: strip_tags(args.update.html),
    CollectiveId,
    TierId: get(args, 'update.tier.id'),
    CreatedByUserId: req.remoteUser.id,
    FromCollectiveId: req.remoteUser.CollectiveId
  });

  return update;
}

async function fetchUpdate(id) {
  const update = await models.Update.findById(id);
  if (!update) throw new errors.NotFound({ message: `Update with id ${id} not found` });
  return update;
}

export async function editUpdate(_, args, req) {
  require(args, 'update.id');
  const update = await fetchUpdate(args.update.id);
  return await update.edit(req.remoteUser, args.update);
}

export async function publishUpdate(_, args, req) {
  const update = await fetchUpdate(args.id);
  return await update.publish(req.remoteUser);
}

export async function unpublishUpdate(_, args, req) {
  const update = await fetchUpdate(args.id);
  return await update.unpublish(req.remoteUser);
}

export async function deleteUpdate(_, args, req) {
  const update = await fetchUpdate(args.id);
  return await update.delete(req.remoteUser);
}
<commit_msg>Whitelist anchors for updates creation<commit_after>import models from '../../models';
import * as errors from '../errors';
import { mustHaveRole } from '../../lib/auth';
import { get } from 'lodash';
import { strip_tags } from '../../lib/utils';

function require(args, path) {
  if (!get(args, path)) throw new errors.ValidationFailed({ message: `${path} required` });
}

export async function createUpdate(_, args, req) {
  const CollectiveId = get(args, 'update.collective.id');
  const allowedExtensions = ['a', 'h1', 'h2', 'strong', 'img', 'ul', 'li'];
  mustHaveRole(req.remoteUser, 'ADMIN', CollectiveId, "create an update");
  require(args, 'update.title');

  const markdown = args.update.markdown
        ? strip_tags(args.update.markdown, allowedExtensions)
        : '';

  const update = await models.Update.create({
    title: args.update.title,
    markdown,
    html: strip_tags(args.update.html),
    CollectiveId,
    TierId: get(args, 'update.tier.id'),
    CreatedByUserId: req.remoteUser.id,
    FromCollectiveId: req.remoteUser.CollectiveId
  });

  return update;
}

async function fetchUpdate(id) {
  const update = await models.Update.findById(id);
  if (!update) throw new errors.NotFound({ message: `Update with id ${id} not found` });
  return update;
}

export async function editUpdate(_, args, req) {
  require(args, 'update.id');
  const update = await fetchUpdate(args.update.id);
  return await update.edit(req.remoteUser, args.update);
}

export async function publishUpdate(_, args, req) {
  const update = await fetchUpdate(args.id);
  return await update.publish(req.remoteUser);
}

export async function unpublishUpdate(_, args, req) {
  const update = await fetchUpdate(args.id);
  return await update.unpublish(req.remoteUser);
}

export async function deleteUpdate(_, args, req) {
  const update = await fetchUpdate(args.id);
  return await update.delete(req.remoteUser);
}
<|endoftext|>


<commit_before>Meteor.publish("singlePost", function (idOrTitle) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				$or: [
					{
						_id: idOrTitle
					},
					{
						title: idOrTitle
					}
				]
			},
			permissionsSelector
		]
	};
	// Return the cursor finding that post
	return Posts.find(selector);
});

Meteor.publish("postsByAuthor", function (authorId) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				// Select only published posts
				published: true,
				// Authored by userId
				authors: {
					$elemMatch: {
						userId: authorId
					}
				}
			},
			permissionsSelector
		]
	};
	// Return the cursor finding those posts
	return Posts.find(selector);
});

Meteor.publish("latestPosts", function (limit) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				// Select only published posts
				published: true
			},
			permissionsSelector
		]
	};
	// Sanitize the limit
	limit = parseInt(limit, 10);
	limit = isNaN(limit) ? 10 : limit;
	var options = {
		limit: limit,
		sort: {
			publishedOn: -1
		},
		fields: {
			title: 1,
			subtitle: 1,
			authors: 1,
			publishedOn: 1,
			published: 1,
			likedBy: 1
		}
	};
	// Return the cursor finding those posts
	return Posts.find(selector, options);
});

Meteor.publish("postDrafts", function (limit) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				// Select only published posts
				published: false
			},
			permissionsSelector
		]
	};
	// Sanitize the limit
	limit = parseInt(limit, 10);
	limit = isNaN(limit) ? 10 : limit;
	var options = {
		limit: limit,
		sort: {
			publishedOn: -1
		},
		fields: {
			title: 1,
			subtitle: 1,
			authors: 1,
			publishedOn: 1,
			published: 1
		}
	};
	// Return the cursor finding those posts
	return Posts.find(selector, options);
});
<commit_msg>included post body into latestPosts<commit_after>Meteor.publish("singlePost", function (idOrTitle) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				$or: [
					{
						_id: idOrTitle
					},
					{
						title: idOrTitle
					}
				]
			},
			permissionsSelector
		]
	};
	// Return the cursor finding that post
	return Posts.find(selector);
});

Meteor.publish("postsByAuthor", function (authorId) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				// Select only published posts
				published: true,
				// Authored by userId
				authors: {
					$elemMatch: {
						userId: authorId
					}
				}
			},
			permissionsSelector
		]
	};
	// Return the cursor finding those posts
	return Posts.find(selector);
});

Meteor.publish("latestPosts", function (limit, retrieveAllFields) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				// Select only published posts
				published: true
			},
			permissionsSelector
		]
	};
	// Sanitize the limit
	limit = parseInt(limit, 10);
	limit = isNaN(limit) ? 10 : limit;
	var options = {
		limit: limit,
		sort: {
			publishedOn: -1
		},
		fields: retrieveAllFields ? undefined : {
			title: 1,
			subtitle: 1,
			authors: 1,
			publishedOn: 1,
			published: 1,
			likedBy: 1
		}
	};
	// Return the cursor finding those posts
	return Posts.find(selector, options);
});

Meteor.publish("postDrafts", function (limit) {
	// Get the current user
	var user = Meteor.users.findOne({_id: this.userId}) || {};
	// Get the permissions selector
	var permissionsSelector = PermissionsEnum.Posts.getPermissionsSelector(user);
	// Construct the selector
	var selector = {
		$and: [
			{
				// Select only published posts
				published: false
			},
			permissionsSelector
		]
	};
	// Sanitize the limit
	limit = parseInt(limit, 10);
	limit = isNaN(limit) ? 10 : limit;
	var options = {
		limit: limit,
		sort: {
			publishedOn: -1
		},
		fields: {
			title: 1,
			subtitle: 1,
			authors: 1,
			publishedOn: 1,
			published: 1
		}
	};
	// Return the cursor finding those posts
	return Posts.find(selector, options);
});<|endoftext|>


<commit_before>/*
MIT License

Copyright (c) 2017 Erik De Rijcke

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

'use strict'

const RegistryResource = require('./RegistryResource')
const RegistryRequests = require('./RegistryRequests')
const Global = require('./Global')

/**
 * @implements {RegistryRequests}
 */
class Registry extends RegistryRequests {
  constructor () {
    super()
    /**
     * @type {Array<RegistryResource>}
     * @private
     */
    this._registryResources = []
    /**
     * @type {Object.<number,Global>}
     * @private
     */
    this._globals = {}
    /**
     * @type {number}
     * @private
     */
    this._nextGlobalName = 0
  }

  /**
   * Register a global to make it available to clients.
   *
   * @param {Object} implementation
   * @param {string}interface_
   * @param {number}version
   * @param {function(Client,number,number):void}bindCallback callback with Client, id, version arguments
   * @return {Global}
   */
  createGlobal (implementation, interface_, version, bindCallback) {
    const name = ++this._nextGlobalName
    const global = new Global(this, implementation, interface_, version, name, bindCallback)
    this._globals[name] = global
    this._registryResources.forEach(registryResource => registryResource.global(global.name, global.interface_, global.version))
    return global
  }

  /**
   * Unregister a global and revoke it from clients.
   *
   * @param {Global} global
   */
  destroyGlobal (global) {
    if (this._globals[global.name]) {
      delete this._globals[global.name]
      this._registryResources.forEach(registryResource => registryResource.globalRemove(global.name))
    }
  }

  /**
   * @param {RegistryResource} registryResource
   */
  publishGlobals (registryResource) {
    Object.entries(this._globals).forEach((global, name) => registryResource.global(name, global.interface_, global.version))
  }

  /**
   *
   * @param {Client} client
   * @param {number} id
   */
  createRegistryResource (client, id) {
    const registryResource = new RegistryResource(client, id, 1)
    registryResource.implementation = this
    this._registryResources.push(registryResource)
    return registryResource
  }

  /**
   * Binds a new, client-created object to the server using the
   * specified name as the identifier.
   * @param {Client}client
   * @param {RegistryResource}resource
   * @param {number}name unique numeric name of the object
   * @param {string}interface_
   * @param {number}version
   * @param {number}id bounded object
   * @override
   */
  bind (client, resource, name, interface_, version, id) {
    this._globals[name].bindClient(client, id, version)
  }
}

module.exports = Registry<commit_msg>properly destructure object entry iteration<commit_after>/*
MIT License

Copyright (c) 2017 Erik De Rijcke

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

'use strict'

const RegistryResource = require('./RegistryResource')
const RegistryRequests = require('./RegistryRequests')
const Global = require('./Global')

/**
 * @implements {RegistryRequests}
 */
class Registry extends RegistryRequests {
  constructor () {
    super()
    /**
     * @type {Array<RegistryResource>}
     * @private
     */
    this._registryResources = []
    /**
     * @type {Object.<number,Global>}
     * @private
     */
    this._globals = {}
    /**
     * @type {number}
     * @private
     */
    this._nextGlobalName = 0
  }

  /**
   * Register a global to make it available to clients.
   *
   * @param {Object} implementation
   * @param {string}interface_
   * @param {number}version
   * @param {function(Client,number,number):void}bindCallback callback with Client, id, version arguments
   * @return {Global}
   */
  createGlobal (implementation, interface_, version, bindCallback) {
    const name = ++this._nextGlobalName
    const global = new Global(this, implementation, interface_, version, name, bindCallback)
    this._globals[name] = global
    this._registryResources.forEach(registryResource => registryResource.global(global.name, global.interface_, global.version))
    return global
  }

  /**
   * Unregister a global and revoke it from clients.
   *
   * @param {Global} global
   */
  destroyGlobal (global) {
    if (this._globals[global.name]) {
      delete this._globals[global.name]
      this._registryResources.forEach(registryResource => registryResource.globalRemove(global.name))
    }
  }

  /**
   * @param {RegistryResource} registryResource
   */
  publishGlobals (registryResource) {
    Object.entries(this._globals).forEach(([name, global]) => registryResource.global(Number.parseInt(name), global.interface_, global.version))
  }

  /**
   *
   * @param {Client} client
   * @param {number} id
   */
  createRegistryResource (client, id) {
    const registryResource = new RegistryResource(client, id, 1)
    registryResource.implementation = this
    this._registryResources.push(registryResource)
    return registryResource
  }

  /**
   * Binds a new, client-created object to the server using the
   * specified name as the identifier.
   * @param {Client}client
   * @param {RegistryResource}resource
   * @param {number}name unique numeric name of the object
   * @param {string}interface_
   * @param {number}version
   * @param {number}id bounded object
   * @override
   */
  bind (client, resource, name, interface_, version, id) {
    this._globals[name].bindClient(client, id, version)
  }
}

module.exports = Registry<|endoftext|>


<commit_before>var express = require('express');
var models = require('../models.js').models;
var collections = require('../models.js').collections;

var projectController = {};

projectController.getAllProjects = function (req, res) {
  models.Project
    .fetchAll({
      withRelated: ['user']
    })
    .then(function (coll) {
      res.send(coll.toJSON());
    })
};

projectController.get = function (req, res) {
  //dummy data, currently an array of projects as objects
  res.json([{
    name: 'doc1',
    createdAt: 'Fri, 19 Dec 2014 00:58:17 GMT'
  }, {
    name: 'doc2',
    createdAt: 'Tue, 16 Dec 2014 00:58:17 GMT'
  }, {
    name: 'doc3',
    createdAt: 'Tue, 16 Dec 2014 00:58:17 GMT'
  }, {
    name: 'doc4',
    createdAt: 'Tue, 16 Dec 2014 00:58:17 GMT'
  }]);
};

projectController.getSpecificProject = function (req, res) {

  console.log(req.params.id);
  models.Project
    .query('where', 'id', '=', req.params.id)
    .fetch({
      withRelated: ['user']
    })
    .then(function (coll) {
      // console.log('RES !!!!!!!!!!!', res);
      // console.log('COLl !!!!!!!!!!!!!!!!!!!!!', coll);
      res.send(coll);
    })
};

projectController.put = function (req, res) {
  res.status(200).end();
};

// projectController.getProject = function (req, res) {
//   //dummy data
//   res.json({
//     indexhtml: 'htmlcodehtmlcode'
//   });
// };

projectController.put = function (req, res) {
  //add users
  //add files
  //remove users
  res.status(200).end();
};

projectController.delete = function (req, res) {
  res.status(200).end();
};

module.exports = projectController;<commit_msg>Fix rebase/merge mess<commit_after>var express = require('express');
var models = require('../models.js').models;
var collections = require('../models.js').collections;

var projectController = {};

projectController.getAllProjects = function (req, res) {
  models.Project
    .fetchAll({
      withRelated: ['user']
    })
    .then(function (coll) {
      res.send(coll.toJSON());
    })
};

projectController.getSpecificProject = function (req, res) {
  models.Project
    .query('where', 'id', '=', req.params.id)
    .fetch({
      withRelated: ['user']
    })
    .then(function (coll) {
      // console.log('RES !!!!!!!!!!!', res);
      // console.log('COLl !!!!!!!!!!!!!!!!!!!!!', coll);
      res.send(coll);
    })
};

projectController.put = function (req, res) {
  res.status(200).end();
};

// projectController.getProject = function (req, res) {
//   //dummy data
//   res.json({
//     indexhtml: 'htmlcodehtmlcode'
//   });
// };

projectController.put = function (req, res) {
  //add users
  //add files
  //remove users
  res.status(200).end();
};

projectController.delete = function (req, res) {
  res.status(200).end();
};

module.exports = projectController;<|endoftext|>


<commit_before>module.exports = function getOne (req, res) {
	var request = require('request');

	if(req.query && req.query.url)
    	request.get(req.query.url).pipe(res);
    else
    	res.sendStatus(400);
}<commit_msg>server side: handle image proxy pipe errors<commit_after>module.exports = function getOne (req, res) {
	var request = require('request');

	if(req.query && req.query.url){
		var stream = request.get(req.query.url);
		stream.on('error', function(e){
			res.status(400).json({error: "Bad url params"});
		});

		stream.pipe(res).on('error', function(e){
			res.status(400).json({error: "Bad url params"});
		});
	}else{
    	res.sendStatus(400);
	}
}<|endoftext|>


<commit_before>var _ = require('lodash'),
    redis = require('redis'),
    socketIo = require('socket.io'),
    mongoose = require('mongoose'),
    Alert = mongoose.model('Alert'),
    permissionsManager = require('../controllers/permissionsManager')(Alert);

module.exports = function(server){
    var io = socketIo.listen(server);
    var redisPubSubClient = redis.createClient();
    var redisKeyStoreClient = redis.createClient();

    var num_connections = 0;
    var socketId_user_map = {};

    var ascertainPermissions = function(socketId, doc){
        var permissions = permissionsManager.ascertainBasicPermissions(doc);
        var user = socketId_user_map[socketId];

        if(user){
            permissions = permissionsManager.ascertainPermissions(user, doc);
        }

        return permissions;
    };

    var stripDoc = function(doc, permissions){
        //remove all field for which the user does not have read access
        var _doc;
        if(doc.toObject){
            //convert mongoose model to POJO
            _doc = doc.toObject();
        }
        else{
            //if doc is already a POJO, create a copy
            _doc = _.extend({}, doc);
        }
        _doc = permissionsManager.removeNonPermitedFields(permissions, _doc);
        return _doc;
    };

    var filterDocs = function(socketId, docs){
        //remove the docs that user does not have permission to view
        //for remaining docs, remove fields that user does not have permission to view
        var _docs = [];
        docs.forEach(function(doc){
            var permissions = ascertainPermissions(socketId, doc);

            if(!doc.published && !_.contains(permissions, Alert.readUnpublishedPermission())){
                console.log('socket', socketId, 'user cant view unpublished Alert', doc._id);
                return;
            }

            var _doc = stripDoc(doc, permissions);
            _docs.push(_doc);
        });
        return _docs;
    };

    var getRedisItems = function(key, callback){
        redisKeyStoreClient.lrange(key, 0, -1, function(err, items){
            if(err){
                console.error('error retrieving', key, 'from redis. error', err);
                if(callback){
                    callback(err);
                }
            }
            else{
                console.log('key', key, 'retrieved', items.length,'from redis');
                if(callback){
                    callback(err, items);
                }
            }
        });
    };

    var handleSocketConnection = function(socket){
        //connecting user may have missed out on all previous transmissions, get them up to speed -
        //retrieve all previously emitted messages from redis and send to user
        getRedisItems('alerts',function(err, items){
            if(!err){
                var _docs = filterDocs(socket.id, items);

                console.log('sending', _docs.length, 'out of', items.length,' items to socket', socket.id);
                io.sockets.connected[socket.id].emit('alerts', _docs);
            }
        });
    };

    var emitToAllSockets = function(doc, channel) {
        if (!channel) {
            channel = 'alert';
        }
        for (var socketId in io.sockets.connected) {
            var permissions = ascertainPermissions(socketId, doc);

            //prevent user from viewing unpublished content unless they have permission to do so
            //see baseController.get for more details
            if (!doc.published && !_.contains(permissions, Alert.readUnpublishedPermission())) {
                console.log('socket', socketId, 'user cant view unpublished Alert', doc._id);
                continue;
            }

            var _doc = stripDoc(doc, permissions);
            console.log('emitting doc', doc._id, 'to socket', socketId, 'on channel', channel);
            io.sockets.connected[socketId].emit(channel, _doc);
        }
    };

    io.sockets.on('connection', function(socket) {
        console.log('connection to socket', socket.id, '. num_connections:', ++num_connections);

        socket.on('authenicated_connection', function(user){
            console.log('user', user._id, 'connected to socket', socket.id);
            socketId_user_map[socket.id] = user;
            handleSocketConnection(socket);
        });

        socket.on('anonymous_connection', function(){
            console.log('anonymous connection to socket', socket.id);
            handleSocketConnection(socket);
        });

        socket.on('disconnect', function(){
            console.log('user disconnected. num_connections', --num_connections);
            delete socketId_user_map[socket.id];
        });
    });

    //TODO: enddate >= today
    var stream = Alert.find().stream();

    //clear cache on startups
    redisKeyStoreClient.del('alerts');

    stream.on('data', function (doc) {
        //note: there may be as few a 0 users connected at this point, meaning that noone may see this initial data
        //hence, it is stored in redis, so that it will be accessible to all who join later
        console.log('Alert stream doc', doc._id, 'num_connections emitting to:', num_connections);

        emitToAllSockets(doc);
        emitToAllSockets(doc);

        redisKeyStoreClient.rpush('alerts', JSON.stringify(doc));
    });

    stream.on('error', function (err) {
        console.error('Alert stream error', err);
    });

    stream.on('close', function () {
        console.log('Alert stream closed');
    });

    redisPubSubClient.on('pmessage', function(pattern, channel, message){
        //ex[expecting message to be the result of JSON.stringify(doc), doc being a mongoose model
        //expecting channel to be of the formar 'alerts.created', 'alerts.updated', etc
        console.log('redis - pattern', pattern, 'recieved message', message, 'on channel', channel);

        var type = channel.split('.')[1];
        var _doc = JSON.parse(message);

        emitToAllSockets(_doc, channel);

        if(type == 'created'){
            console.log('created redis alert', _doc._id);

            redisKeyStoreClient.rpush('alerts', message);
        }
        else if(type == 'updated'){
            getRedisItems('alerts', function(err, items){
                if(err){
                    return err;
                }
                console.log('updated redis alert', _doc._id);

                redisKeyStoreClient.del('alerts');
                items.forEach(function(item){
                    var __doc = JSON.parse(item);
                    if( _doc._id == __doc._id){
                        item = _doc;
                    }
                    redisKeyStoreClient.rpush('alerts', item);
                });
            });
        }
        else if(type == 'deleted'){
            getRedisItems('alerts', function(err, items){
                if(err){
                   return err;
                }
                var _docs = items.filter(function(item){
                    return _doc._id != item._id;
                });

                redisKeyStoreClient.set('alerts', _docs);
            });
        }
    });

    redisPubSubClient.on('psubscribe', function(pattern, count){
        console.log('redis subscribed to pattern',pattern, 'count', count);
    });

    redisPubSubClient.on("error", function (err) {
        console.error("redisPubSubClient error " + err);
    });

    redisKeyStoreClient.on("error", function (err) {
        console.error("redisKeyStoreClient error " + err);
    });

    redisPubSubClient.psubscribe('alert.*');
};
<commit_msg>Fixed redis alerts.deleted handlign logic such that redis key values are properly set. Fixed bug in redis alerts.updated handling logic where objects were not being stringified.<commit_after>var _ = require('lodash'),
    redis = require('redis'),
    socketIo = require('socket.io'),
    mongoose = require('mongoose'),
    Alert = mongoose.model('Alert'),
    permissionsManager = require('../controllers/permissionsManager')(Alert);

module.exports = function(server){
    var io = socketIo.listen(server);
    var redisPubSubClient = redis.createClient();
    var redisKeyStoreClient = redis.createClient();

    var num_connections = 0;
    var socketId_user_map = {};

    var ascertainPermissions = function(socketId, doc){
        var permissions = permissionsManager.ascertainBasicPermissions(doc);
        var user = socketId_user_map[socketId];

        if(user){
            permissions = permissionsManager.ascertainPermissions(user, doc);
        }

        return permissions;
    };

    var stripDoc = function(doc, permissions){
        //remove all field for which the user does not have read access
        var _doc;
        if(doc.toObject){
            //convert mongoose model to POJO
            _doc = doc.toObject();
        }
        else{
            //if doc is already a POJO, create a copy
            _doc = _.extend({}, doc);
        }
        _doc = permissionsManager.removeNonPermitedFields(permissions, _doc);
        return _doc;
    };

    var filterDocs = function(socketId, docs){
        //remove the docs that user does not have permission to view
        //for remaining docs, remove fields that user does not have permission to view
        var _docs = [];
        docs.forEach(function(doc){
            var permissions = ascertainPermissions(socketId, doc);

            if(!doc.published && !_.contains(permissions, Alert.readUnpublishedPermission())){
                console.log('socket', socketId, 'user cant view unpublished Alert', doc._id);
                return;
            }

            var _doc = stripDoc(doc, permissions);
            _docs.push(_doc);
        });
        return _docs;
    };

    var getRedisItems = function(key, callback){
        redisKeyStoreClient.lrange(key, 0, -1, function(err, items){
            if(err){
                console.error('error retrieving', key, 'from redis. error', err);
                if(callback){
                    callback(err);
                }
            }
            else{
                console.log('key', key, 'retrieved', items.length,'from redis');
                if(callback){
                    callback(err, items);
                }
            }
        });
    };

    var handleSocketConnection = function(socket){
        //connecting user may have missed out on all previous transmissions, get them up to speed -
        //retrieve all previously emitted messages from redis and send to user
        getRedisItems('alerts',function(err, items){
            if(!err){
                var _docs = filterDocs(socket.id, items);

                console.log('sending', _docs.length, 'out of', items.length,' items to socket', socket.id);
                io.sockets.connected[socket.id].emit('alerts', _docs);
            }
        });
    };

    var emitToAllSockets = function(doc, channel) {
        if (!channel) {
            channel = 'alert';
        }
        for (var socketId in io.sockets.connected) {
            var permissions = ascertainPermissions(socketId, doc);

            //prevent user from viewing unpublished content unless they have permission to do so
            //see baseController.get for more details
            if (!doc.published && !_.contains(permissions, Alert.readUnpublishedPermission())) {
                console.log('socket', socketId, 'user cant view unpublished Alert', doc._id);
                continue;
            }

            var _doc = stripDoc(doc, permissions);
            console.log('emitting doc', doc._id, 'to socket', socketId, 'on channel', channel);
            io.sockets.connected[socketId].emit(channel, _doc);
        }
    };

    io.sockets.on('connection', function(socket) {
        console.log('connection to socket', socket.id, '. num_connections:', ++num_connections);

        socket.on('authenicated_connection', function(user){
            console.log('user', user._id, 'connected to socket', socket.id);
            socketId_user_map[socket.id] = user;
            handleSocketConnection(socket);
        });

        socket.on('anonymous_connection', function(){
            console.log('anonymous connection to socket', socket.id);
            handleSocketConnection(socket);
        });

        socket.on('disconnect', function(){
            console.log('user disconnected. num_connections', --num_connections);
            delete socketId_user_map[socket.id];
        });
    });

    //TODO: enddate >= today
    var stream = Alert.find().stream();

    //clear cache on startups
    redisKeyStoreClient.del('alerts');

    stream.on('data', function (doc) {
        //note: there may be as few a 0 users connected at this point, meaning that noone may see this initial data
        //hence, it is stored in redis, so that it will be accessible to all who join later
        console.log('Alert stream doc', doc._id, 'num_connections emitting to:', num_connections);

        emitToAllSockets(doc);
        emitToAllSockets(doc);

        redisKeyStoreClient.rpush('alerts', JSON.stringify(doc));
    });

    stream.on('error', function (err) {
        console.error('Alert stream error', err);
    });

    stream.on('close', function () {
        console.log('Alert stream closed');
    });

    redisPubSubClient.on('pmessage', function(pattern, channel, message){
        //ex[expecting message to be the result of JSON.stringify(doc), doc being a mongoose model
        //expecting channel to be of the formar 'alerts.created', 'alerts.updated', etc
        console.log('redis - pattern', pattern, 'recieved message', message, 'on channel', channel);

        var type = channel.split('.')[1];
        var _doc = JSON.parse(message);

        emitToAllSockets(_doc, channel);

        if(type == 'created'){
            console.log('created redis alert', _doc._id);
            redisKeyStoreClient.rpush('alerts', message);
        }
        else if(type == 'updated'){
            getRedisItems('alerts', function(err, items){
                if(err){
                    return err;
                }
                console.log('updated redis alert', _doc._id);

                redisKeyStoreClient.del('alerts');
                items.forEach(function(item){
                    var __doc = JSON.parse(item);
                    if( _doc._id == __doc._id){
                        item = JSON.stringify(_doc);
                    }
                    redisKeyStoreClient.rpush('alerts', item);
                });
            });
        }
        else if(type == 'deleted'){
            getRedisItems('alerts', function(err, items){
                if(err){
                   return err;
                }
                console.log('deleted redis alert', _doc._id);

                redisKeyStoreClient.del('alerts');
                items.forEach(function(item){
                    var __doc = JSON.parse(item);
                    if( _doc._id == __doc._id){
                        return;
                    }
                    redisKeyStoreClient.rpush('alerts', item);
                });
            });
        }
    });

    redisPubSubClient.on('psubscribe', function(pattern, count){
        console.log('redis subscribed to pattern',pattern, 'count', count);
    });

    redisPubSubClient.on("error", function (err) {
        console.error("redisPubSubClient error " + err);
    });

    redisKeyStoreClient.on("error", function (err) {
        console.error("redisKeyStoreClient error " + err);
    });

    redisPubSubClient.psubscribe('alert.*');
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * Copyright 2017 Google Inc. All rights reserved.
 * Modifications copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const path = require('path');
const {Registry} = require('../lib/utils/registry');
const fs = require('fs');
const protocolGenerator = require('./protocol-types-generator');
const {execSync} = require('child_process');

const SCRIPT_NAME = path.basename(__filename);
const ROOT_PATH = path.resolve(path.join(__dirname, '..'));

function usage() {
  return `
usage: ${SCRIPT_NAME} <browser> <revision>

Roll the <browser> to a specific <revision> and generate new protocol.
Supported browsers: chromium, firefox, webkit, ffmpeg, firefox-beta.

Example:
  ${SCRIPT_NAME} chromium 123456
`;
}

(async () => {
  // 1. Parse CLI arguments
  const args = process.argv.slice(2);
  if (args.some(arg => arg === '--help')) {
    console.log(usage());
    process.exit(1);
  } else if (args.length < 1) {
    console.log(`Please specify the browser name, e.g. 'chromium'.`);
    console.log(`Try running ${SCRIPT_NAME} --help`);
    process.exit(1);
  } else if (args.length < 2) {
    console.log(`Please specify the revision`);
    console.log(`Try running ${SCRIPT_NAME} --help`);
    process.exit(1);
  }
  const browsersJSON = require(path.join(ROOT_PATH, 'browsers.json'));
  const browserName = args[0].toLowerCase();
  const descriptor = browsersJSON.browsers.find(b => b.name === browserName);
  if (!descriptor) {
    console.log(`Unknown browser "${browserName}"`);
    console.log(`Try running ${SCRIPT_NAME} --help`);
    process.exit(1);
  }
  const revision = args[1];
  console.log(`Rolling ${browserName} to ${revision}`);

  // 2. Update browsers.json.
  console.log('\nUpdating browsers.json...');
  descriptor.revision = String(revision);
  if (browserName === 'chromium')
    browsersJSON.browsers.find(b => b.name === 'chromium-with-symbols').revision = String(revision);
  fs.writeFileSync(path.join(ROOT_PATH, 'browsers.json'), JSON.stringify(browsersJSON, null, 2) + '\n');

  if (descriptor.installByDefault) {
    // 3. Download new browser.
    console.log('\nDownloading new browser...');
    const registry = new Registry(browsersJSON);
    await registry.install();

    // 4. Generate types.
    console.log('\nGenerating protocol types...');
    const executablePath = registry.findExecutable(browserName).executablePathOrDie();
    await protocolGenerator.generateProtocol(browserName, executablePath).catch(console.warn);

    // 5. Update docs.
    console.log('\nUpdating documentation...');
    try {
      process.stdout.write(execSync('npm run --silent doc'));
    } catch (e) {
    }

    if (browserName === 'chromium') {
      // 5. Update chromedriver.
      console.log('\nUpdating chromedriver...');
      try {
        process.stdout.write(execSync('npm install --save-dev chromedriver@latest'));
      } catch (e) {
      }
    }
  }
  console.log(`\nRolled ${browserName} to ${revision}`);
})().catch(err => {
  console.error(err);
  process.exit(1);
});

<commit_msg>chore: fix utils/roll_browser.js after #9078<commit_after>#!/usr/bin/env node
/**
 * Copyright 2017 Google Inc. All rights reserved.
 * Modifications copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const path = require('path');
const {Registry} = require('../lib/utils/registry');
const fs = require('fs');
const protocolGenerator = require('./protocol-types-generator');
const {execSync} = require('child_process');

const SCRIPT_NAME = path.basename(__filename);
const ROOT_PATH = path.resolve(path.join(__dirname, '..'));

function usage() {
  return `
usage: ${SCRIPT_NAME} <browser> <revision>

Roll the <browser> to a specific <revision> and generate new protocol.
Supported browsers: chromium, firefox, webkit, ffmpeg, firefox-beta.

Example:
  ${SCRIPT_NAME} chromium 123456
`;
}

(async () => {
  // 1. Parse CLI arguments
  const args = process.argv.slice(2);
  if (args.some(arg => arg === '--help')) {
    console.log(usage());
    process.exit(1);
  } else if (args.length < 1) {
    console.log(`Please specify the browser name, e.g. 'chromium'.`);
    console.log(`Try running ${SCRIPT_NAME} --help`);
    process.exit(1);
  } else if (args.length < 2) {
    console.log(`Please specify the revision`);
    console.log(`Try running ${SCRIPT_NAME} --help`);
    process.exit(1);
  }
  const browsersJSON = require(path.join(ROOT_PATH, 'browsers.json'));
  const browserName = args[0].toLowerCase();
  const descriptor = browsersJSON.browsers.find(b => b.name === browserName);
  if (!descriptor) {
    console.log(`Unknown browser "${browserName}"`);
    console.log(`Try running ${SCRIPT_NAME} --help`);
    process.exit(1);
  }
  const revision = args[1];
  console.log(`Rolling ${browserName} to ${revision}`);

  // 2. Update browsers.json.
  console.log('\nUpdating browsers.json...');
  descriptor.revision = String(revision);
  if (browserName === 'chromium')
    browsersJSON.browsers.find(b => b.name === 'chromium-with-symbols').revision = String(revision);
  fs.writeFileSync(path.join(ROOT_PATH, 'browsers.json'), JSON.stringify(browsersJSON, null, 2) + '\n');

  if (descriptor.installByDefault) {
    // 3. Download new browser.
    console.log('\nDownloading new browser...');
    const registry = new Registry(browsersJSON);
    const executables = registry.defaultExecutables();
    await registry.install(executables);

    // 4. Generate types.
    console.log('\nGenerating protocol types...');
    const executablePath = registry.findExecutable(browserName).executablePathOrDie();
    await protocolGenerator.generateProtocol(browserName, executablePath).catch(console.warn);

    // 5. Update docs.
    console.log('\nUpdating documentation...');
    try {
      process.stdout.write(execSync('npm run --silent doc'));
    } catch (e) {
    }

    if (browserName === 'chromium') {
      // 5. Update chromedriver.
      console.log('\nUpdating chromedriver...');
      try {
        process.stdout.write(execSync('npm install --save-dev chromedriver@latest'));
      } catch (e) {
      }
    }
  }
  console.log(`\nRolled ${browserName} to ${revision}`);
})().catch(err => {
  console.error(err);
  process.exit(1);
});

<|endoftext|>


<commit_before>var Class = require('../utils/Class');

// A Set is a collection of unique elements.
var Set = new Class({

    initialize:

    function Set (elements)
    {
        this.entries = [];

        if (Array.isArray(elements))
        {
            for (var i = 0; i < elements.length; i++)
            {
                this.set(elements[i]);
            }
        }
    },

    set: function (value)
    {
        if (this.entries.indexOf(value) === -1)
        {
            this.entries.push(value);
        }

        return this;
    },

    get: function (property, value)
    {
        for (var i = 0; i < this.entries.length; i++)
        {
            var entry = this.entries[i];

            if (entry[property] === value)
            {
                return entry;
            }
        }
    },

    getArray: function ()
    {
        return this.entries.slice(0);
    },

    delete: function (value)
    {
        var index = this.entries.indexOf(value);

        if (index > -1)
        {
            this.entries.splice(index, 1);
        }

        return this;
    },

    dump: function ()
    {
        console.group('Set');

        for (var i = 0; i < this.entries.length; i++)
        {
            var entry = this.entries[i];
            console.log(entry);
        }

        console.groupEnd();
    },

    //  For when you know this Set will be modified during the iteration
    each: function (callback, callbackScope)
    {
        var i;
        var temp = this.entries.slice();
        var len = temp.length;

        if (callbackScope)
        {
            for (i = 0; i < len; i++)
            {
                if (callback.call(callbackScope, temp[i], i) === false)
                {
                    break;
                }
            }
        }
        else
        {
            for (i = 0; i < len; i++)
            {
                if (callback(temp[i], i) === false)
                {
                    break;
                }
            }
        }

        return this;
    },

    //  For when you absolutely know this Set won't be modified during the iteration
    iterate: function (callback, callbackScope)
    {
        var i;
        var len = this.entries.length;

        if (callbackScope)
        {
            for (i = 0; i < len; i++)
            {
                if (callback.call(callbackScope, this.entries[i], i) === false)
                {
                    break;
                }
            }
        }
        else
        {
            for (i = 0; i < len; i++)
            {
                if (callback(this.entries[i], i) === false)
                {
                    break;
                }
            }
        }

        return this;
    },

    clear: function ()
    {
        this.entries.length = 0;

        return this;
    },

    contains: function (value)
    {
        return (this.entries.indexOf(value) > -1);
    },

    union: function (set)
    {
        var newSet = new Set();

        set.values.forEach(function (value)
        {
            newSet.add(value);
        });

        this.entries.forEach(function (value)
        {
            newSet.add(value);
        });

        return newSet;
    },

    intersect: function (set)
    {
        var newSet = new Set();

        this.entries.forEach(function (value)
        {
            if (set.contains(value))
            {
                newSet.add(value);
            }
        });

        return newSet;
    },

    difference: function (set)
    {
        var newSet = new Set();

        this.entries.forEach(function (value)
        {
            if (!set.contains(value))
            {
                newSet.add(value);
            }
        });

        return newSet;
    },

    size: {

        get: function ()
        {
            return this.entries.length;
        },

        set: function (value)
        {
            return this.entries.length = value;
        }

    }

});

module.exports = Set;
<commit_msg>New Set.iterateLocal method<commit_after>var Class = require('../utils/Class');

// A Set is a collection of unique elements.
var Set = new Class({

    initialize:

    function Set (elements)
    {
        this.entries = [];

        if (Array.isArray(elements))
        {
            for (var i = 0; i < elements.length; i++)
            {
                this.set(elements[i]);
            }
        }
    },

    set: function (value)
    {
        if (this.entries.indexOf(value) === -1)
        {
            this.entries.push(value);
        }

        return this;
    },

    get: function (property, value)
    {
        for (var i = 0; i < this.entries.length; i++)
        {
            var entry = this.entries[i];

            if (entry[property] === value)
            {
                return entry;
            }
        }
    },

    getArray: function ()
    {
        return this.entries.slice(0);
    },

    delete: function (value)
    {
        var index = this.entries.indexOf(value);

        if (index > -1)
        {
            this.entries.splice(index, 1);
        }

        return this;
    },

    dump: function ()
    {
        console.group('Set');

        for (var i = 0; i < this.entries.length; i++)
        {
            var entry = this.entries[i];
            console.log(entry);
        }

        console.groupEnd();
    },

    //  For when you know this Set will be modified during the iteration
    each: function (callback, callbackScope)
    {
        var i;
        var temp = this.entries.slice();
        var len = temp.length;

        if (callbackScope)
        {
            for (i = 0; i < len; i++)
            {
                if (callback.call(callbackScope, temp[i], i) === false)
                {
                    break;
                }
            }
        }
        else
        {
            for (i = 0; i < len; i++)
            {
                if (callback(temp[i], i) === false)
                {
                    break;
                }
            }
        }

        return this;
    },

    //  For when you absolutely know this Set won't be modified during the iteration
    iterate: function (callback, callbackScope)
    {
        var i;
        var len = this.entries.length;

        if (callbackScope)
        {
            for (i = 0; i < len; i++)
            {
                if (callback.call(callbackScope, this.entries[i], i) === false)
                {
                    break;
                }
            }
        }
        else
        {
            for (i = 0; i < len; i++)
            {
                if (callback(this.entries[i], i) === false)
                {
                    break;
                }
            }
        }

        return this;
    },

    iterateLocal: function (callbackKey)
    {
        var i;
        var args = [];

        for (i = 1; i < arguments.length; i++)
        {
            args.push(arguments[i]);
        }

        var len = this.entries.length;

        for (i = 0; i < len; i++)
        {
            var entry = this.entries[i];

            entry[callbackKey].apply(entry, args);
        }

        return this;
    },

    clear: function ()
    {
        this.entries.length = 0;

        return this;
    },

    contains: function (value)
    {
        return (this.entries.indexOf(value) > -1);
    },

    union: function (set)
    {
        var newSet = new Set();

        set.values.forEach(function (value)
        {
            newSet.add(value);
        });

        this.entries.forEach(function (value)
        {
            newSet.add(value);
        });

        return newSet;
    },

    intersect: function (set)
    {
        var newSet = new Set();

        this.entries.forEach(function (value)
        {
            if (set.contains(value))
            {
                newSet.add(value);
            }
        });

        return newSet;
    },

    difference: function (set)
    {
        var newSet = new Set();

        this.entries.forEach(function (value)
        {
            if (!set.contains(value))
            {
                newSet.add(value);
            }
        });

        return newSet;
    },

    size: {

        get: function ()
        {
            return this.entries.length;
        },

        set: function (value)
        {
            return this.entries.length = value;
        }

    }

});

module.exports = Set;
<|endoftext|>


<commit_before>var utils  = require('../utils');

/**
 * session
 *
 * Takes a list of files and creates a set of file names that occur in subject
 * directories. Then generates a warning if a given subject is missing any
 * files from the set.
 */
var session = function missingSessionFiles(fileList) {
    var subjects = [];
    var issues = [];
    for (var key in fileList) {
        var file = fileList[key];
        var filename;

        if (!file || (typeof window != 'undefined' && !file.webkitRelativePath)) {
            continue;
        }

        var path = utils.files.relativePath(file);
        if (!utils.type.isBIDS(path)) {
            continue;
        }
        var subject;
        //match the subject identifier up to the '/' in the full path to a file.
        var match = path.match(/sub-(.*?)(?=\/)/);
        if (match === null) {
            continue;
        } else {
            subject = match[0];
        }
        // initialize an empty array if we haven't seen this subject before
        if (typeof(subjects[subject]) === 'undefined') {
            subjects[subject] = [];
        }
        // files are prepended with subject name, the following two commands
        // remove the subject from the file name to allow filenames to be more
        // easily compared
        filename = path.substring(path.match(subject).index + subject.length);
        filename = filename.replace(subject, '<sub>');
        subjects[subject].push(filename);
    }

    var subject_files = [];
    for (var subjKey in subjects) {
        subject = subjects[subjKey];
        for (var i = 0; i < subject.length; i++) {
            file = subject[i];
            if (subject_files.indexOf(file) < 0) {
                subject_files.push(file);
            }
        }
    }

    subjects.sort();
    for (subject in subjects) {
        for (var set_file in subject_files) {
            if (subjects[subject].indexOf(subject_files[set_file]) === -1) {
                var fileThatsMissing = '/' + subject + subject_files[set_file].replace('<sub>', subject);
                issues.push(new utils.Issue({
                    file: {relativePath: fileThatsMissing},
                    //evidence: "Subject: " + subject + "; Missing file.",
                    code: 38
                }));
            }
        }
    }
    return issues;
};

module.exports = session;
<commit_msg>remove commented out line<commit_after>var utils  = require('../utils');

/**
 * session
 *
 * Takes a list of files and creates a set of file names that occur in subject
 * directories. Then generates a warning if a given subject is missing any
 * files from the set.
 */
var session = function missingSessionFiles(fileList) {
    var subjects = [];
    var issues = [];
    for (var key in fileList) {
        var file = fileList[key];
        var filename;

        if (!file || (typeof window != 'undefined' && !file.webkitRelativePath)) {
            continue;
        }

        var path = utils.files.relativePath(file);
        if (!utils.type.isBIDS(path)) {
            continue;
        }
        var subject;
        //match the subject identifier up to the '/' in the full path to a file.
        var match = path.match(/sub-(.*?)(?=\/)/);
        if (match === null) {
            continue;
        } else {
            subject = match[0];
        }
        // initialize an empty array if we haven't seen this subject before
        if (typeof(subjects[subject]) === 'undefined') {
            subjects[subject] = [];
        }
        // files are prepended with subject name, the following two commands
        // remove the subject from the file name to allow filenames to be more
        // easily compared
        filename = path.substring(path.match(subject).index + subject.length);
        filename = filename.replace(subject, '<sub>');
        subjects[subject].push(filename);
    }

    var subject_files = [];
    for (var subjKey in subjects) {
        subject = subjects[subjKey];
        for (var i = 0; i < subject.length; i++) {
            file = subject[i];
            if (subject_files.indexOf(file) < 0) {
                subject_files.push(file);
            }
        }
    }

    subjects.sort();
    for (subject in subjects) {
        for (var set_file in subject_files) {
            if (subjects[subject].indexOf(subject_files[set_file]) === -1) {
                var fileThatsMissing = '/' + subject + subject_files[set_file].replace('<sub>', subject);
                issues.push(new utils.Issue({
                    file: {relativePath: fileThatsMissing},
                    code: 38
                }));
            }
        }
    }
    return issues;
};

module.exports = session;
<|endoftext|>


<commit_before>var set = Ember.set;

Ember.onLoad('application', function(app) {
  app.registerInjection(function(app, stateManager, property) {
    if (property === 'Store') {
      set(stateManager, 'store', app[property].create());
    }
  });
});
<commit_msg>Update to new injection syntax<commit_after>var set = Ember.set;

Ember.onLoad('application', function(app) {
  app.registerInjection({
    name: "store",
    before: "controllers",

    injection: function(app, stateManager, property) {
      if (property === 'Store') {
        set(stateManager, 'store', app[property].create());
      }
    }
  });
});
<|endoftext|>


<commit_before>/**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/

/* global Uint8Array, FileReader */

const ExifImage = require(`exif`).ExifImage;

/**
* Draws the image on the canvas so that the thumbnail
* could be generated
* @param {Object} options(orientation: image exif orientation range from 1-8, img: Image object, x: start x-axis, y: start y-axis, width: width of the thumbnail, height: height of the thumbnail, ctx: canvas context)
* @returns {Object}
*/
export function drawImage(options) {
  // save current context before applying transformations
  options.ctx.save();
  let rad;
  // convert degrees to radians
  if (options.flip) {
    rad = options.deg * Math.PI / 180;
  }
  else {
    rad = 2 * Math.PI - options.deg * Math.PI / 180;
  }
  // set the origin to the center of the image
  options.ctx.translate(options.x + options.width / 2, options.y + options.height / 2);
  // rotate the canvas around the origin
  options.ctx.rotate(rad);
  if (options.flip) {
    // flip the canvas
    options.ctx.scale(-1, 1);
  }
  // draw the image
  options.ctx.drawImage(options.img, -options.width / 2, -options.height / 2, options.width, options.height);
  // restore the canvas
  options.ctx.restore();
}

/**
* Updates the image file with exif information, required to correctly rotate the image activity
* @param {Object} file
* @returns {Promise<Object>}
*/
export function updateImageOrientation(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function onload() {
      const arrayBuffer = reader.result;
      const buf = new Buffer(arrayBuffer.byteLength);
      const view = new Uint8Array(arrayBuffer);
      for (let i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
      }
      resolve(buf);
    };
  })
  .then((buf) => readExifData(file, buf));
}

/**
* Adds exif orientation information on the image file
* @param {Object} file
* @param {Object} buf
* @returns {Promise<ExifImage>}
*/
export function readExifData(file, buf) {
  return new Promise((resolve) => {
    // For avatar images the file.type is set as image/jpeg, however for images shared in an activity file.mimeType is set as image/jpeg. Handling both conditions.
    if (file && file.image && (file.type === `image/jpeg` || file.mimeType === `image/jpeg`)) {
      /* eslint-disable no-new */
      new ExifImage({image: buf}, (error, exifData) => {
        if (!error && exifData) {
          file.image.orientation = exifData.image.Orientation;
        }
        resolve(buf);
      });
    }
    else {
      resolve(buf);
    }
  });
}

/* eslint complexity: ["error", 9] */
/**
* Rotates/flips the image on the canvas as per exif information
* @param {Object} options
* @param {Object} file
* @returns {Object}
*/
export function orient(options, file) {
  if (file && file.image && file.image.orientation && file.image.orientation !== 1) {
    const image = {
      img: options.img,
      x: options.x,
      y: options.y,
      width: options.width,
      height: options.height,
      deg: 0,
      flip: true,
      ctx: options.ctx
    };
    switch (options && options.orientation) {
    case 3:
      // rotateImage180
      image.deg = 180;
      image.flip = false;
      break;
    case 4:
      // rotate180AndFlipImage
      image.deg = 180;
      image.flip = true;
      break;
    case 5:
      // rotate90AndFlipImage
      image.deg = 270;
      image.flip = true;
      break;
    case 6:
      // rotateImage90
      image.deg = 270;
      image.flip = false;
      break;
    case 7:
      // rotateNeg90AndFlipImage
      image.deg = 90;
      image.flip = true;
      break;
    case 8:
      // rotateNeg90
      image.deg = 90;
      image.flip = false;
      break;
    default:
      break;
    }
    drawImage(image);
  }
  else {
    options.ctx.drawImage(options.img, options.x, options.y, options.width, options.height);
  }
}
<commit_msg>docs(helper-image): added documentation for options passed to image orientation function<commit_after>/**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/

/* global Uint8Array, FileReader */

const ExifImage = require(`exif`).ExifImage;

/**
* Draws the image on the canvas so that the thumbnail
* could be generated
* @param {Object} options(options(orientation: image exif orientation range from 1-8, img: Image object, x: start x-axis, y: start y-axis, width: width of the thumbnail, height: height of the thumbnail, deg: counterclockwise degree rotation, flip: flip Image, ctx: canvas context))
* @returns {Object}
*/
export function drawImage(options) {
  // save current context before applying transformations
  options.ctx.save();
  let rad;
  // convert degrees to radians
  if (options.flip) {
    rad = options.deg * Math.PI / 180;
  }
  else {
    rad = 2 * Math.PI - options.deg * Math.PI / 180;
  }
  // set the origin to the center of the image
  options.ctx.translate(options.x + options.width / 2, options.y + options.height / 2);
  // rotate the canvas around the origin
  options.ctx.rotate(rad);
  if (options.flip) {
    // flip the canvas
    options.ctx.scale(-1, 1);
  }
  // draw the image
  options.ctx.drawImage(options.img, -options.width / 2, -options.height / 2, options.width, options.height);
  // restore the canvas
  options.ctx.restore();
}

/**
* Updates the image file with exif information, required to correctly rotate the image activity
* @param {Object} file
* @returns {Promise<Object>}
*/
export function updateImageOrientation(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function onload() {
      const arrayBuffer = reader.result;
      const buf = new Buffer(arrayBuffer.byteLength);
      const view = new Uint8Array(arrayBuffer);
      for (let i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
      }
      resolve(buf);
    };
  })
  .then((buf) => readExifData(file, buf));
}

/**
* Adds exif orientation information on the image file
* @param {Object} file
* @param {Object} buf
* @returns {Promise<ExifImage>}
*/
export function readExifData(file, buf) {
  return new Promise((resolve) => {
    // For avatar images the file.type is set as image/jpeg, however for images shared in an activity file.mimeType is set as image/jpeg. Handling both conditions.
    if (file && file.image && (file.type === `image/jpeg` || file.mimeType === `image/jpeg`)) {
      /* eslint-disable no-new */
      new ExifImage({image: buf}, (error, exifData) => {
        if (!error && exifData) {
          file.image.orientation = exifData.image.Orientation;
        }
        resolve(buf);
      });
    }
    else {
      resolve(buf);
    }
  });
}

/* eslint complexity: ["error", 9] */
/**
* Rotates/flips the image on the canvas as per exif information
* @param {Object} options(orientation: image exif orientation range from 1-8, img: Image object, x: start x-axis, y: start y-axis, width: width of the thumbnail, height: height of the thumbnail, ctx: canvas context)
* @param {Object} file
* @returns {Object}
*/
export function orient(options, file) {
  if (file && file.image && file.image.orientation && file.image.orientation !== 1) {
    const image = {
      img: options.img,
      x: options.x,
      y: options.y,
      width: options.width,
      height: options.height,
      deg: 0,
      flip: true,
      ctx: options.ctx
    };
    switch (options && options.orientation) {
    case 3:
      // rotateImage180
      image.deg = 180;
      image.flip = false;
      break;
    case 4:
      // rotate180AndFlipImage
      image.deg = 180;
      image.flip = true;
      break;
    case 5:
      // rotate90AndFlipImage
      image.deg = 270;
      image.flip = true;
      break;
    case 6:
      // rotateImage90
      image.deg = 270;
      image.flip = false;
      break;
    case 7:
      // rotateNeg90AndFlipImage
      image.deg = 90;
      image.flip = true;
      break;
    case 8:
      // rotateNeg90
      image.deg = 90;
      image.flip = false;
      break;
    default:
      break;
    }
    drawImage(image);
  }
  else {
    options.ctx.drawImage(options.img, options.x, options.y, options.width, options.height);
  }
}
<|endoftext|>