<commit_before>var path = require('path');

var AsyncDependenciesBlock = require('webpack/lib/AsyncDependenciesBlock');
var DependenciesBlockVariable = require('webpack/lib/DependenciesBlockVariable');
var RawModule = require('webpack/lib/RawModule');

var ModuleError = require('webpack-core/lib/ModuleError');
var ModuleWarning = require('webpack-core/lib/ModuleWarning');

var RawSource = require('webpack-sources').RawSource;

var HardModuleDependency = require('./dependencies').HardModuleDependency;
var HardContextDependency = require('./dependencies').HardContextDependency;
var HardNullDependency = require('./dependencies').HardNullDependency;
var HardHarmonyExportDependency = require('./dependencies').HardHarmonyExportDependency;
var HardHarmonyImportDependency =
require('./dependencies').HardHarmonyImportDependency;
var HardHarmonyImportSpecifierDependency =
require('./dependencies').HardHarmonyImportSpecifierDependency;
var HardHarmonyExportImportedSpecifierDependency = require('./dependencies').HardHarmonyExportImportedSpecifierDependency;

var HardSource = require('./hard-source');

module.exports = HardModule;

function HardModule(cacheItem) {
  RawModule.call(this, cacheItem.source, cacheItem.identifier, cacheItem.userRequest);

  this.cacheItem = cacheItem;

  this.request = cacheItem.request;
  this.userRequest = cacheItem.userRequest;
  this.rawRequest = cacheItem.rawRequest;
  this.resource = cacheItem.resource;
  this.context = cacheItem.context;
  this.loaders = cacheItem.loaders;

  this.strict = cacheItem.strict;
  this.meta = cacheItem.meta;
  this.buildTimestamp = cacheItem.buildTimestamp;
  this.fileDependencies = cacheItem.fileDependencies;
  this.contextDependencies = cacheItem.contextDependencies;
}
HardModule.prototype = Object.create(RawModule.prototype);
HardModule.prototype.constructor = HardModule;

function needRebuild(buildTimestamp, fileDependencies, contextDependencies, fileTimestamps, contextTimestamps, fileMd5s, cachedMd5s) {
  var timestamp = 0;
  var needsMd5Rebuild = false;

  fileDependencies.forEach(function(file) {
    if (!needsMd5Rebuild) {
      needsMd5Rebuild = cachedMd5s[file] !== fileMd5s[file];
    }
    var ts = fileTimestamps[file];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  contextDependencies.forEach(function(context) {
    var ts = contextTimestamps[context];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  return timestamp >= buildTimestamp && needsMd5Rebuild;
}

HardModule.needRebuild = needRebuild;
HardModule.prototype.needRebuild = function(fileTimestamps, contextTimestamps) {
  return this.cacheItem.invalid || needRebuild(this.buildTimestamp, this.fileDependencies, this.contextDependencies, fileTimestamps, contextTimestamps);
};

HardModule.prototype.source = function() {
  return this._renderedSource;
};

HardModule.prototype.updateHash = function(hash) {
  hash.update(this.cacheItem.hashContent);
};

// HardModule.prototype.libIdent = function(options) {
//   return this.cacheItem.libIdent;
// };

// From webpack/lib/NormalModule.js
function contextify(options, request) {
  return request.split("!").map(function(r) {
    var rp = path.relative(options.context, r);
    if(path.sep === "\\")
      rp = rp.replace(/\\/g, "/");
    if(rp.indexOf("../") !== 0)
      rp = "./" + rp;
    return rp;
  }).join("!");
}

HardModule.prototype.libIdent = function(options) {
  return contextify(options, this.userRequest);
};

// HardModule.prototype.isUsed = function(exportName) {
//   return exportName ? exportName : false;
// };

function deserializeDependencies(deps, parent) {
  return deps.map(function(req) {
    if (req.contextDependency) {
      var dep = new HardContextDependency(req.request, req.recursive, req.regExp ? new RegExp(req.regExp) : null);
      dep.critical = req.contextCritical;
      dep.loc = req.loc;
      return dep;
    }
    if (req.constDependency) {
      return new HardNullDependency();
    }
    if (req.harmonyExport) {
      return new HardHarmonyExportDependency(parent, req.harmonyId, req.harmonyName, req.harmonyPrecedence);
    }
    if (req.harmonyImport) {
      if (this.state.imports[req.request]) {
        return this.state.imports[req.request];
      }
      return this.state.imports[req.request] = new HardHarmonyImportDependency(req.request);
    }
    if (req.harmonyImportSpecifier) {
      var dep = new HardHarmonyImportSpecifierDependency(this.state.imports[req.harmonyRequest], req.harmonyId, req.harmonyName);
      dep.loc = req.loc;
      return dep;
    }
    if (req.harmonyExportImportedSpecifier) {
      if (!this.state.imports[req.harmonyRequest]) {
        this.state.imports[req.harmonyRequest] = new HardHarmonyImportDependency(req.harmonyRequest);
      }
      return new HardHarmonyExportImportedSpecifierDependency(parent, this.state.imports[req.harmonyRequest], req.harmonyId, req.harmonyName);
    }
    var dep = new HardModuleDependency(req.request);
    dep.loc = req.loc;
    return dep;
  }, this);
}
function deserializeVariables(vars, parent) {
  return vars.map(function(req) {
    return new DependenciesBlockVariable(req.name, req.expression, deserializeDependencies.call(this, req.dependencies, parent));
  }, this);
}
function deserializeBlocks(blocks, parent) {
  blocks.map(function(req) {
    if (req.async) {
      var block = new AsyncDependenciesBlock(req.name, parent);
      block.dependencies = deserializeDependencies.call(this, req.dependencies, parent);
      block.variables = deserializeVariables.call(this, req.variables, parent);
      deserializeBlocks(req.blocks, block);
      return block;
    }
  }, this)
  .filter(Boolean)
  .forEach(function(block) {
    parent.addBlock(block);
  });
}

function deserializeError(ErrorClass, state) {
  return function(serialized) {
    var err = new ErrorClass(this, serialized.message);
    if (serialized.origin) {
      err.origin = deserializeDependencies.call(state, [serialized.origin], this)[0];
    }
    if (serialized.dependencies) {
      err.dependencies = deserializeDependencies.call(state, serialized.dependencies, this);
    }
    return err;
  };
}

HardModule.prototype.build = function build(options, compilation, resolver, fs, callback) {
  // Non-rendered source used by Stats.
  if (this.cacheItem.rawSource) {
    this._source = new RawSource(this.cacheItem.rawSource);
  }
  // Rendered source used in built output.
  this._renderedSource = new HardSource(this.cacheItem);

  var state = {state: {imports: {}}};
  this.dependencies = deserializeDependencies.call(state, this.cacheItem.dependencies, this);
  this.variables = deserializeVariables.call(state, this.cacheItem.variables, this);
  this.warnings = this.cacheItem.warnings.map(deserializeError(ModuleWarning, state), this);
  this.errors = this.cacheItem.errors.map(deserializeError(ModuleError, state), this);
  deserializeBlocks.call(state, this.cacheItem.blocks, this);

  var cacheItem = this.cacheItem;
  this.assets = Object.keys(cacheItem.assets).reduce(function(carry, key) {
    var source = cacheItem.assets[key];
    if (source.type === 'Buffer') {
      source = new Buffer(source);
    }
    carry[key] = new RawSource(source);
    return carry;
  }, {});

  callback();
};
<commit_msg>Fix needRebuild<commit_after>var path = require('path');

var AsyncDependenciesBlock = require('webpack/lib/AsyncDependenciesBlock');
var DependenciesBlockVariable = require('webpack/lib/DependenciesBlockVariable');
var RawModule = require('webpack/lib/RawModule');

var ModuleError = require('webpack-core/lib/ModuleError');
var ModuleWarning = require('webpack-core/lib/ModuleWarning');

var RawSource = require('webpack-sources').RawSource;

var HardModuleDependency = require('./dependencies').HardModuleDependency;
var HardContextDependency = require('./dependencies').HardContextDependency;
var HardNullDependency = require('./dependencies').HardNullDependency;
var HardHarmonyExportDependency = require('./dependencies').HardHarmonyExportDependency;
var HardHarmonyImportDependency =
require('./dependencies').HardHarmonyImportDependency;
var HardHarmonyImportSpecifierDependency =
require('./dependencies').HardHarmonyImportSpecifierDependency;
var HardHarmonyExportImportedSpecifierDependency = require('./dependencies').HardHarmonyExportImportedSpecifierDependency;

var HardSource = require('./hard-source');

module.exports = HardModule;

function HardModule(cacheItem) {
  RawModule.call(this, cacheItem.source, cacheItem.identifier, cacheItem.userRequest);

  this.cacheItem = cacheItem;

  this.request = cacheItem.request;
  this.userRequest = cacheItem.userRequest;
  this.rawRequest = cacheItem.rawRequest;
  this.resource = cacheItem.resource;
  this.context = cacheItem.context;
  this.loaders = cacheItem.loaders;

  this.strict = cacheItem.strict;
  this.meta = cacheItem.meta;
  this.buildTimestamp = cacheItem.buildTimestamp;
  this.fileDependencies = cacheItem.fileDependencies;
  this.contextDependencies = cacheItem.contextDependencies;
}
HardModule.prototype = Object.create(RawModule.prototype);
HardModule.prototype.constructor = HardModule;

function needRebuild(buildTimestamp, fileDependencies, contextDependencies, fileTimestamps, contextTimestamps, fileMd5s, cachedMd5s) {
  var timestamp = 0;
  var needsMd5Rebuild = !(fileMd5s && cachedMd5s);

  fileDependencies.forEach(function(file) {
    if (!needsMd5Rebuild) {
      needsMd5Rebuild = cachedMd5s[file] !== fileMd5s[file];
    }
    var ts = fileTimestamps[file];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  contextDependencies.forEach(function(context) {
    var ts = contextTimestamps[context];
    if(!ts) timestamp = Infinity;
    if(ts > timestamp) timestamp = ts;
  });
  return timestamp >= buildTimestamp && needsMd5Rebuild;
}

HardModule.needRebuild = needRebuild;
HardModule.prototype.needRebuild = function(fileTimestamps, contextTimestamps) {
  return this.cacheItem.invalid || needRebuild(this.buildTimestamp, this.fileDependencies, this.contextDependencies, fileTimestamps, contextTimestamps);
};

HardModule.prototype.source = function() {
  return this._renderedSource;
};

HardModule.prototype.updateHash = function(hash) {
  hash.update(this.cacheItem.hashContent);
};

// HardModule.prototype.libIdent = function(options) {
//   return this.cacheItem.libIdent;
// };

// From webpack/lib/NormalModule.js
function contextify(options, request) {
  return request.split("!").map(function(r) {
    var rp = path.relative(options.context, r);
    if(path.sep === "\\")
      rp = rp.replace(/\\/g, "/");
    if(rp.indexOf("../") !== 0)
      rp = "./" + rp;
    return rp;
  }).join("!");
}

HardModule.prototype.libIdent = function(options) {
  return contextify(options, this.userRequest);
};

// HardModule.prototype.isUsed = function(exportName) {
//   return exportName ? exportName : false;
// };

function deserializeDependencies(deps, parent) {
  return deps.map(function(req) {
    if (req.contextDependency) {
      var dep = new HardContextDependency(req.request, req.recursive, req.regExp ? new RegExp(req.regExp) : null);
      dep.critical = req.contextCritical;
      dep.loc = req.loc;
      return dep;
    }
    if (req.constDependency) {
      return new HardNullDependency();
    }
    if (req.harmonyExport) {
      return new HardHarmonyExportDependency(parent, req.harmonyId, req.harmonyName, req.harmonyPrecedence);
    }
    if (req.harmonyImport) {
      if (this.state.imports[req.request]) {
        return this.state.imports[req.request];
      }
      return this.state.imports[req.request] = new HardHarmonyImportDependency(req.request);
    }
    if (req.harmonyImportSpecifier) {
      var dep = new HardHarmonyImportSpecifierDependency(this.state.imports[req.harmonyRequest], req.harmonyId, req.harmonyName);
      dep.loc = req.loc;
      return dep;
    }
    if (req.harmonyExportImportedSpecifier) {
      if (!this.state.imports[req.harmonyRequest]) {
        this.state.imports[req.harmonyRequest] = new HardHarmonyImportDependency(req.harmonyRequest);
      }
      return new HardHarmonyExportImportedSpecifierDependency(parent, this.state.imports[req.harmonyRequest], req.harmonyId, req.harmonyName);
    }
    var dep = new HardModuleDependency(req.request);
    dep.loc = req.loc;
    return dep;
  }, this);
}
function deserializeVariables(vars, parent) {
  return vars.map(function(req) {
    return new DependenciesBlockVariable(req.name, req.expression, deserializeDependencies.call(this, req.dependencies, parent));
  }, this);
}
function deserializeBlocks(blocks, parent) {
  blocks.map(function(req) {
    if (req.async) {
      var block = new AsyncDependenciesBlock(req.name, parent);
      block.dependencies = deserializeDependencies.call(this, req.dependencies, parent);
      block.variables = deserializeVariables.call(this, req.variables, parent);
      deserializeBlocks(req.blocks, block);
      return block;
    }
  }, this)
  .filter(Boolean)
  .forEach(function(block) {
    parent.addBlock(block);
  });
}

function deserializeError(ErrorClass, state) {
  return function(serialized) {
    var err = new ErrorClass(this, serialized.message);
    if (serialized.origin) {
      err.origin = deserializeDependencies.call(state, [serialized.origin], this)[0];
    }
    if (serialized.dependencies) {
      err.dependencies = deserializeDependencies.call(state, serialized.dependencies, this);
    }
    return err;
  };
}

HardModule.prototype.build = function build(options, compilation, resolver, fs, callback) {
  // Non-rendered source used by Stats.
  if (this.cacheItem.rawSource) {
    this._source = new RawSource(this.cacheItem.rawSource);
  }
  // Rendered source used in built output.
  this._renderedSource = new HardSource(this.cacheItem);

  var state = {state: {imports: {}}};
  this.dependencies = deserializeDependencies.call(state, this.cacheItem.dependencies, this);
  this.variables = deserializeVariables.call(state, this.cacheItem.variables, this);
  this.warnings = this.cacheItem.warnings.map(deserializeError(ModuleWarning, state), this);
  this.errors = this.cacheItem.errors.map(deserializeError(ModuleError, state), this);
  deserializeBlocks.call(state, this.cacheItem.blocks, this);

  var cacheItem = this.cacheItem;
  this.assets = Object.keys(cacheItem.assets).reduce(function(carry, key) {
    var source = cacheItem.assets[key];
    if (source.type === 'Buffer') {
      source = new Buffer(source);
    }
    carry[key] = new RawSource(source);
    return carry;
  }, {});

  callback();
};
<|endoftext|>


<commit_before><commit_msg>working line chart<commit_after><|endoftext|>


<commit_before>// Welcome to the peaceful town of Hamelin :)

var Hamelin = {
  neighborhoods: [
    {streets: [
      {houses: [
        {rooms: }
      ]}
    ]},
    {streets: []},
    {streets: []},
    {streets: []}
  ],

};

// The peaceful town of Hamelin has been overridden by rats!
function
// As you can see, there are a lot of them
<commit_msg>fix town structure and update functions<commit_after>// Welcome to the peaceful town of Hamelin :)

// Hamelin is a small town in germany
// Recently they have been overridden by an infestation of rats!

// Here is a list of all the sub-sections of the town
// and whether or not the rats have taken over:
var districtsOfHamelin = [
  {name: 'Afferde',      hasRats: true,  numberOfRats: 35 },
  {name: 'Hastenbeck',   hasRats: true,  numberOfRats: 74 },
  {name: 'Halvestorf',   hasRats: false, numberOfRats: 0  },
  {name: 'Haverbeck',    hasRats: true,  numberOfRats: 24 },
  {name: 'Hilligsfeld',  hasRats: false, numberOfRats: 0  },
  {name: 'Sünteltal',    hasRats: true,  numberOfRats: 68 },
  {name: 'Klein Berkel', hasRats: true,  numberOfRats: 36 },
  {name: 'Tündern',      hasRats: false, numberOfRats: 0  },
  {name: 'Wehrbergen',   hasRats: true,  numberOfRats: 37 },
  {name: 'Rohrsen',      hasRats: true,  numberOfRats: 59 },
  {name: 'Welliehausen', hasRats: true,  numberOfRats: 93]
];

// We need a way to tell what neighborhoods are overrun
function findRats (places) {
  var withRats = [];
  for (var i = 0; i < places.length; i++) {
    if (places[i].hasRats)
    withRats.push(places[i].name);
  }
  return withRats;
}

//___________________________________________________________________
// Section 1

// Once we know which ones have rats, let's tell everyone
function announceRats (places) {
  var withRats = findRats(places);
  for (var i = 0; i < withRats.length; i++) {
    console.log(places[i] + 'HAS BEEN OVERCOME BY RATS!')
  }
  return places; // always returning a value is just good practice, even if we won't use it now
}

// Extra Credit: replace the for loop in findRats as well

//___________________________________________________________________
// Section 2

// The townspeople need a way to tell which parts of Hamelin are safe!
function findSafePlaces (places) {
  var safe = [];
  for var (i = 0; i < places.length; i++) {
    if (places[i].hasRats === false) {
      safe.push(places[i].name)
    }
  }
  return safe;
}

// Extra Credit: replace the loop (or each) in findRats

//___________________________________________________________________
// Section 3

// Just how serious is this problem? Let's find the total number of rats
function totalRats (town) {
  var ratPopulations = [];
  var total = 0;
  for (var i = 0; i < town.length; i++) {
    ratPopulations.push(town[i].numberOfRats); //
  }
  for (var i = 0; i < ratPopulations.length; i++) {
    total += ratPopulations[i];
  }
  return total;
}

//___________________________________________________________________
// Section 4

// Tree with reduce

//___________________________________________________________________
// Extra credit:

// Let's clean up our town array
// We don't really need to keep a boolean and number
// Let's change it to a number
function prettifyTown (town) {
  town.map(function (place) {
    return {
      name:         place.name,
      numberOfRats: place.numberOfRats
    };
  });
}
// Map is the right choice for this function, but just for fun, try
// to switch the .map() out for a .reduce()

//___________________________________________________________________
//Section 6

<|endoftext|>


<commit_before>var minimist = require('minimist')
var targets = require('./targets')

if (process.env.npm_config_argv) {
  var npmargs = ['compile', 'build-from-source', 'debug']
  try {
    var npmArgv = JSON.parse(process.env.npm_config_argv).cooked
    for (var i = 0; i < npmargs.length; ++i) {
      if (npmArgv.indexOf('--' + npmargs[i]) !== -1) {
        process.argv.push('--' + npmargs[i])
      }
      if (npmArgv.indexOf('--no-' + npmargs[i]) !== -1) {
        process.argv.push('--no-' + npmargs[i])
      }
    }
  } catch (e) { }
}

var npmconfigs = ['proxy', 'https-proxy', 'local-address']
for (var j = 0; j < npmconfigs.length; ++j) {
  var envname = 'npm_config_' + npmconfigs[j].replace('-', '_')
  if (process.env[envname]) {
    process.argv.push('--' + npmconfigs[j])
    process.argv.push(process.env[envname])
  }
}

var rc = module.exports = require('rc')('prebuild', {
  target: process.version,
  arch: process.arch,
  libc: process.env.LIBC,
  platform: process.platform,
  abi: process.versions.modules,
  all: false,
  force: false,
  debug: false,
  verbose: false,
  path: '.',
  backend: 'node-gyp',
  proxy: process.env['HTTP_PROXY'],
  'https-proxy': process.env['HTTPS_PROXY']
}, minimist(process.argv, {
  alias: {
    target: 't',
    prebuild: 'b',
    help: 'h',
    arch: 'a',
    path: 'p',
    force: 'f',
    version: 'v',
    upload: 'u',
    download: 'd',
    'build-from-source': 'compile',
    compile: 'c',
    preinstall: 'i'
  }
}))

if (rc.path === true) {
  delete rc.path
}

if (rc.prebuild) {
  rc.pb = rc.prebuild
}

if (rc.pb) {
  rc.prebuild = rc.pb
}

if (rc.all === true) {
  delete rc.prebuild
  rc.prebuild = targets
}

if (rc['upload-all']) {
  rc.upload = rc['upload-all']
}

if (!module.parent) {
  console.log(JSON.stringify(module.exports, null, 2))
}
<commit_msg>rc: respect npm env vars "target" and "abi"<commit_after>var minimist = require('minimist')
var targets = require('./targets')

if (process.env.npm_config_argv) {
  var npmargs = ['compile', 'build-from-source', 'debug']
  try {
    var npmArgv = JSON.parse(process.env.npm_config_argv).cooked
    for (var i = 0; i < npmargs.length; ++i) {
      if (npmArgv.indexOf('--' + npmargs[i]) !== -1) {
        process.argv.push('--' + npmargs[i])
      }
      if (npmArgv.indexOf('--no-' + npmargs[i]) !== -1) {
        process.argv.push('--no-' + npmargs[i])
      }
    }
  } catch (e) { }
}

var npmconfigs = ['proxy', 'https-proxy', 'local-address', 'target', 'abi']
for (var j = 0; j < npmconfigs.length; ++j) {
  var envname = 'npm_config_' + npmconfigs[j].replace('-', '_')
  if (process.env[envname]) {
    process.argv.push('--' + npmconfigs[j])
    process.argv.push(process.env[envname])
  }
}

var rc = module.exports = require('rc')('prebuild', {
  target: process.version,
  arch: process.arch,
  libc: process.env.LIBC,
  platform: process.platform,
  abi: process.versions.modules,
  all: false,
  force: false,
  debug: false,
  verbose: false,
  path: '.',
  backend: 'node-gyp',
  proxy: process.env['HTTP_PROXY'],
  'https-proxy': process.env['HTTPS_PROXY']
}, minimist(process.argv, {
  alias: {
    target: 't',
    prebuild: 'b',
    help: 'h',
    arch: 'a',
    path: 'p',
    force: 'f',
    version: 'v',
    upload: 'u',
    download: 'd',
    'build-from-source': 'compile',
    compile: 'c',
    preinstall: 'i'
  }
}))

if (rc.path === true) {
  delete rc.path
}

if (rc.prebuild) {
  rc.pb = rc.prebuild
}

if (rc.pb) {
  rc.prebuild = rc.pb
}

if (rc.all === true) {
  delete rc.prebuild
  rc.prebuild = targets
}

if (rc['upload-all']) {
  rc.upload = rc['upload-all']
}

if (!module.parent) {
  console.log(JSON.stringify(module.exports, null, 2))
}
<|endoftext|>


<commit_before>import React from 'react';
import moment from 'moment';
import AutoComplete from 'material-ui/AutoComplete';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import DatePicker from 'material-ui/DatePicker';
import Subheader from 'material-ui/Subheader';
import TimePicker from 'material-ui/TimePicker';
import Chip from 'material-ui/Chip';
import { List } from 'material-ui/List';
import PermissionItem from './PermissionItem';

export default class EditEvent extends React.Component {
    static propTypes = {
        id: React.PropTypes.string,
        title: React.PropTypes.string,
        location: React.PropTypes.string,
        start: React.PropTypes.string,
        end: React.PropTypes.string,
        tags: React.PropTypes.array,
        permissions: React.PropTypes.array,
        mdtext: React.PropTypes.string,
        saveEvent: React.PropTypes.func,
        closeEdit: React.PropTypes.func,
        viewer: React.PropTypes.object,
    }

    state = {
        id: this.props.id,
        title: this.props.title,
        location: this.props.location,
        start: this.props.start ? moment(this.props.start).toDate() : null,
        end: this.props.end ? moment(this.props.end).toDate() : null,
        tags: this.props.tags,
        mdtext: this.props.mdtext,
        permissions: this.props.permissions || [],
    }

    onChangeTitle = (event, title) => {
        this.setState({ title });
    }

    onChangeLocation = (event, location) => {
        this.setState({ location });
    }

    onChangeStart = (event, date) => {
        this.setState({ start: date });
    }
    onChangeEnd = (event, date) => {
        this.setState({ end: date });
    }

    onChangeStartDate = (event, date) => {
        if (!this.state.start) {
            this.setState({ start: date });
        }
        else {
            this.setState({
                start: moment(this.state.start).set({
                    year: date.getFullYear(),
                    month: date.getMonth(),
                    date: date.getDate(),
                }).toDate(),
            });
        }
    }

    onChangeEndDate = (event, date) => {
        if (!this.state.end) {
            this.setState({ end: date });
        }
        else {
            this.setState({
                end: moment(this.state.end).set({
                    year: date.getFullYear(),
                    month: date.getMonth(),
                    date: date.getDate(),
                }).toDate(),
            });
        }
    }

    onChangeDescription = (event, mdtext) => {
        this.setState({ mdtext });
    }

    onPermissionChange = (value) => {
        this.setState({
            permission: value,
        });
    }

    addPermission = (chosen) => {
        const permissions = this.state.permissions;
        permissions.push(chosen);
        this.setState({
            permissions,
            permission: '',
        });
    }

    removePermission = (permissionId) => {
        const permissions = this.state.permissions.filter((_p) => {
            return _p.value !== permissionId;
        });
        this.setState({
            permissions,
        });
    }

    saveEvent = () => {
        this.props.saveEvent(this.state, this.props.closeEdit);
    }

    renderChip = (data, key) => {
        return (
            <Chip
                key={key}
            >
                {data}
            </Chip>
        );
    }

    render() {
        const viewer = this.props.viewer;
        const permissions = [];
        if (viewer) {
            permissions.push({ value: 'p', text: 'Verden' });
            viewer.groups.forEach((group) => {
                permissions.push({ value: group.id, text: group.name });
            });
        }
        return (
            <form>

                    <TextField
                        value={this.state.title}
                        floatingLabelText="Tittel"
                        onChange={this.onChangeTitle}
                    />

                    <TextField
                        value={this.state.location}
                        floatingLabelText="Sted"
                    />

                    <DatePicker
                        value={this.state.start}
                        floatingLabelText="Start"
                        onChange={this.onChangeStartDate}
                    />
                    <TimePicker
                        value={this.state.start}
                        floatingLabelText="Klokkeslett"
                        format="24hr"
                        onChange={this.onChangeStart}
                    />

                    <DatePicker
                        value={this.state.end}
                        floatingLabelText="Slutt"
                        onChange={this.onChangeEndDate}
                    />
                    <TimePicker
                        value={this.state.end}
                        floatingLabelText="Klokkeslett"
                        format="24hr"
                        onChange={this.onChangeEnd}
                    />

                    <TextField
                        value={this.state.mdtext}
                        floatingLabelText="Beskrivelse"
                        multiLine
                        onChange={this.onChangeDescription}
                    />

                    {this.state.tags
                        ? this.state.tags.map((tag, i) => {
                            return this.renderChip(tag, i);
                        })
                        : null
                    }

                    <List>
                        <Subheader>Rettigheter</Subheader>
                        {this.state.permissions.map((permission) => {
                            return (
                                <PermissionItem
                                    key={permission.value}
                                    removePermission={this.removePermission}
                                    {...permission}
                                />
                            );
                        })}
                    </List>
                    <AutoComplete
                        id="permissions"
                        floatingLabelText="Legg til rettigheter"
                        filter={AutoComplete.fuzzyFilter}
                        dataSource={permissions}
                        maxSearchResults={8}
                        searchText={this.state.permission}
                        onNewRequest={this.addPermission}
                        onUpdateInput={this.onPermissionChange}
                    />

                    <RaisedButton onClick={this.saveEvent} label="Lagre" />

            </form>
        );
    }
}
<commit_msg>Location should be changable<commit_after>import React from 'react';
import moment from 'moment';
import AutoComplete from 'material-ui/AutoComplete';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import DatePicker from 'material-ui/DatePicker';
import Subheader from 'material-ui/Subheader';
import TimePicker from 'material-ui/TimePicker';
import Chip from 'material-ui/Chip';
import { List } from 'material-ui/List';
import PermissionItem from './PermissionItem';

export default class EditEvent extends React.Component {
    static propTypes = {
        id: React.PropTypes.string,
        title: React.PropTypes.string,
        location: React.PropTypes.string,
        start: React.PropTypes.string,
        end: React.PropTypes.string,
        tags: React.PropTypes.array,
        permissions: React.PropTypes.array,
        mdtext: React.PropTypes.string,
        saveEvent: React.PropTypes.func,
        closeEdit: React.PropTypes.func,
        viewer: React.PropTypes.object,
    }

    state = {
        id: this.props.id,
        title: this.props.title,
        location: this.props.location,
        start: this.props.start ? moment(this.props.start).toDate() : null,
        end: this.props.end ? moment(this.props.end).toDate() : null,
        tags: this.props.tags,
        mdtext: this.props.mdtext,
        permissions: this.props.permissions || [],
    }

    onChangeTitle = (event, title) => {
        this.setState({ title });
    }

    onChangeLocation = (event, location) => {
        this.setState({ location });
    }

    onChangeStart = (event, date) => {
        this.setState({ start: date });
    }
    onChangeEnd = (event, date) => {
        this.setState({ end: date });
    }

    onChangeStartDate = (event, date) => {
        if (!this.state.start) {
            this.setState({ start: date });
        }
        else {
            this.setState({
                start: moment(this.state.start).set({
                    year: date.getFullYear(),
                    month: date.getMonth(),
                    date: date.getDate(),
                }).toDate(),
            });
        }
    }

    onChangeEndDate = (event, date) => {
        if (!this.state.end) {
            this.setState({ end: date });
        }
        else {
            this.setState({
                end: moment(this.state.end).set({
                    year: date.getFullYear(),
                    month: date.getMonth(),
                    date: date.getDate(),
                }).toDate(),
            });
        }
    }

    onChangeDescription = (event, mdtext) => {
        this.setState({ mdtext });
    }

    onPermissionChange = (value) => {
        this.setState({
            permission: value,
        });
    }

    addPermission = (chosen) => {
        const permissions = this.state.permissions;
        permissions.push(chosen);
        this.setState({
            permissions,
            permission: '',
        });
    }

    removePermission = (permissionId) => {
        const permissions = this.state.permissions.filter((_p) => {
            return _p.value !== permissionId;
        });
        this.setState({
            permissions,
        });
    }

    saveEvent = () => {
        this.props.saveEvent(this.state, this.props.closeEdit);
    }

    renderChip = (data, key) => {
        return (
            <Chip
                key={key}
            >
                {data}
            </Chip>
        );
    }

    render() {
        const viewer = this.props.viewer;
        const permissions = [];
        if (viewer) {
            permissions.push({ value: 'p', text: 'Verden' });
            viewer.groups.forEach((group) => {
                permissions.push({ value: group.id, text: group.name });
            });
        }
        return (
            <form>

                    <TextField
                        value={this.state.title}
                        floatingLabelText="Tittel"
                        onChange={this.onChangeTitle}
                    />

                    <TextField
                        value={this.state.location}
                        floatingLabelText="Sted"
                        onChange={this.onChangeLocation}
                    />

                    <DatePicker
                        value={this.state.start}
                        floatingLabelText="Start"
                        onChange={this.onChangeStartDate}
                    />
                    <TimePicker
                        value={this.state.start}
                        floatingLabelText="Klokkeslett"
                        format="24hr"
                        onChange={this.onChangeStart}
                    />

                    <DatePicker
                        value={this.state.end}
                        floatingLabelText="Slutt"
                        onChange={this.onChangeEndDate}
                    />
                    <TimePicker
                        value={this.state.end}
                        floatingLabelText="Klokkeslett"
                        format="24hr"
                        onChange={this.onChangeEnd}
                    />

                    <TextField
                        value={this.state.mdtext}
                        floatingLabelText="Beskrivelse"
                        multiLine
                        onChange={this.onChangeDescription}
                    />

                    {this.state.tags
                        ? this.state.tags.map((tag, i) => {
                            return this.renderChip(tag, i);
                        })
                        : null
                    }

                    <List>
                        <Subheader>Rettigheter</Subheader>
                        {this.state.permissions.map((permission) => {
                            return (
                                <PermissionItem
                                    key={permission.value}
                                    removePermission={this.removePermission}
                                    {...permission}
                                />
                            );
                        })}
                    </List>
                    <AutoComplete
                        id="permissions"
                        floatingLabelText="Legg til rettigheter"
                        filter={AutoComplete.fuzzyFilter}
                        dataSource={permissions}
                        maxSearchResults={8}
                        searchText={this.state.permission}
                        onNewRequest={this.addPermission}
                        onUpdateInput={this.onPermissionChange}
                    />

                    <RaisedButton onClick={this.saveEvent} label="Lagre" />

            </form>
        );
    }
}
<|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You 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.
 */

var sys = require('sys');
var exec = require('child_process').exec;
var ps = require('util/pubsub');
var async = require('extern/async');

function getServer()
{
  return require('services/http')._serverOnly();
}

var hello = "Hello World";

exports['PUT t.txt'] = function(assert, beforeExit) {
  var n = 0;

  assert.response(getServer(), {
    url: '/bundles/foo/t.txt',
    method: 'PUT',
    data: hello
  },
  function(res) {
    n++;
    assert.equal(res.statusCode, 204);
    assert.length(res.body, 0);
    ps.emit('t.txt created');
  });
  beforeExit(function(){
    assert.equal(1, n, 'Responses Received');
  });
};

exports['GET t.txt'] = function(assert, beforeExit) {
  var n = 0;
  ps.on('t.txt created', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/t.txt',
      method: 'GET'
    },
    function(res) {
      n++;
      assert.equal(200, res.statusCode);
      assert.equal(hello, res.body);
      ps.emit('t.txt read');
    });
  });
  beforeExit(function(){
    assert.equal(1, n, 'Responses Received');
  });
};

exports['DELETE t.txt'] = function(assert, beforeExit) {
  var n = 0;
  ps.on('t.txt read', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/t.txt',
      method: 'DELETE'
    },
    function(res) {
      n++;
      assert.equal(res.statusCode, 204);
      assert.length(res.body, 0);
      ps.emit('t.txt deleted');
    });
  });

  ps.on('t.txt deleted', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/t.txt',
      method: 'GET'
    },
    function(res) {
      n++;
      assert.equal(404, res.statusCode);
    });
  });

  beforeExit(function(){
    assert.equal(2, n, 'Responses Received');
  });
};

exports.setup = function(done) {
  async.series([
    async.apply(ps.ensure, "config"),
    async.apply(exec, "mkdir -p .tests/data_root/bundles/foo")
  ], done);
};
<commit_msg>Add a bunch more bundle tests<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You 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.
 */

var sys = require('sys');
var exec = require('child_process').exec;
var ps = require('util/pubsub');
var misc = require('util/misc');
var async = require('extern/async');

function getServer() {
  return require('services/http')._serverOnly();
}

var hello = "Hello World";

function verify_response_code(url, code, method, data) {
  var method = method || 'GET';
  var req = {
    url: url,
    method: method
  }
  if (data) {
    req.data = data;
  }
  return function(assert, beforeExit) {
    // Make sure listing the 'bar' bundle 404s
    var n = 0;
    assert.response(getServer(), req, function(res) {
      n++;
      assert.equal(res.statusCode, code);
    });

    beforeExit(function(){
      assert.equal(1, n, 'Responses Received');
    });
  }
}

// The following tests can be executed asynchronously in any order

exports['GET /bundles/'] = function(assert, beforeExit) {
  // Make sure the 'foo' bundle is listed
  var n = 0;
  assert.response(getServer(), {
    url: '/bundles/',
    method: 'GET',
  },
  function(res) {
    n++;
    assert.equal(res.statusCode, 200);
    var data = JSON.parse(res.body);
    assert.ok(data instanceof Array);
    assert.equal(data.length, 1);
    assert.equal(data[0], "foo");
  });
  beforeExit(function(){
    assert.equal(1, n, 'Responses Received');
  });
};

// Non-existant bundle
exports['GET /bundles/bar/'] = verify_response_code('/bundles/bar/', 404);

// Up one level from bundles
exports['GET /bundles/../'] = verify_response_code('/bundles/../', 404);

// At the bundles level
exports['GET /bundles/./'] = verify_response_code('/bundles/./', 404);

// Uploading to non-existant bundle
exports['PUT /bundles/foo/t.txt'] = verify_response_code('/bundles/bar/t.txt', 404, 'PUT', hello);

// Uploading to the bundles directory
exports['PUT /bundles/foo/../'] = verify_response_code('/bundles/foo/../', 404, 'PUT', hello);

// Listing a file in the bundles directory
exports['GET /bundles/baz.txt'] = verify_response_code('/bundles/baz.txt/', 404);

// These tests must be executed in series and enforce this using util/pubsub

exports['PUT t.txt'] = function(assert, beforeExit) {
  // Make sure adding a file to a bundle succeeds
  var n = 0;
  assert.response(getServer(), {
    url: '/bundles/foo/t.txt',
    method: 'PUT',
    data: hello
  },
  function(res) {
    n++;
    assert.equal(res.statusCode, 204);
    assert.length(res.body, 0);
    ps.emit('t.txt created');
  });
  beforeExit(function(){
    assert.equal(1, n, 'Responses Received');
  });
};

exports['GET /bundles/foo/'] = function(assert, beforeExit) {
  // Make sure listing the bundle shows the file
  var n = 0;
  ps.on('t.txt created', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/',
      method: 'GET',
    },
    function(res) {
      n++;
      assert.equal(res.statusCode, 200);
      var data = JSON.parse(res.body);
      assert.ok(data instanceof Array);
      assert.equal(data.length, 1);
      assert.equal(data[0], "t.txt");
      ps.emit('t.txt listed');
    });
  });
  beforeExit(function(){
    assert.equal(1, n, 'Responses Received');
  });
};

exports['GET t.txt'] = function(assert, beforeExit) {
  // Make sure we can download the file and the contents are correct
  var n = 0;
  ps.on('t.txt listed', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/t.txt',
      method: 'GET'
    },
    function(res) {
      n++;
      assert.equal(200, res.statusCode);
      assert.equal(hello, res.body);
      ps.emit('t.txt read');
    });
  });
  beforeExit(function(){
    assert.equal(1, n, 'Responses Received');
  });
};

exports['DELETE t.txt'] = function(assert, beforeExit) {
  // Make sure we can delete the file
  var n = 0;
  ps.on('t.txt read', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/t.txt',
      method: 'DELETE'
    },
    function(res) {
      n++;
      assert.equal(res.statusCode, 204);
      assert.length(res.body, 0);
      ps.emit('t.txt deleted');
    });
  });

  // And that it gets deleted
  ps.on('t.txt deleted', function() {
    assert.response(getServer(), {
      url: '/bundles/foo/t.txt',
      method: 'GET'
    },
    function(res) {
      n++;
      assert.equal(404, res.statusCode);
      ps.emit('t.txt verified deleted');
    });
  });

  beforeExit(function(){
    assert.equal(2, n, 'Responses Received');
  });
};

exports['PUT long.txt'] = function(assert, beforeExit) {
  var n = 0;
  ps.on('t.txt verified deleted', function() {
    var req = {
      url: '/bundles/foo/long.txt',
      method: 'PUT',
      headers: {
        'Transfer-Encoding': 'chunked'
      },
      streamer: function(request) {
        var intervalId;
        function write_some() {
          request.write(misc.randstr(1024));
          if (++n === 1000) {
            request.end();
            clearInterval(intervalId);
          }
        }
        var intervalId = setInterval(write_some, 5);
      }
    };
    assert.response(getServer(), req, function(res) {
      n++;
      assert.equal(204, res.statusCode);
    });
  });

  beforeExit(function(){
    assert.equal(1001, n, 'Responses Received');
  });
};

exports.setup = function(done) {
  async.series([
    async.apply(ps.ensure, "config"),
    async.apply(exec, "mkdir -p .tests/data_root/bundles/foo/baz"),
    async.apply(exec, "touch .tests/data_root/bundles/baz.txt")
  ], done);
};
<|endoftext|>


<commit_before>angular.module('materialscommons').component('mcTaskTemplate', {
    templateUrl: 'app/project/experiments/experiment/components/tasks/components/mc-task-template.html',
    controller: MCTaskTemplateComponentController,
    bindings: {
        template: '='
    }
});

/*@ngInject*/
function MCTaskTemplateComponentController() {
    var ctrl = this;
    //ctrl.template = template.get();
}<commit_msg>Set the template_name on the task when a template is added.<commit_after>angular.module('materialscommons').component('mcTaskTemplate', {
    templateUrl: 'app/project/experiments/experiment/components/tasks/components/mc-task-template.html',
    controller: MCTaskTemplateComponentController,
    bindings: {
        task: '='
    }
});

/*@ngInject*/
function MCTaskTemplateComponentController() {
    var ctrl = this;
    //ctrl.template = template.get();
}<|endoftext|>


<commit_before>(function (env) {
    "use strict";
    env.ddg_spice_rust_cargo = function(api_result){

        if (!api_result || !api_result.crates) {
            return Spice.failed('rust_cargo');
        }
        var crates = api_result.crates;

        var query = DDG.get_query().replace(/(cargo|rust) (package|crate)(s)?/, "").trim();

        DDG.require("moment.js", function() {
            Spice.add({
                id: "rust_cargo",
                name: "Software",
                data: crates,
                meta: {
                    itemType: "Cargo crates",
                    searchTerm: query,
                    sourceName: "Cargo",
                    sourceUrl: 'https://crates.io/search?q=' + encodeURIComponent(query)
                },
                normalize: function(item) {
                    return {
                        title: item.name + " " + item.max_version,
                        subtitle: "Last updated " + moment(item.updated_at).fromNow(),
                        description: item.description,
                        url: "https://crates.io/crates/" + encodeURIComponent(item.id),
                        abbrevDownloads: DDG.abbrevNumber(item.downloads)
                    }
                },

                templates: {
                    group: 'text',
                    detail: false,
                    item_detail: false,
                    options: {
                        footer: Spice.rust_cargo.footer
                    },
                    variants: {
                        tile: 'basic4'
                    }
                },
                sort_fields: {
                    downloads: function(a, b) {
                        return a.downloads > b.downloads ? -1 : 1;
                    }
                },
                sort_default: 'downloads'
            });
        });
    };
}(this));
<commit_msg>Rust Cargo: include more triggers in regex<commit_after>(function (env) {
    "use strict";
    env.ddg_spice_rust_cargo = function(api_result){

        if (!api_result || !api_result.crates) {
            return Spice.failed('rust_cargo');
        }
        var crates = api_result.crates;

        var query = DDG.get_query().replace(/(cargo|rust) (package|crate|cargo)(s)?/, "").trim();

        DDG.require("moment.js", function() {
            Spice.add({
                id: "rust_cargo",
                name: "Software",
                data: crates,
                meta: {
                    itemType: "Cargo crates",
                    searchTerm: query,
                    sourceName: "Cargo",
                    sourceUrl: 'https://crates.io/search?q=' + encodeURIComponent(query)
                },
                normalize: function(item) {
                    return {
                        title: item.name + " " + item.max_version,
                        subtitle: "Last updated " + moment(item.updated_at).fromNow(),
                        description: item.description,
                        url: "https://crates.io/crates/" + encodeURIComponent(item.id),
                        abbrevDownloads: DDG.abbrevNumber(item.downloads)
                    }
                },

                templates: {
                    group: 'text',
                    detail: false,
                    item_detail: false,
                    options: {
                        footer: Spice.rust_cargo.footer
                    },
                    variants: {
                        tile: 'basic4'
                    }
                },
                sort_fields: {
                    downloads: function(a, b) {
                        return a.downloads > b.downloads ? -1 : 1;
                    }
                },
                sort_default: 'downloads'
            });
        });
    };
}(this));
<|endoftext|>


<commit_before>OC.L10N.register(
    "audioplayer",
    {

	"Add new Songs to playlist" : "Dodaj nową piosenkę do playlisty",
	"Scan for new audio files" : "Skanowanie w poszukiwaniu nowych plików audio",
	"Sort Playlist" : "Sortuj Playlistę",
	"Delete Playlist" : "Usuń Playlistę",
	"Delete Song from Playlist" :"Usuń piosenkę z Playlisty",
	"No Songs found in current Playlist! Add new Songs per Drag & Drop from album view" : "Nie znaleziono utworu w bieżącej Playliście! Dodaj nowy utwór za pomocą Drag & Drop z podglądu albumu",
	"No Playlist selected!" : "Nie wybrano Playlisty!",
	"Sort modus active" : "Przetwarzanie włączone",
	"Delete playlist success!" : "Playlista została usunięta!",
	"Rename Playlist" : "Zmiana nazwy Playlisty",
	"Start scanning ..." : "Rozpocznij skanowanie ...",
	"Scanning finished! New Audios found!" :"Skanowanie zakończone! Znalezione nowe pliki audio!",
	"Yes" : "Tak",
	"No" : "Nie",
	"Are you sure?" : "Czy jesteś pewien?",
	"Track" : "Ścieżka",
	"File" : "Plik",
	"Title" : "Tytuł",
	"Interpret" : "Artysta",
	"Artist" : "Artysta",
	"Year" : "Rok",
	"Album" : "Album",
	"Edit Song from Playlist" : "Edycja utworu z playlisty",
	"Edit track information (ID3)" : "Edytuj informacje utwóru (ID3)",
	"Missing Permissions for editing ID3 Tags of song!" : "Brak uprawnień do edycji tagów ID3 piosenki!",
	"Existing Albums" : "Istniejące albumy",
	"New Album" : "Nowy album",
	"Genre" : "Gatunek",
	"Add as Albumcover" : "Dodaj jako okładkę albumu",
	"of" : "z",
	"Total" : "Ogólny",
	"Select from cloud" : "Wybierz z chmury",
	"Edit" : "Edycja",
	"Delete" : "Usuń",
	"Upload" : "Wgraj",
	"Drop Photo" : "Upuść zdjęcie",
	"Drag Image Here!" : "Przeciągnij tutaj obraz!",
	"Reset Media Library" : "Resetowanie biblioteki multimediów",
	"Start deleting and resetting media library ..." : "Zacznij usuwanie i resetowanie biblioteki multimediów ...",
	"Resetting finished!" : "Resetowanie zakończone!",
	"Are you sure? All music database entries will be deleted!" : "Czy jesteś pewien? Wszystkie wpisy muzyczne w bazie danych zostaną usunięte!",
	"Close" : "Zamknij",
	"Play" : "Graj",
	"Save" : "Zapisz",
	"Existing Artists" : "Istniejący artyści",
	"New Artist" : "Nowy artysta",
	"Existing Genres" : "Istniejące gatunki muzyczne",
	"New Genre" : "Nowy gatunek muzyczny",
	"Selected Folder" : "Wybrany folder",
	"Selected Playlist" : "Wybrana Playlista",
	"Selected Genre" : "Wybrany gatunek",
	"Selected Year" : "Wybrany rok",
	"Selected" : "Wybrany",
	"Selected Artist" : "Wybrany artysta",
	"Length" : "Długość"
},
"");<commit_msg>Delete pl_PL.js<commit_after><|endoftext|>


<commit_before>var express = require('express');
var app = express();
var fs = require('fs');
var rootPath = __dirname.replace('/web', '');
var staticServer = require('serve-static');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var Post = require('../blog/entities/post');
var config = require('../config');
var passport = require('passport');
var TwitterStrategy = require('passport-twitter').Strategy;
var Datastore = require('nedb');
var membersDbFilePath = config.dataPath + '/members.db';
var signer = require('jws');
var Editor = require(rootPath + '/blog/entities/editor');
var Persistence = require('../boundaries/persistence')(config);
var postPath = config.dataPath + '/posts/';
var DateParser = require('../dateParser');
var Marked = require('marked');

function Resource(obj){
	for(var key in obj) this[key] = obj[key];
}
Resource.prototype = {
	layout: 'default'
	, title: config.site.title
	, js: []
	, css: []
	, header: {}
	, user: null
	, status: {code: 200, description: 'Ok'}
	, posts: []
};
var represent = require('represent').Represent({
	themeRoot: rootPath + '/web/themes/' + config.theme
	, appPath: rootPath + '/web'
});
express.response.represent = require('./withRepresent')(represent, config);

app.use(compression());
app.use("/public", staticServer(represent.themeRoot));
app.set("views", rootPath + "/themes/default/templates");
app.set("view engine", function(view, options, fn){ return fn(view, options);});
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride(function(req, res){
	if(req.body._method) return req.body._method;
	return req.method;
}));
app.use(cookieSession({ keys: [config.cookie.key, ':blah:'], secret: config.cookie.secret}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(member, done) {
	var signature = signer.sign({
		header: {alg: 'HS256'}
		, payload: member.token
		, secret: config.secret
	});
	done(null, signature);
});
passport.deserializeUser(function deserializeUser(token, done) {
	var decodedSignature = signer.decode(token);
	if(!decodedSignature) return done(null, null);
	var db = new Datastore({filename: membersDbFilePath, autoload: true});
	db.findOne({token: decodedSignature.payload}, function(err, member) {
		if(err) console.log(err);
		done(err, member);
	});
});
function handleDatastoreError(err){
	if(err) console.log("An error occurred when manipulating a db file", err);
}
passport.use(new TwitterStrategy({
	consumerKey: config.twitter.consumer.key
	, consumerSecret: config.twitter.consumer.secret
	, callbackURL: config.twitter.callbackUrl
	, passReqToCallback: true
  }
  , function(request, token, tokenSecret, profile, done) {
	  var allowedTwitterUsers = ['ijoeyguerra', 'joseguerra', 'Hubot'];
	  if(allowedTwitterUsers.indexOf(profile.username) === -1) return done(null, null);
	  var db = new Datastore({filename: membersDbFilePath, autoload: true});
	  db.findOne({"token":token}, function(err, member){
			if(err) return done(err);
			if(member) return done(null, member);
			var memberDb = new Datastore({filename: membersDbFilePath, autoload: true});
			var editor = Editor({
				token: token
				, name: profile.displayName
				, avatar: profile._json.profile_background_image_url
				, username: profile.username
			});
			process.nextTick(function(){
				memberDb.insert(editor, function(err, docs){
					if(err) return done(err);
					done(null, docs);
				});
			});
	  });
  }
));

var posts = [];
app.get('/' + config.google.verification + '\.html', function(req, resp){
	resp.represent(200, 'google-site-verification: ' + config.google.verification + '.html');
});
app.get("/robots.txt", function(req, resp, next){
	resp.represent({
		view: 'robots/index'
		, resource: new Resource({
			posts: posts}
		)
		, model: {}});
});
app.get("/humans.txt", function(req, resp, next){
	resp.represent({
		view: 'humans/index'
		, resource: new Resource({
			posts: posts}
		)
		, model: {}});
});
app.get("/sitemap.:format", function(req, resp, next){
	resp.represent({
		view: 'sitemap/index'
		, resource: new Resource({
			posts: posts}
		)
		, model: posts});
});

app.get('/index:format?', function(req, resp, next){
	var post = new Post();
	fs.readFile(__dirname + '/data/index.json', null, function(err, data){
		if(err) console.log(err);
		post = new Post(JSON.parse(data));
		resp.represent({view: 'index/index'
			, resource: new Resource({
				posts: posts
			})
			, model: post});
	});
});
app.get('/', function(req, resp, next){
	var post = null;
	fs.readFile(__dirname + '/data/index.json', null, function(err, data){
		if(err){
			console.log(err);
			return next(404);
		}
		post = new Post(JSON.parse(data));
		resp.represent({view: 'index/index'
		, resource: new Resource({
			title: post.title
			, posts: posts
		})
		, model: post});
	});
});

// authenticated endpoints
app.get(['/posts.:format?', "/post.:format?", "/post/:title"], function(req, resp, next){
	if(!req.isAuthenticated()) return next(401);
	next();
});

app.post("/post.:format?", function(req, resp, next){
	if(!req.isAuthenticated()) return next(401);
	next();
});
app.get('/logout', function(req, resp, next){
	req.logout();
	resp.redirect('/');
});

// twitter auth endpoints
app.get('/auth/twitter\??', passport.authenticate('twitter'));
app.get("/auth/twitter/callback", passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/' }));

// posts endpoints
app.delete("/posts.:format?", function(req, resp, next){
	var id = req.body._id;
	Persistence.post.findOne({_id: id}, function(err, post){
		if(err) console.log(err);
		if(post && post._id !== null){
			client.send(new Commands.DeletePost(post));
		}
	});
	resp.redirect('/posts');
});

app.get("/posts.:format?", function(req, resp, next){
	var docs = [];
	Persistence.post.find({}, {published: -1}, function(err, docs){
		if(err){
			console.log(err);
			next(500);
		}
		resp.represent({view: 'post/index'
			, resource: new Resource({title: "List of Posts"
			, posts: posts})
			, model: docs});
	});
});
app.get('/posts/:_id.:format?', function(req, resp, next){
	Persistence.post.findOne({_id: req.params._id}, function(err, doc){
		if(err) return next(500);
		if(doc === null) return next(404);
		resp.represent({view: 'post/show'
			, resource: new Resource({title: doc.title, posts: posts, css: ['post'], js: ['post']})
			, model: doc});
	});
});
app.get("/post/:_id.:format?", function getPostById(req, resp, next){
	Persistence.post.findOne({_id: req.params._id}, function(err, doc){
		if(err) return next(500);
		if(doc === null) return next(404);
		resp.represent({view: 'post/edit'
			, resource: new Resource({title: doc.title, posts: posts, css: ['post'], js: ['post']})
			, model: doc});
	});
});
app.get("/post.:format?", function getPostEditForm(req, resp, next){
	resp.represent({view: 'post/edit'
		, resource: new Resource({title: "New Post", posts: posts
			, css: ['post']
			, js: ['post']
		})
		, model: {
			title: ''
			, content: ''
			, author: req.user
			, published: new Date()
		}
	});
});
app.get('/reader.:format?', function(req, resp, next){
	resp.represent({view: 'reader/index'
		, resource: new Resource({
			title: "WillRead"
			, posts: posts
			})
			, model: {}
		});
});

app.put("/post/:_id.:format?", function updatePostById(req, resp, next){
	var postKey = null;
	var post = new Post();
	var id = req.params._id;
	Persistence.post.findOne({_id: id}, function(err, doc){
		if(!doc) return next(404);
		doc.title = req.body.title;
		doc.content = req.body.content;
		doc.author = req.user;
		doc.published = DateParser(req.body.published);
		client.send(new Commands.UpdatePost(doc));
		resp.redirect('/posts');
	});
});

app.post("/post.:format?", function(req, resp, next){
	var post = new Post();
	post.title = req.body.title;
	post.content = req.body.content;
	post.author = req.user;
	post.published = DateParser(req.body.published);
	client.send(new Commands.AddPost(post));
	resp.redirect('/posts');
});

app.get("/:slug.:format?", function (request, response, next){
	var filePath = postPath + request.params.slug + '.json';
	fs.exists(filePath, function(exists){
		if(!exists){
			return next(404);
		}
		fs.readFile(filePath, null, function(err, data){
			if(err){
				console.log(err);
				return next(500);
			}
			post = new Post(JSON.parse(data));
			response.represent({view: 'post/show', resource: new Resource({title: post.title, description: post.excerpt(255), author: post.author.name, posts: posts}), model: post});
		});
	})
});
function HttpStatus(code){
	this.code = code;
	var self = this;
	function messageFromCode(c){
		var message = 'Ok';
		switch(c){
			case(401):
				message = "Unauthorized";
				break;
			case(404):
				message = "Not Found";
				break;
		}
		return message;
	}
	Object.defineProperty(this, 'message', {
		get: function(){
			return messageFromCode(self.code);
		}
		, enumerable: true
	});
}

app.use(function(err, req, res, next){
	res.status(typeof err != 'number' ? 404 : err);
	var status = new HttpStatus(typeof err != 'number' ? 404 : err);
	res.send(status.message);
});
process.argv.forEach(function(value, fileName, args){
	if(/as:/.test(value)) config.runAsUser = /as\:([a-zA-Z-]+)/.exec(value)[1];
	if(/port:/.test(value)) config.port = /port:(\d+)/.exec(value)[1];
});
process.on('exit', function() {
	console.log('web server exited.');
});
process.on('SIGTERM', function(){
	console.log('SIGTERM.');
	process.exit(1);
});
process.on('SIGINT', function(){
	console.log('SIGINT.');
	process.exit(1);
});

var Server = app.listen(config.port, function(){
	console.log('Server started, on port ', Server.address().port);
});

var Commands = require('../blog/commands');
var Events = require('../blog/events');
var Bus = require('../web/bus');
var bus = new Bus.AsA_Subscriber(8125);
var client = new Bus.AsA_Client();
client.request(new PostRequest({published: {"$lt":(new Date()).getTime()}}), function(err, docs){
	console.log('post request replied with ', err, docs ? docs.length : ' docs is null');
});
bus.start();
console.log('starting subscriber');
bus.iSubscribeTo('PostWasUpdated', {host: 'localhost', port: 8124}, {
	update: function(event){
		Persistence.refresh();
		var post = event.body;
		postSyncher();
	}
});
bus.iSubscribeTo('PostWasCreated', {host: 'localhost', port: 8124}, {
	update: function(event){
		Persistence.refresh();
		var post = event.body;
		postSyncher();
	}
});
bus.iSubscribeTo('PostWasDeleted', {host: 'localhost', port: 8124}, {
	update: function(event){
		Persistence.refresh();
		var post = event.body;
		postSyncher();
	}
});
function PostRequest(query){
	this.query = query;
	this.header = {
		id: (new Date()).getTime()
		, endpoint: {port: 8124, host: 'localhost'}
		, token: ''
		, name: 'PostRequest'
	};
	this.type = 'request';
}
function synchMostRecentPost(){
	Persistence.post.findMostRecentlyPublished({published: {"$lt":(new Date()).getTime()}}, function(err, post){
		fs.writeFile(__dirname + '/data/index.json', JSON.stringify(post), function(err){
			if(err) console.log(err);
		});
	});
}
function postSyncher(){
	var files = fs.readdirSync(postPath);
	files.forEach(function(file){
		fs.unlinkSync(postPath + file);
	});
	Persistence.post.findPublished(function(err, docs){
		posts = [];
		docs.forEach(function(doc){
			fs.writeFile(rootPath + '/web/data/posts/' + doc.slug + '.json', JSON.stringify(doc), function(err){
				if(err) console.log(err);
			});
			posts.push(new Post(doc));
		});
		synchMostRecentPost();
	});
}
postSyncher();
<commit_msg>update path to index.json<commit_after>var express = require('express');
var app = express();
var fs = require('fs');
var rootPath = __dirname.replace('/web', '');
var staticServer = require('serve-static');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var Post = require('../blog/entities/post');
var config = require('../config');
var passport = require('passport');
var TwitterStrategy = require('passport-twitter').Strategy;
var Datastore = require('nedb');
var membersDbFilePath = config.dataPath + '/members.db';
var signer = require('jws');
var Editor = require(rootPath + '/blog/entities/editor');
var Persistence = require('../boundaries/persistence')(config);
var postPath = config.dataPath + '/posts/';
var DateParser = require('../dateParser');
var Marked = require('marked');

function Resource(obj){
	for(var key in obj) this[key] = obj[key];
}
Resource.prototype = {
	layout: 'default'
	, title: config.site.title
	, js: []
	, css: []
	, header: {}
	, user: null
	, status: {code: 200, description: 'Ok'}
	, posts: []
};
var represent = require('represent').Represent({
	themeRoot: rootPath + '/web/themes/' + config.theme
	, appPath: rootPath + '/web'
});
express.response.represent = require('./withRepresent')(represent, config);

app.use(compression());
app.use("/public", staticServer(represent.themeRoot));
app.set("views", rootPath + "/themes/default/templates");
app.set("view engine", function(view, options, fn){ return fn(view, options);});
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride(function(req, res){
	if(req.body._method) return req.body._method;
	return req.method;
}));
app.use(cookieSession({ keys: [config.cookie.key, ':blah:'], secret: config.cookie.secret}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(member, done) {
	var signature = signer.sign({
		header: {alg: 'HS256'}
		, payload: member.token
		, secret: config.secret
	});
	done(null, signature);
});
passport.deserializeUser(function deserializeUser(token, done) {
	var decodedSignature = signer.decode(token);
	if(!decodedSignature) return done(null, null);
	var db = new Datastore({filename: membersDbFilePath, autoload: true});
	db.findOne({token: decodedSignature.payload}, function(err, member) {
		if(err) console.log(err);
		done(err, member);
	});
});
function handleDatastoreError(err){
	if(err) console.log("An error occurred when manipulating a db file", err);
}
passport.use(new TwitterStrategy({
	consumerKey: config.twitter.consumer.key
	, consumerSecret: config.twitter.consumer.secret
	, callbackURL: config.twitter.callbackUrl
	, passReqToCallback: true
  }
  , function(request, token, tokenSecret, profile, done) {
	  var allowedTwitterUsers = ['ijoeyguerra', 'joseguerra', 'Hubot'];
	  if(allowedTwitterUsers.indexOf(profile.username) === -1) return done(null, null);
	  var db = new Datastore({filename: membersDbFilePath, autoload: true});
	  db.findOne({"token":token}, function(err, member){
			if(err) return done(err);
			if(member) return done(null, member);
			var memberDb = new Datastore({filename: membersDbFilePath, autoload: true});
			var editor = Editor({
				token: token
				, name: profile.displayName
				, avatar: profile._json.profile_background_image_url
				, username: profile.username
			});
			process.nextTick(function(){
				memberDb.insert(editor, function(err, docs){
					if(err) return done(err);
					done(null, docs);
				});
			});
	  });
  }
));

var posts = [];
app.get('/' + config.google.verification + '\.html', function(req, resp){
	resp.represent(200, 'google-site-verification: ' + config.google.verification + '.html');
});
app.get("/robots.txt", function(req, resp, next){
	resp.represent({
		view: 'robots/index'
		, resource: new Resource({
			posts: posts}
		)
		, model: {}});
});
app.get("/humans.txt", function(req, resp, next){
	resp.represent({
		view: 'humans/index'
		, resource: new Resource({
			posts: posts}
		)
		, model: {}});
});
app.get("/sitemap.:format", function(req, resp, next){
	resp.represent({
		view: 'sitemap/index'
		, resource: new Resource({
			posts: posts}
		)
		, model: posts});
});

app.get('/index:format?', function(req, resp, next){
	var post = new Post();
	fs.readFile(__dirname + '/data/index.json', null, function(err, data){
		if(err) console.log(err);
		post = new Post(JSON.parse(data));
		resp.represent({view: 'index/index'
			, resource: new Resource({
				posts: posts
			})
			, model: post});
	});
});
app.get('/', function(req, resp, next){
	var post = null;
	fs.readFile(__dirname + '/data/index.json', null, function(err, data){
		if(err){
			console.log(err);
			return next(404);
		}
		post = new Post(JSON.parse(data));
		resp.represent({view: 'index/index'
		, resource: new Resource({
			title: post.title
			, posts: posts
		})
		, model: post});
	});
});

// authenticated endpoints
app.get(['/posts.:format?', "/post.:format?", "/post/:title"], function(req, resp, next){
	if(!req.isAuthenticated()) return next(401);
	next();
});

app.post("/post.:format?", function(req, resp, next){
	if(!req.isAuthenticated()) return next(401);
	next();
});
app.get('/logout', function(req, resp, next){
	req.logout();
	resp.redirect('/');
});

// twitter auth endpoints
app.get('/auth/twitter\??', passport.authenticate('twitter'));
app.get("/auth/twitter/callback", passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/' }));

// posts endpoints
app.delete("/posts.:format?", function(req, resp, next){
	var id = req.body._id;
	Persistence.post.findOne({_id: id}, function(err, post){
		if(err) console.log(err);
		if(post && post._id !== null){
			client.send(new Commands.DeletePost(post));
		}
	});
	resp.redirect('/posts');
});

app.get("/posts.:format?", function(req, resp, next){
	var docs = [];
	Persistence.post.find({}, {published: -1}, function(err, docs){
		if(err){
			console.log(err);
			next(500);
		}
		resp.represent({view: 'post/index'
			, resource: new Resource({title: "List of Posts"
			, posts: posts})
			, model: docs});
	});
});
app.get('/posts/:_id.:format?', function(req, resp, next){
	Persistence.post.findOne({_id: req.params._id}, function(err, doc){
		if(err) return next(500);
		if(doc === null) return next(404);
		resp.represent({view: 'post/show'
			, resource: new Resource({title: doc.title, posts: posts, css: ['post'], js: ['post']})
			, model: doc});
	});
});
app.get("/post/:_id.:format?", function getPostById(req, resp, next){
	Persistence.post.findOne({_id: req.params._id}, function(err, doc){
		if(err) return next(500);
		if(doc === null) return next(404);
		resp.represent({view: 'post/edit'
			, resource: new Resource({title: doc.title, posts: posts, css: ['post'], js: ['post']})
			, model: doc});
	});
});
app.get("/post.:format?", function getPostEditForm(req, resp, next){
	resp.represent({view: 'post/edit'
		, resource: new Resource({title: "New Post", posts: posts
			, css: ['post']
			, js: ['post']
		})
		, model: {
			title: ''
			, content: ''
			, author: req.user
			, published: new Date()
		}
	});
});
app.get('/reader.:format?', function(req, resp, next){
	resp.represent({view: 'reader/index'
		, resource: new Resource({
			title: "WillRead"
			, posts: posts
			})
			, model: {}
		});
});

app.put("/post/:_id.:format?", function updatePostById(req, resp, next){
	var postKey = null;
	var post = new Post();
	var id = req.params._id;
	Persistence.post.findOne({_id: id}, function(err, doc){
		if(!doc) return next(404);
		doc.title = req.body.title;
		doc.content = req.body.content;
		doc.author = req.user;
		doc.published = DateParser(req.body.published);
		client.send(new Commands.UpdatePost(doc));
		resp.redirect('/posts');
	});
});

app.post("/post.:format?", function(req, resp, next){
	var post = new Post();
	post.title = req.body.title;
	post.content = req.body.content;
	post.author = req.user;
	post.published = DateParser(req.body.published);
	client.send(new Commands.AddPost(post));
	resp.redirect('/posts');
});

app.get("/:slug.:format?", function (request, response, next){
	var filePath = postPath + request.params.slug + '.json';
	fs.exists(filePath, function(exists){
		if(!exists){
			return next(404);
		}
		fs.readFile(filePath, null, function(err, data){
			if(err){
				console.log(err);
				return next(500);
			}
			post = new Post(JSON.parse(data));
			response.represent({view: 'post/show', resource: new Resource({title: post.title, description: post.excerpt(255), author: post.author.name, posts: posts}), model: post});
		});
	})
});
function HttpStatus(code){
	this.code = code;
	var self = this;
	function messageFromCode(c){
		var message = 'Ok';
		switch(c){
			case(401):
				message = "Unauthorized";
				break;
			case(404):
				message = "Not Found";
				break;
		}
		return message;
	}
	Object.defineProperty(this, 'message', {
		get: function(){
			return messageFromCode(self.code);
		}
		, enumerable: true
	});
}

app.use(function(err, req, res, next){
	res.status(typeof err != 'number' ? 404 : err);
	var status = new HttpStatus(typeof err != 'number' ? 404 : err);
	res.send(status.message);
});
process.argv.forEach(function(value, fileName, args){
	if(/as:/.test(value)) config.runAsUser = /as\:([a-zA-Z-]+)/.exec(value)[1];
	if(/port:/.test(value)) config.port = /port:(\d+)/.exec(value)[1];
});
process.on('exit', function() {
	console.log('web server exited.');
});
process.on('SIGTERM', function(){
	console.log('SIGTERM.');
	process.exit(1);
});
process.on('SIGINT', function(){
	console.log('SIGINT.');
	process.exit(1);
});

var Server = app.listen(config.port, function(){
	console.log('Server started, on port ', Server.address().port);
});

var Commands = require('../blog/commands');
var Events = require('../blog/events');
var Bus = require('../web/bus');
var bus = new Bus.AsA_Subscriber(8125);
var client = new Bus.AsA_Client();
client.request(new PostRequest({published: {"$lt":(new Date()).getTime()}}), function(err, docs){
	console.log('post request replied with ', err, docs ? docs.length : ' docs is null');
});
bus.start();
console.log('starting subscriber');
bus.iSubscribeTo('PostWasUpdated', {host: 'localhost', port: 8124}, {
	update: function(event){
		Persistence.refresh();
		var post = event.body;
		postSyncher();
	}
});
bus.iSubscribeTo('PostWasCreated', {host: 'localhost', port: 8124}, {
	update: function(event){
		Persistence.refresh();
		var post = event.body;
		postSyncher();
	}
});
bus.iSubscribeTo('PostWasDeleted', {host: 'localhost', port: 8124}, {
	update: function(event){
		Persistence.refresh();
		var post = event.body;
		postSyncher();
	}
});
function PostRequest(query){
	this.query = query;
	this.header = {
		id: (new Date()).getTime()
		, endpoint: {port: 8124, host: 'localhost'}
		, token: ''
		, name: 'PostRequest'
	};
	this.type = 'request';
}
function synchMostRecentPost(){
	Persistence.post.findMostRecentlyPublished({published: {"$lt":(new Date()).getTime()}}, function(err, post){
		fs.writeFile(config.dataPath + '/posts/index.json', JSON.stringify(post), function(err){
			if(err) console.log(err);
		});
	});
}
function postSyncher(){
	var files = fs.readdirSync(postPath);
	files.forEach(function(file){
		fs.unlinkSync(postPath + file);
	});
	Persistence.post.findPublished(function(err, docs){
		posts = [];
		docs.forEach(function(doc){
			fs.writeFile(config.dataPath + '/posts/' + doc.slug + '.json', JSON.stringify(doc), function(err){
				if(err) console.log(err);
			});
			posts.push(new Post(doc));
		});
		synchMostRecentPost();
	});
}
postSyncher();
<|endoftext|>


<commit_before>/**
 * Globals
 */
var messageList = [];
var activeTarget = -1;
var friendLis;
var current_user = null;

function addFriendListener() {
    var friend;

    friendLis = document.getElementById('friends-list').children;

    for (var i in friendLis) {
        friend = friendLis[i];

        if (friend.nodeName === "LI") {
            friend.addEventListener("click", function () {

                if (this.classList) {
                    this.classList.add('active');
                }

                // TODO: How do I remove?
                this.setAttribute('class', "active");
                var user_id = parseInt(this.getAttribute('user-id'));
                activeTarget = user_id;
                fetchLatestMessages();
            });
        }
    }

}

/**
 * Given a number, add a zero if it is less than 2 in length
 */
function padNumber(num) {
    var newNum = '0' + num;

    if (newNum.length < 3) {
        return newNum;
    } else {
        return num;
    }
}

function fetchLatestMessages() {
    if (activeTarget != -1) {
        var xmlHttp = new XMLHttpRequest();

        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                var response = xmlHttp.responseText;
                var messages = JSON.parse(response);

                var chat_message = document.getElementById("chat-list");

                // Reset the chat
                chat_message.innerHTML = "";
                messageList = [];

                for (var i in messages) {
                    // Only add new messages
                    if (messageList.indexOf(messages[i].id) < 0) {
                        var date = new Date(messages[i].sentTime.date.split(" ").join("T"));
                        var dateString = '' + padNumber(date.getHours()) + ':' + padNumber(date.getMinutes()) + ':' + padNumber(date.getSeconds());
                        var messageContent = messages[i].messageContent;
                        var sender = messages[i].sendUsername;

                        var el_li = document.createElement("li");
                        el_li.className = "message-ul";
                        el_li.innerHTML = '<time date-time="' + date.toString() + '">' + dateString + '</time>' +
                            '' + sender + ':' +
                            '' + messageContent + '';

                        // Append the converted object
                        chat_message.appendChild(el_li);

                        messageList.push(messages[i].id);
                    }
                }

            }

        }

        xmlHttp.open("GET", "messages/inbox/" + activeTarget, true);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xmlHttp.send();
    }
}

/**
 * Get the friend list for the current user
 */
function fetchFriendsList() {
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var response = xmlHttp.responseText;
            var friends = JSON.parse(response);

            // Build up the new
 elements
            var ul = document.getElementById('friends-list');

            for (var i in friends) {
                users = friends[i].users;

                for (var u in users) {
                    user = users[u];

                    if (user.id != current_user) {
                        el = document.createElement("li");
                        el.setAttribute('user-id', user.id);
                        // TODO: Add a wee checkmark for accepting?
                        el.innerHTML = user.username;

                        ul.appendChild(el);
                    }
                }
            }

            // Load the friend listener
            addFriendListener();
        }
    }
    xmlHttp.open("GET", "/user_relationship", true)
    xmlHttp.send()
}

/**
 * Send the results of the send message form to the backend
 */
function sendMessage() {
    if (activeTarget > 0) {
        console.log("Send Message");

        var date, xmlHttp, params;

        var messageText = $("#message-text").val();
        console.log(messageText);

        // TODO: Test override

        // Check the box isn't just empty, or empty strings
        // TODO: Add some HTML5 validation
        if (messageText != "") {
            xmlHttp = new XMLHttpRequest();

            xmlHttp.open('POST', '/messages/send', true);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

            // Parameters
            date = new Date();

            // Build up the parameters needed for the new Entity
            params = {
                "messageKey": "FIXME",
                "sentTime": {
                    "date": {
                        "month": date.getMonth() + 1,
                        "day": date.getDate(),
                        "year": date.getFullYear()
                    },
                    "time": {
                        "hour": date.getHours(),
                        "minute": date.getMinutes()
                    }
                },
                "messageContent": messageText,
                "targetUser": activeTarget
            }

            params = "json_str=" + JSON.stringify(params);
            xmlHttp.send(params);

            // Update the message list
            fetchLatestMessages();

            $("#message-text").val("");
        }
    }
}

/*
 * Setup the global current_user from the users endpoint
 */
function getUserId() {
    xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            current_user = xmlHttp.responseText;
        }
    }

    xmlHttp.open('GET', "/users/me", true);
    xmlHttp.send();
}

function addFriend() {
    var form, friend_name, xmlHttp, params;

    var messageText = $("#friend-name").val();

    if (friend_name != "") {
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open('POST', '/user_relationship/new', true);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        params = {
            "target_username": messageText
        }

        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState) {
                var response = xmlHttp.responseText;
                console.log(response);
            }
        }

        params = "json_str=" + JSON.stringify(params);
        xmlHttp.send(params);

        $("#friend-name").val("");
    }
}

/**
 * Globally setup some listeners
 */
getUserId();

// Check messages every second
var intervalId = window.setInterval(fetchLatestMessages, 3000);
<commit_msg>Replaced GET requests for friends list and messages with JQuery getJSON calls.<commit_after>/**
 * Globals
 */
var messageList = [];
var activeTarget = -1;
var friendLis;
var current_user = null;

function addFriendListener() {
    var friend;

    friendLis = document.getElementById('friends-list').children;

    for (var i in friendLis) {
        friend = friendLis[i];

        if (friend.nodeName === "LI") {
            friend.addEventListener("click", function () {

                if (this.classList) {
                    this.classList.add('active');
                }

                // TODO: How do I remove?
                this.setAttribute('class', "active");
                var user_id = parseInt(this.getAttribute('user-id'));
                activeTarget = user_id;
                fetchLatestMessages();
            });
        }
    }

}

/**
 * Given a number, add a zero if it is less than 2 in length
 */
function padNumber(num) {
    var newNum = '0' + num;

    if (newNum.length < 3) {
        return newNum;
    } else {
        return num;
    }
}

function fetchLatestMessages() {
    $.getJSON('/messages/inbox/' + activeTarget, function (messages) {
        var chat_message = document.getElementById("chat-list");

        // Reset the chat
        chat_message.innerHTML = "";
        messageList = [];

        for (var i in messages) {
            // Only add new messages
            if (messageList.indexOf(messages[i].id) < 0) {
                var date = new Date(messages[i].sentTime.date.split(" ").join("T"));
                var dateString = '' + padNumber(date.getHours()) + ':' + padNumber(date.getMinutes()) + ':' + padNumber(date.getSeconds());
                var messageContent = messages[i].messageContent;
                var sender = messages[i].sendUsername;

                var el_li = document.createElement("li");
                el_li.className = "message-ul";
                el_li.innerHTML = '<time date-time="' + date.toString() + '">' + dateString + '</time>' +
                    '' + sender + ':' +
                    '' + messageContent + '';

                // Append the converted object
                chat_message.appendChild(el_li);

                messageList.push(messages[i].id);
            }
        }
    });
}

/**
 * Get the friend list for the current user
 */
function fetchFriendsList() {
    $.getJSON('/user_relationship', function (friends) {
        // Build up the new
 elements
        var ul = document.getElementById('friends-list');

        for (var i in friends) {
            users = friends[i].users;

            for (var u in users) {
                user = users[u];

                if (user.id != current_user) {
                    el = document.createElement("li");
                    el.setAttribute('user-id', user.id);
                    // TODO: Add a wee checkmark for accepting?
                    el.innerHTML = user.username;

                    ul.appendChild(el);
                }
            }
        }

        // Load the friend listener
        addFriendListener();
    });
}

/**
 * Send the results of the send message form to the backend
 */
function sendMessage() {
    if (activeTarget > 0) {
        console.log("Send Message");

        var date, xmlHttp, params;

        var messageText = $("#message-text").val();
        console.log(messageText);

        // TODO: Test override

        // Check the box isn't just empty, or empty strings
        // TODO: Add some HTML5 validation
        if (messageText != "") {
            xmlHttp = new XMLHttpRequest();

            xmlHttp.open('POST', '/messages/send', true);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

            // Parameters
            date = new Date();

            // Build up the parameters needed for the new Entity
            params = {
                "messageKey": "FIXME",
                "sentTime": {
                    "date": {
                        "month": date.getMonth() + 1,
                        "day": date.getDate(),
                        "year": date.getFullYear()
                    },
                    "time": {
                        "hour": date.getHours(),
                        "minute": date.getMinutes()
                    }
                },
                "messageContent": messageText,
                "targetUser": activeTarget
            }

            params = "json_str=" + JSON.stringify(params);
            xmlHttp.send(params);

            // Update the message list
            fetchLatestMessages();

            $("#message-text").val("");
        }
    }
}

/*
 * Setup the global current_user from the users endpoint
 */
function getUserId() {
    xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            current_user = xmlHttp.responseText;
        }
    }

    xmlHttp.open('GET', "/users/me", true);
    xmlHttp.send();
}

function addFriend() {
    var form, friend_name, xmlHttp, params;

    var messageText = $("#friend-name").val();

    if (friend_name != "") {
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open('POST', '/user_relationship/new', true);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        params = {
            "target_username": messageText
        }

        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState) {
                var response = xmlHttp.responseText;
                console.log(response);
            }
        }

        params = "json_str=" + JSON.stringify(params);
        xmlHttp.send(params);

        $("#friend-name").val("");
    }
}

/**
 * Globally setup some listeners
 */
getUserId();

// Check messages every second
var intervalId = window.setInterval(fetchLatestMessages, 3000);
<|endoftext|>


<commit_before>window.admin = {};

$(document).ready(function() {
	$("#admin-feedback").on("tabOpened", function() {
		window.api.get("admin/feedback/getList", function(resp) {
			$("#admin-feedback-list").text("");
			for (var feedbackIndex in resp.feedback) {
				var feedbackItem = resp.feedback[feedbackIndex];
				var $feedbackLi = $('

');
					var $feedbackDesc = $('

');
						$feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg);
						var $icon = $('');
							if (feedbackItem.type == "smile") {
								$icon.addClass("fa-smile-o");
							} else if (feedbackItem.type == "frown") {
								$icon.addClass("fa-frown-o");
							} else if (feedbackItem.type == "idea") {
								$icon.addClass("fa-lightbulb-o");
							}
						$feedbackDesc.prepend($icon);
					$feedbackLi.append($feedbackDesc);
					var $feedbackName = $('

');
						$feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")");
					$feedbackLi.append($feedbackName);
					var $feedbackDay = $('

');
						$feedbackDay.children("em").text("Sent " + moment(feedbackItem.timestamp).format("MM/DD/YY"));
					$feedbackLi.append($feedbackDay);
					$feedbackLi.attr("data-webpage", feedbackItem.webpage)
					$feedbackLi.click(function() {
						$("#admin-feedback-modal").find("iframe").attr("src", "data:text/html;base64," + $(this).attr("data-webpage"));
						$("#admin-feedback-modal").modal();
					});
				$("#admin-feedback-list").append($feedbackLi);
			};
		});
	});
	window.api.get('overview/announcements/get/', function(data) {
		var response = data.feedback;
		for(feed in response) {
			if(moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
				var $feedLi = $("

");
					$feedLi.append(response[feed].msg);
					$feedLi.attr("data-id", response[feed].announcementId);
					$("#adminAnnouncementList").append($feedLi);
					var $removeBtn = $('<button class="btn btn-xs btn-danger"></button>');
						$removeBtn.click(function() {
							var idThingy = $(this).parent().attr("data-id");
							window.api.post('admin/announcements/remove', {id: idThingy}, function(result){});
						});
					$feedLi.append($removeBtn)
				$("#announcement-delete-list").append($feedLi);
			}
		}
		if($("#adminAnnouncementList").children().size() > 1) {
			$("#adminNoAnnouncements").remove()
		}
	});
	$("#announcement-submit").click(function() {
		var postMe = {};
		postMe.days = $("#announcement-days").val();
		postMe.time = window.utils.formatDate_api(moment().toDate());
		postMe.msg = $("#announcement-msg").val();
		window.api.post('admin/announcements/post/', postMe, function(result){});
		swal("Yay", "Your announcment has been posted", "success");
	});
});
<commit_msg>maybe thast the issue<commit_after>window.admin = {};

$(document).ready(function() {
	$("#admin-feedback").on("tabOpened", function() {
		window.api.get("admin/feedback/getList", function(resp) {
			$("#admin-feedback-list").text("");
			for (var feedbackIndex in resp.feedback) {
				var feedbackItem = resp.feedback[feedbackIndex];
				var $feedbackLi = $('

');
					var $feedbackDesc = $('

');
						$feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg);
						var $icon = $('');
							if (feedbackItem.type == "smile") {
								$icon.addClass("fa-smile-o");
							} else if (feedbackItem.type == "frown") {
								$icon.addClass("fa-frown-o");
							} else if (feedbackItem.type == "idea") {
								$icon.addClass("fa-lightbulb-o");
							}
						$feedbackDesc.prepend($icon);
					$feedbackLi.append($feedbackDesc);
					var $feedbackName = $('

');
						$feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")");
					$feedbackLi.append($feedbackName);
					var $feedbackDay = $('

');
						$feedbackDay.children("em").text("Sent " + moment(feedbackItem.timestamp).format("MM/DD/YY"));
					$feedbackLi.append($feedbackDay);
					$feedbackLi.attr("data-webpage", feedbackItem.webpage)
					$feedbackLi.click(function() {
						$("#admin-feedback-modal").find("iframe").attr("src", "data:text/html;base64," + $(this).attr("data-webpage"));
						$("#admin-feedback-modal").modal();
					});
				$("#admin-feedback-list").append($feedbackLi);
			};
		});
	});
	window.api.get('overview/announcements/get/', function(data) {
		var response = data.feedback;
		for(feed in response) {
			if(moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
				var $feedLi = $("

");
					$feedLi.append(response[feed].msg);
					$feedLi.attr("data-id", response[feed].announcementId);
					var $copyLi = $feedLi;
					$("#adminAnnouncementList").append($copyLi);
					var $removeBtn = $('<button class="btn btn-xs btn-danger"></button>');
						$removeBtn.click(function() {
							var idThingy = $(this).parent().attr("data-id");
							window.api.post('admin/announcements/remove', {id: idThingy}, function(result){});
						});
					$feedLi.append($removeBtn)
				$("#announcement-delete-list").append($feedLi);
			}
		}
		if($("#adminAnnouncementList").children().size() > 1) {
			$("#adminNoAnnouncements").remove()
		}
	});
	$("#announcement-submit").click(function() {
		var postMe = {};
		postMe.days = $("#announcement-days").val();
		postMe.time = window.utils.formatDate_api(moment().toDate());
		postMe.msg = $("#announcement-msg").val();
		window.api.post('admin/announcements/post/', postMe, function(result){});
		swal("Yay", "Your announcment has been posted", "success");
	});
});
<|endoftext|>


<commit_before>function output_add_rewrite_var (name, value) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: ob_list_handlers
    // *     example 1: output_add_rewrite_var('var', 'value');
    // *     returns 1: true

    var handlers = [], handler='', startAgain=true;

    handlers = this.ob_list_handlers();

    if (handlers) {
        handler = handlers.pop();
        if (handler === 'URL-Rewriter') {
            startAgain = false;
        }
    }
    if (startAgain) {
        ob_start('URL-Rewriter', 0, true);
    }

    if (!this.php_js.obs[this.php_js.obs.length-1].vars) {
        this.php_js.obs[this.php_js.obs.length-1].vars = {};
    }
    this.php_js.obs[this.php_js.obs.length-1].vars[name] = value;

    return true;
}<commit_msg>Indicate another dependency and add 'this'<commit_after>function output_add_rewrite_var (name, value) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: ob_list_handlers
    // -    depends on: ob_start
    // *     example 1: output_add_rewrite_var('var', 'value');
    // *     returns 1: true

    var handlers = [], handler='', startAgain=true;

    handlers = this.ob_list_handlers();

    if (handlers) {
        handler = handlers.pop();
        if (handler === 'URL-Rewriter') {
            startAgain = false;
        }
    }
    if (startAgain) {
        this.ob_start('URL-Rewriter', 0, true);
    }

    if (!this.php_js.obs[this.php_js.obs.length-1].vars) {
        this.php_js.obs[this.php_js.obs.length-1].vars = {};
    }
    this.php_js.obs[this.php_js.obs.length-1].vars[name] = value;

    return true;
}<|endoftext|>