<commit_before>#!/usr/bin/env node
"use strict";

var assert = require('assert')
var _ = require('underscore');
var URI = require('URIjs');
var Client = require('node-rest-client').Client;
var Tool = require('swagger-tools').specs.v2;
var mime = require('mime-types');
var jp = require('jsonpath');
var api = require('json-schema-compatibility');
var fs = require('fs');

function validateSwagger(swagger, cb) {
  //Trick to get rid of undefined properties
  var strSwagger = JSON.stringify(swagger, null, 2);
  swagger = JSON.parse(strSwagger);

  return Tool.validate(swagger, function (validationError, validationResults) {
    if (validationError) {
      console.log(validationError);
      process.exit(1);
    }

    if (validationResults && validationResults.errors && validationResults.errors.length) {
      console.log(strSwagger);
      console.log(validationResults.errors);
      process.exit(1);
    }
    cb(strSwagger);
  });
}

if (!process.argv[2]) {
  console.log("missing directory name");
  process.exit(1);
}

mkdirSafe(process.argv[2]);
process.chdir(process.argv[2]);

var discovery = new Client();
discovery.get("https://www.googleapis.com/discovery/v1/apis", processList);

function processList(data,response) {
   data = JSON.parse(data);
   assert.equal(data.kind, 'discovery#directoryList')
   assert.equal(data.discoveryVersion, 'v1')

   //FIXME: data.preferred

   data.items.map(function (api) {
     discovery.get(api.discoveryRestUrl, processAPI);
   });
}

function processAPI(data) {
   data = JSON.parse(data);

   assert.equal(data.kind, 'discovery#restDescription')
   assert.equal(data.discoveryVersion, 'v1')
   assert.equal(data.protocol, 'rest')

   if ([
         //missing API description
         "cloudlatencytest:v2",
         //asterisk in path
         "admin:directory_v1",
         //plus in path
         "pubsub:v1beta1",
         "pubsub:v1beta1a",
         "pubsub:v1beta2",
         //FIXME: bug with default value, not matching enum definition
         "blogger:v3",
         "youtube:v3",
         //FIXME
         //circular reference in MapFolder/MapItem
         "mapsengine:exp2",
         "mapsengine:v1",
       ].indexOf(data.id) >= 0) {
      return;
   }

   //fields that doesn't map to anything:
   //	id
   //	name
   //	revision
   //	icons
   //	batchPath

   //deprecated:
   //	baseUrl
   //	basePath

   //FIXME:
   //console.log(data.labels);
   //features

   var rootUrl = URI(data.rootUrl);
   var srGlobalRefParameters = [];
   var srGlobalParameters = processGlobalParameters(data.parameters, srGlobalRefParameters);

   var swagger = {
     swagger: "2.0",
     info: {
       title: data.title,
       description: data.description,
       contact: {
         name: data.ownerName,
         url: 'https://' + data.ownerDomain,
       },
       version: data.version,
     },
     host: rootUrl.host(),
     basePath: "/" + data.servicePath.replace(/^\/|\/$/, ""),
     schemes: [rootUrl.scheme()],
     externalDocs: {
       url: data.documentationLink,
     },
     paths: processResource(data, srGlobalRefParameters),
     definitions: processDefinitions(data.schemas),
     parameters: srGlobalParameters,
   };

   //if ("auth" in data) {
   //  assert("oauth2" in data.auth);

   //  _.extend(swagger, {
   //    security: {
   //    },
   //    securityDefinitions: {
   //      type: "oauth2",
   //    }
   //  });
   //  var auth = data.auth;
   //  var srSecurity = {
   //  };

   //  swagger.security = srSecurity;
   //}
   validateSwagger(swagger, function (str) {
     saveSwagger(data.name, data.version, str);
   });
}

function saveSwagger(name, version, swagger) {
  var path = name + '/';
  mkdirSafe(path);
  path += version + '/';
  mkdirSafe(path);
  path += 'swagger.json'
  fs.writeFileSync(path, swagger)
  console.log(path);
}

function mkdirSafe(path) {
  try {
    fs.mkdirSync(path);
  } catch (e) {
    if (e.code !== 'EEXIST')
      throw e;
  }
}

function processGlobalParameters(parameters, srGlobalRefParameters) {
  var srGlobalParameters = {};
  for (var name in parameters) {
    srGlobalParameters[name] = processParameter(name, parameters[name]);
    srGlobalRefParameters.push({$ref: '#/parameters/' + name});
  }
  return srGlobalParameters;
}

function fixRef(ref) {
  return "#/definitions/" + ref;
}

function processDefinitions(schemas) {
  if (schemas == undefined)
    return undefined;

  schemas = api.v4(schemas);
  jp.apply(schemas, "$..*['$ref']" , function (value) {
    //if $ref isn't string it mean that this isn't reference
    //it something called '$ref', this happens in "discovery:v1".
    if (typeof value !== "string")
      return value;
    return fixRef(value);
  });

  jp.apply(schemas, "$..*.type" , function (value) {
    if (value === "any")
      return undefined;
    return value;
  });

  //Google for some reason code minimum/maximum as strings
  function convertInt(value) {
    if (typeof value === "string")
      return parseInt(value);
    return value;
  }
  jp.apply(schemas, "$..*.minimum" , convertInt);
  jp.apply(schemas, "$..*.maximum" , convertInt);

  return schemas;
}

function processResource(resources, srGlobalRefParameters, srPaths) {
  srPaths = srPaths || {};
  //Process methods
  if ("methods" in resources) {
    for (var key in resources.methods) {
      var method = resources.methods[key];
      var srPath = "/" + method.path;
      var srOperation = method.httpMethod.toLowerCase();

      if (!(srPath in srPaths))
        srPaths[srPath] = { parameters: srGlobalRefParameters };
      srPaths[srPath][srOperation] = processMethod(method);
    }
  }

  //Process recursive resources
  if ("resources" in resources)
    for (var key in resources.resources)
      processResource(resources.resources[key], srGlobalRefParameters, srPaths);

  return srPaths;
}

function convertMime(list) {
  var result = [];
  _.each(list, function (pattern) {
    _.each(mime.glob(pattern), function (name) {
      //FIXME: workaround for https://github.com/swagger-api/swagger-spec/issues/268
      if (name.indexOf("_") >= 0)
        return;
      result.push(name);
    });
  });
  return result;
}

function processMethod(method) {
   var srResponse = {
     description: "Successful response",
   };

   var srMethod = {
     description: method.description,
     operationId: method.id,
     responses: {
       200 : srResponse
     },
   };

   //TODO: test on youtube example
   if (method.supportsMediaUpload) {
     srMethod.consumes = convertMime(method.mediaUpload.accept);
     //TODO: rest of fields in 'mediaUpload'
   }

   //FIXME: https://code.google.com/p/google-api-go-client/issues/detail?id=16
   //assert(!method.hasOwnProperty('supportsMediaDownload'))
   //FIXME: supportsSubscription
   //FIXME: oath

   if ("parameters" in method)
     srMethod.parameters = processParameterList(method);

   //FIXME:
   //assert(!("request" in method));

   if ("response" in method) {
     assert("$ref" in method.response);
     srResponse.schema = {
       $ref: fixRef(method.response.$ref)
     };
   }

   return srMethod;
}

function processParameterList(method) {
   var parameters = method.parameters;
   var paramOrder = method.paramOreder || [];

   var srParameters = paramOrder.map(function (name) {
     return processParameter(name, parameters[name])
   });

   for (var name in parameters) {
     if (paramOrder.indexOf(name) !== -1)
       continue;
     var srParam = processParameter(name, parameters[name])
     srParameters.push(srParam);
   }

   return srParameters;
}

function processParameter(name, param) {

  assert(!('$ref' in param));
  assert(param.location == 'query' || param.location == 'path');
  assert(["string", "number", "integer", "boolean"].indexOf(param.type) >= 0);
  assert(!("properties" in param));
  assert(!("additionalProperties" in param));
  assert(!("annotations" in param));

  var srParam = {
    name: name,
    in: param.location,
    description: param.description,
    required: param.required,
    default: param.default
  };

  var srType = srParam;
  if (param.repeated === true) {
    srType = {}
    _.extend(srParam, {
      type: "array",
      items: srType,
      //FIXME: test
      collectionFormat: ((srParam.in === "path") ? "csv" : "multi")
    });
  }

  _.extend(srType, {
    type: param.type,
    enum: param.enum,
    minimum: (param.minimum ? parseInt(param.minimum) : undefined),
    maximum: (param.maximum ? parseInt(param.maximum) : undefined)
  });

  //FIXME: enumDescriptions
  if ("format" in param) {
    //FIXME: convert format.
  }

  return srParam;
}
<commit_msg>Fix indentation<commit_after>#!/usr/bin/env node
"use strict";

var assert = require('assert')
var _ = require('underscore');
var URI = require('URIjs');
var Client = require('node-rest-client').Client;
var Tool = require('swagger-tools').specs.v2;
var mime = require('mime-types');
var jp = require('jsonpath');
var api = require('json-schema-compatibility');
var fs = require('fs');

function validateSwagger(swagger, cb) {
  //Trick to get rid of undefined properties
  var strSwagger = JSON.stringify(swagger, null, 2);
  swagger = JSON.parse(strSwagger);

  return Tool.validate(swagger, function (validationError, validationResults) {
    if (validationError) {
      console.log(validationError);
      process.exit(1);
    }

    if (validationResults && validationResults.errors && validationResults.errors.length) {
      console.log(strSwagger);
      console.log(validationResults.errors);
      process.exit(1);
    }
    cb(strSwagger);
  });
}

if (!process.argv[2]) {
  console.log("missing directory name");
  process.exit(1);
}

mkdirSafe(process.argv[2]);
process.chdir(process.argv[2]);

var discovery = new Client();
discovery.get("https://www.googleapis.com/discovery/v1/apis", processList);

function processList(data,response) {
  data = JSON.parse(data);
  assert.equal(data.kind, 'discovery#directoryList')
  assert.equal(data.discoveryVersion, 'v1')

  //FIXME: data.preferred

  data.items.map(function (api) {
    discovery.get(api.discoveryRestUrl, processAPI);
  });
}

function processAPI(data) {
  data = JSON.parse(data);

  assert.equal(data.kind, 'discovery#restDescription')
  assert.equal(data.discoveryVersion, 'v1')
  assert.equal(data.protocol, 'rest')

  if ([
         //missing API description
         "cloudlatencytest:v2",
         //asterisk in path
         "admin:directory_v1",
         //plus in path
         "pubsub:v1beta1",
         "pubsub:v1beta1a",
         "pubsub:v1beta2",
         //FIXME: bug with default value, not matching enum definition
         "blogger:v3",
         "youtube:v3",
         //FIXME
         //circular reference in MapFolder/MapItem
         "mapsengine:exp2",
         "mapsengine:v1",
       ].indexOf(data.id) >= 0) {
      return;
  }

  //fields that doesn't map to anything:
  //	id
  //	name
  //	revision
  //	icons
  //	batchPath

  //deprecated:
  //	baseUrl
  //	basePath

  //FIXME:
  //console.log(data.labels);
  //features

  var rootUrl = URI(data.rootUrl);
  var srGlobalRefParameters = [];
  var srGlobalParameters = processGlobalParameters(data.parameters, srGlobalRefParameters);

  var swagger = {
    swagger: "2.0",
    info: {
      title: data.title,
      description: data.description,
      contact: {
        name: data.ownerName,
        url: 'https://' + data.ownerDomain,
      },
      version: data.version,
    },
    host: rootUrl.host(),
    basePath: "/" + data.servicePath.replace(/^\/|\/$/, ""),
    schemes: [rootUrl.scheme()],
    externalDocs: {
      url: data.documentationLink,
    },
    paths: processResource(data, srGlobalRefParameters),
    definitions: processDefinitions(data.schemas),
    parameters: srGlobalParameters,
  };

  //if ("auth" in data) {
  //  assert("oauth2" in data.auth);

  //  _.extend(swagger, {
  //    security: {
  //    },
  //    securityDefinitions: {
  //      type: "oauth2",
  //    }
  //  });
  //  var auth = data.auth;
  //  var srSecurity = {
  //  };

  //  swagger.security = srSecurity;
  //}
  validateSwagger(swagger, function (str) {
    saveSwagger(data.name, data.version, str);
  });
}

function saveSwagger(name, version, swagger) {
  var path = name + '/';
  mkdirSafe(path);
  path += version + '/';
  mkdirSafe(path);
  path += 'swagger.json'
  fs.writeFileSync(path, swagger)
  console.log(path);
}

function mkdirSafe(path) {
  try {
    fs.mkdirSync(path);
  } catch (e) {
    if (e.code !== 'EEXIST')
      throw e;
  }
}

function processGlobalParameters(parameters, srGlobalRefParameters) {
  var srGlobalParameters = {};
  for (var name in parameters) {
    srGlobalParameters[name] = processParameter(name, parameters[name]);
    srGlobalRefParameters.push({$ref: '#/parameters/' + name});
  }
  return srGlobalParameters;
}

function fixRef(ref) {
  return "#/definitions/" + ref;
}

function processDefinitions(schemas) {
  if (schemas == undefined)
    return undefined;

  schemas = api.v4(schemas);
  jp.apply(schemas, "$..*['$ref']" , function (value) {
    //if $ref isn't string it mean that this isn't reference
    //it something called '$ref', this happens in "discovery:v1".
    if (typeof value !== "string")
      return value;
    return fixRef(value);
  });

  jp.apply(schemas, "$..*.type" , function (value) {
    if (value === "any")
      return undefined;
    return value;
  });

  //Google for some reason code minimum/maximum as strings
  function convertInt(value) {
    if (typeof value === "string")
      return parseInt(value);
    return value;
  }
  jp.apply(schemas, "$..*.minimum" , convertInt);
  jp.apply(schemas, "$..*.maximum" , convertInt);

  return schemas;
}

function processResource(resources, srGlobalRefParameters, srPaths) {
  srPaths = srPaths || {};
  //Process methods
  if ("methods" in resources) {
    for (var key in resources.methods) {
      var method = resources.methods[key];
      var srPath = "/" + method.path;
      var srOperation = method.httpMethod.toLowerCase();

      if (!(srPath in srPaths))
        srPaths[srPath] = { parameters: srGlobalRefParameters };
      srPaths[srPath][srOperation] = processMethod(method);
    }
  }

  //Process recursive resources
  if ("resources" in resources)
    for (var key in resources.resources)
      processResource(resources.resources[key], srGlobalRefParameters, srPaths);

  return srPaths;
}

function convertMime(list) {
  var result = [];
  _.each(list, function (pattern) {
    _.each(mime.glob(pattern), function (name) {
      //FIXME: workaround for https://github.com/swagger-api/swagger-spec/issues/268
      if (name.indexOf("_") >= 0)
        return;
      result.push(name);
    });
  });
  return result;
}

function processMethod(method) {
  var srResponse = {
    description: "Successful response",
  };

  var srMethod = {
    description: method.description,
    operationId: method.id,
    responses: {
      200 : srResponse
    },
  };

  //TODO: test on youtube example
  if (method.supportsMediaUpload) {
    srMethod.consumes = convertMime(method.mediaUpload.accept);
    //TODO: rest of fields in 'mediaUpload'
  }

  //FIXME: https://code.google.com/p/google-api-go-client/issues/detail?id=16
  //assert(!method.hasOwnProperty('supportsMediaDownload'))
  //FIXME: supportsSubscription
  //FIXME: oath

  if ("parameters" in method)
    srMethod.parameters = processParameterList(method);

  //FIXME:
  //assert(!("request" in method));

  if ("response" in method) {
    assert("$ref" in method.response);
    srResponse.schema = {
      $ref: fixRef(method.response.$ref)
    };
  }

  return srMethod;
}

function processParameterList(method) {
  var parameters = method.parameters;
  var paramOrder = method.paramOreder || [];

  var srParameters = paramOrder.map(function (name) {
    return processParameter(name, parameters[name])
  });

  for (var name in parameters) {
    if (paramOrder.indexOf(name) !== -1)
      continue;
    var srParam = processParameter(name, parameters[name])
    srParameters.push(srParam);
  }

  return srParameters;
}

function processParameter(name, param) {

  assert(!('$ref' in param));
  assert(param.location == 'query' || param.location == 'path');
  assert(["string", "number", "integer", "boolean"].indexOf(param.type) >= 0);
  assert(!("properties" in param));
  assert(!("additionalProperties" in param));
  assert(!("annotations" in param));

  var srParam = {
    name: name,
    in: param.location,
    description: param.description,
    required: param.required,
    default: param.default
  };

  var srType = srParam;
  if (param.repeated === true) {
    srType = {}
    _.extend(srParam, {
      type: "array",
      items: srType,
      //FIXME: test
      collectionFormat: ((srParam.in === "path") ? "csv" : "multi")
    });
  }

  _.extend(srType, {
    type: param.type,
    enum: param.enum,
    minimum: (param.minimum ? parseInt(param.minimum) : undefined),
    maximum: (param.maximum ? parseInt(param.maximum) : undefined)
  });

  //FIXME: enumDescriptions
  if ("format" in param) {
    //FIXME: convert format.
  }

  return srParam;
}
<|endoftext|>


<commit_before>import { prettyPrintXML } from 'substance'
import { JATSExporter, TextureArchive } from 'substance-texture'
import ArticleLoader from './article/ArticleLoader'
import SheetLoader from './sheet/SheetLoader'

export default class StencilaArchive extends TextureArchive {

  constructor(storage, buffer, context) {
    super(storage, buffer)
    this._context = context
  }

  _loadDocument(type, record, sessions) {
    let context = this._context
    let editorSession
    switch (type) {
      case 'article': {
        context = Object.assign({}, this._context, {
          pubMetaDb: sessions['pub-meta'].getDocument(),
          archive: this
        })
        editorSession = ArticleLoader.load(record.data, context)
        break
      }
      case 'sheet': {
        editorSession = SheetLoader.load(record.data, context)
        break
      }
      default:
        throw new Error('Unsupported document type')
    }
    let doc = editorSession.getDocument()
    doc.documentType = type
    return editorSession
  }

  _exportDocument(type, session, sessions) {
    switch (type) {
      case 'article': {
        // FIXME: hard-coded, and thus bad
        // TODO: export only those resources which have been changed
        // Also we need to
        let jatsExporter = new JATSExporter()
        let pubMetaDb = sessions['pub-meta'].getDocument()
        let doc = session.getDocument()
        let dom = doc.toXML()
        let res = jatsExporter.export(dom, { pubMetaDb, doc })
        console.info('saving jats', res.dom.getNativeElement())
        // TODO: bring back pretty printing (currently messes up CDATA content)
        let xmlStr = prettyPrintXML(res.dom)
        //let xmlStr = res.dom.serialize()
        return xmlStr
      }
      case 'sheet': {
        let dom = session.getDocument().toXML()
        let xmlStr = prettyPrintXML(dom)
        return xmlStr
      }
      default:
        throw new Error('Unsupported document type')
    }
  }

  /*
    We use the name of the first document
  */
  getTitle() {
    let entries = this.getDocumentEntries()
    let firstEntry = entries[0]
    return firstEntry.name || firstEntry.id
  }

  getDocumentType(documentId) {
    let editorSession = this.getEditorSession(documentId)
    let doc = editorSession.getDocument()
    return doc.documentType
  }

  // added `info.action = 'addDocument'`
  // TODO: this should go into substance.PersistedDocumentArchive
  _addDocumentRecord(documentId, type, name, path) {
    this._sessions.manifest.transaction(tx => {
      let documents = tx.find('documents')
      let docEntry = tx.createElement('document', { id: documentId }).attr({
        name: name,
        path: path,
        type: type
      })
      documents.appendChild(docEntry)
    }, { action: 'addDocument' })
  }

  // added `info.action = 'renameDocument'`
  // TODO: this should go into substance.PersistedDocumentArchive
  renameDocument(documentId, name) {
    this._sessions.manifest.transaction(tx => {
      let docEntry = tx.find(`#${documentId}`)
      docEntry.attr({name})
    }, { action: 'renameDocument' })
  }

}<commit_msg>Quick fix for loading a DAR with missing resources.<commit_after>import { prettyPrintXML } from 'substance'
import { JATSExporter, TextureArchive } from 'substance-texture'
import ArticleLoader from './article/ArticleLoader'
import SheetLoader from './sheet/SheetLoader'

export default class StencilaArchive extends TextureArchive {

  constructor(storage, buffer, context) {
    super(storage, buffer)
    this._context = context
  }

  // FIXME: Texture #499
  // copied this code from TextureArchive applying a quick-fix
  _ingest(rawArchive) {
    let sessions = {}
    let manifestXML = _importManifest(rawArchive.resources['manifest.xml'].data)
    let manifestSession = this._loadManifest({ data: manifestXML })
    sessions['manifest'] = manifestSession
    let entries = manifestSession.getDocument().getDocumentEntries()

    // Setup empty pubMetaSession for holding the entity database
    let pubMetaSession = PubMetaLoader.load()
    sessions['pub-meta'] = pubMetaSession

    entries.forEach(entry => {
      let record = rawArchive.resources[entry.path]
      if (!record) return
      // Load any document except pub-meta (which we prepared manually)
      if (entry.type !== 'pub-meta') {
        // Passing down 'sessions' so that we can add to the pub-meta session
        let session = this._loadDocument(entry.type, record, sessions)
        sessions[entry.id] = session
      }
    })
    return sessions
  }

  _loadDocument(type, record, sessions) {
    let context = this._context
    let editorSession
    switch (type) {
      case 'article': {
        context = Object.assign({}, this._context, {
          pubMetaDb: sessions['pub-meta'].getDocument(),
          archive: this
        })
        editorSession = ArticleLoader.load(record.data, context)
        break
      }
      case 'sheet': {
        editorSession = SheetLoader.load(record.data, context)
        break
      }
      default:
        throw new Error('Unsupported document type')
    }
    let doc = editorSession.getDocument()
    doc.documentType = type
    return editorSession
  }

  _exportDocument(type, session, sessions) {
    switch (type) {
      case 'article': {
        // FIXME: hard-coded, and thus bad
        // TODO: export only those resources which have been changed
        // Also we need to
        let jatsExporter = new JATSExporter()
        let pubMetaDb = sessions['pub-meta'].getDocument()
        let doc = session.getDocument()
        let dom = doc.toXML()
        let res = jatsExporter.export(dom, { pubMetaDb, doc })
        console.info('saving jats', res.dom.getNativeElement())
        // TODO: bring back pretty printing (currently messes up CDATA content)
        let xmlStr = prettyPrintXML(res.dom)
        //let xmlStr = res.dom.serialize()
        return xmlStr
      }
      case 'sheet': {
        let dom = session.getDocument().toXML()
        let xmlStr = prettyPrintXML(dom)
        return xmlStr
      }
      default:
        throw new Error('Unsupported document type')
    }
  }

  /*
    We use the name of the first document
  */
  getTitle() {
    let entries = this.getDocumentEntries()
    let firstEntry = entries[0]
    return firstEntry.name || firstEntry.id
  }

  getDocumentType(documentId) {
    let editorSession = this.getEditorSession(documentId)
    let doc = editorSession.getDocument()
    return doc.documentType
  }

  // added `info.action = 'addDocument'`
  // TODO: this should go into substance.PersistedDocumentArchive
  _addDocumentRecord(documentId, type, name, path) {
    this._sessions.manifest.transaction(tx => {
      let documents = tx.find('documents')
      let docEntry = tx.createElement('document', { id: documentId }).attr({
        name: name,
        path: path,
        type: type
      })
      documents.appendChild(docEntry)
    }, { action: 'addDocument' })
  }

  // added `info.action = 'renameDocument'`
  // TODO: this should go into substance.PersistedDocumentArchive
  renameDocument(documentId, name) {
    this._sessions.manifest.transaction(tx => {
      let docEntry = tx.find(`#${documentId}`)
      docEntry.attr({name})
    }, { action: 'renameDocument' })
  }

}<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
    model(params) {
        return this.store.find('todo-list', params.id);
    }
});
<commit_msg>Reload todo-list in todo-list route if relationships not loaded<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
    setupController(controller, model) {
        if (!model) {
            return controller.set('model', this.store.find('todo-list', model.id));
        }

        if (!model._internalModel ||
            !model._internalModel._relationships ||
            !model._internalModel._relationships.initializedRelationships
        ) {
            return controller.set('model', this.store.fetchById('todo-list', model.id));
        }

        var relationships = model._internalModel._relationships.initializedRelationships;
        if (relationships.groups.canonicalState[0].dataHasInitialized) {
            return;
        }

        return controller.set('model', this.store.fetchById('todo-list', model.id));
    }
});
<|endoftext|>


<commit_before>import React, {Component, Children} from 'react';
import PropTypes from 'prop-types';
import StepConnector from './StepConnector';

const getStyles = (props) => {
  const {orientation} = props;
  return {
    root: {
      display: 'flex',
      flexDirection: orientation === 'horizontal' ? 'row' : 'column',
      alignContent: 'center',
      alignItems: orientation === 'horizontal' ? 'center' : 'stretch',
      justifyContent: 'space-between',
    },
  };
};

class Stepper extends Component {

  static propTypes = {
    /**
     * Set the active step (zero based index). This will enable `Step` control helpers.
     */
    activeStep: PropTypes.number,
    /**
     * Should be two or more `<Step />` components
     */
    children: PropTypes.arrayOf(PropTypes.node),
    /**
     * A component to be placed between each step.
     */
    connector: PropTypes.node,
    /**
     * If set to `true`, the `Stepper` will assist in controlling steps for linear flow
     */
    linear: PropTypes.bool,
    /**
     * The stepper orientation (layout flow direction)
     */
    orientation: PropTypes.oneOf(['horizontal', 'vertical']),
    /**
     * Override the inline-style of the root element.
     */
    style: PropTypes.object,
  };

  static defaultProps = {
    connector: <StepConnector />,
    orientation: 'horizontal',
    linear: true,
  };

  static contextTypes = {muiTheme: PropTypes.object.isRequired};

  static childContextTypes = {stepper: PropTypes.object};

  getChildContext() {
    const {orientation} = this.props;
    return {stepper: {orientation}};
  }

  render() {
    const {
      activeStep,
      children,
      connector,
      linear,
      style,
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const styles = getStyles(this.props, this.context);

    /**
     * One day, we may be able to use real CSS tools
     * For now, we need to create our own "pseudo" elements
     * and nth child selectors, etc
     * That's what some of this garbage is for :)
     */
    const numChildren = Children.count(children);
    const steps = Children.map(children, (step, index) => {
      const controlProps = {index};

      if (activeStep === index) {
        controlProps.active = true;
      } else if (linear && activeStep > index) {
        controlProps.completed = true;
      } else if (linear && activeStep < index) {
        controlProps.disabled = true;
      }

      if (index + 1 === numChildren) {
        controlProps.last = true;
      }

      return [
        index > 0 && connector,
        React.cloneElement(step, Object.assign(controlProps, step.props)),
      ];
    });

    return (

        {steps}

    );
  }
}

export default Stepper;
<commit_msg>[Stepper] Allow single Step child (#6707)<commit_after>import React, {Component, Children} from 'react';
import PropTypes from 'prop-types';
import StepConnector from './StepConnector';

const getStyles = (props) => {
  const {orientation} = props;
  return {
    root: {
      display: 'flex',
      flexDirection: orientation === 'horizontal' ? 'row' : 'column',
      alignContent: 'center',
      alignItems: orientation === 'horizontal' ? 'center' : 'stretch',
      justifyContent: 'space-between',
    },
  };
};

class Stepper extends Component {

  static propTypes = {
    /**
     * Set the active step (zero based index). This will enable `Step` control helpers.
     */
    activeStep: PropTypes.number,
    /**
     * Should be two or more `<Step />` components.
     */
    children: PropTypes.node,
    /**
     * A component to be placed between each step.
     */
    connector: PropTypes.node,
    /**
     * If set to `true`, the `Stepper` will assist in controlling steps for linear flow
     */
    linear: PropTypes.bool,
    /**
     * The stepper orientation (layout flow direction)
     */
    orientation: PropTypes.oneOf(['horizontal', 'vertical']),
    /**
     * Override the inline-style of the root element.
     */
    style: PropTypes.object,
  };

  static defaultProps = {
    connector: <StepConnector />,
    orientation: 'horizontal',
    linear: true,
  };

  static contextTypes = {muiTheme: PropTypes.object.isRequired};

  static childContextTypes = {stepper: PropTypes.object};

  getChildContext() {
    const {orientation} = this.props;
    return {stepper: {orientation}};
  }

  render() {
    const {
      activeStep,
      children,
      connector,
      linear,
      style,
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const styles = getStyles(this.props, this.context);

    /**
     * One day, we may be able to use real CSS tools
     * For now, we need to create our own "pseudo" elements
     * and nth child selectors, etc
     * That's what some of this garbage is for :)
     */
    const numChildren = Children.count(children);
    const steps = Children.map(children, (step, index) => {
      const controlProps = {index};

      if (activeStep === index) {
        controlProps.active = true;
      } else if (linear && activeStep > index) {
        controlProps.completed = true;
      } else if (linear && activeStep < index) {
        controlProps.disabled = true;
      }

      if (index + 1 === numChildren) {
        controlProps.last = true;
      }

      return [
        index > 0 && connector,
        React.cloneElement(step, Object.assign(controlProps, step.props)),
      ];
    });

    return (

        {steps}

    );
  }
}

export default Stepper;
<|endoftext|>


<commit_before>module.exports = {
  objects: {
    singularity: {
      image: [{number: 1, source: "objects/singularity.png", width: 96, x: -32, y: -32, height: 96, visible: false}],
      sync: {
        active: false
      },
      start(){
        this.changeSprite(0, {visible: true});
        this.update();
        this.sync.active = true;
      },
      onStep(delta){
        if (!this.sync.active) return;

        var dir = Math.floor(Math.random()*4);
        this.moveDir(dir, 1);

        for (var i = 0; i < 3; i++){
          for (var j = 0; j < 3; j++){
            var x = this.tx + i - 1;
            var y = this.ty + j - 1;
            var tile = this.world.cellGet(x, y);
            //this.world.cellSet(x, y, 1);
            if (["1", "2", "3", "7"].includes(tile)){
              this.world.cellSet(x, y, 5);
            }else if (["4", "6", "8"].includes(tile)){
              this.world.cellSet(x, y, 10);
            }
          }
        }
      }
    }
  }
}<commit_msg>made the singularity slower<commit_after>module.exports = {
  objects: {
    singularity: {
      image: [{number: 1, source: "objects/singularity.png", width: 96, x: -32, y: -32, height: 96, visible: false}],
      sync: {
        active: false,
        nextMoveIn: 1000
      },
      start(){
        this.changeSprite(0, {visible: true});
        this.update();
        this.sync.active = true;
      },
      onStep(delta){
        if (!this.sync.active) return;

        this.sync.nextMoveIn -= delta;
        if (this.sync.nextMoveIn <= 0){
          this.sync.nextMoveIn = 200;
          var dir = Math.floor(Math.random()*4);
          this.moveDir(dir, 1);

          for (var i = 0; i < 3; i++){
            for (var j = 0; j < 3; j++){
              var x = this.tx + i - 1;
              var y = this.ty + j - 1;
              var tile = this.world.cellGet(x, y);
              //this.world.cellSet(x, y, 1);
              if (["1", "2", "3", "7"].includes(tile)){
                this.world.cellSet(x, y, 5);
              }else if (["4", "6", "8"].includes(tile)){
                this.world.cellSet(x, y, 10);
              }
            }
          }
        }
      }
    }
  }
}<|endoftext|>


<commit_before>/* globals Map */
import * as R from "ramda";
import {webSocket} from "./WebSocketFactory.es6";
import {addBuildstepOutput, outputConnectionState, addBuildDetails, addBuildSummary} from "./Actions.es6";
import {summariesConnectionState} from "./actions/BackendActions.es6";

const CLOSED = 3;
const OPEN = 1;

const outputUrl = (baseUrl, buildId, stepId) => "ws://" + baseUrl + "/lambdaui/api/builds/" + buildId + "/" + stepId;
const detailsUrl = (baseUrl, buildId) => "ws://" +baseUrl + "/lambdaui/api/builds/" + buildId;
const summariesUrl = baseUrl => "ws://" + baseUrl + "/lambdaui/api/builds";
const triggerNewUrl = baseUrl => "http://" + baseUrl + "/lambdaui/api/triggerNew";

export class Backend {
    constructor(baseUrl) {
        this.baseUrl = baseUrl;
        this.outputUrl = R.curry(outputUrl)(baseUrl);
        this.detailsUrl = R.curry(detailsUrl)(baseUrl);
        this.detailsConnections = new Map();
        this.summariesUrl = summariesUrl(baseUrl);
    }

    _closeConnection(websocket) {

      if (websocket && websocket.readystate !== CLOSED) {
        websocket.close();
      }
    }

    _hasOpenDetailsConnection(buildId) {
      const connection = this.detailsConnections.get(buildId);
      return connection && connection.readystate === OPEN;
    }

    requestOutput(dispatch, buildId, stepId) {
      this._closeConnection(this.outputConnection);
      this.outputConnection = webSocket(this.outputUrl(buildId, stepId));
      const connection = this.outputConnection;
        /* eslint-disable */
        connection.onmessage = body => {
            const data = JSON.parse(body.data);
            const out = R.view(R.lensPath(["stepResult", "out"]))(data);
            if(out) {
                dispatch(addBuildstepOutput(buildId, stepId, data.stepResult.out.split("\n")));
            }
      };
      connection.onclose = () => dispatch(outputConnectionState("closed"));
      connection.onopen = () => dispatch(outputConnectionState("open"));
      connection.onerror = () => dispatch(outputConnectionState("error"));
    }

    requestDetails(dispatch, buildId) {
      if(this._hasOpenDetailsConnection(buildId)) {
        return;
      }

      const connection = webSocket(this.detailsUrl(buildId));
      this.detailsConnections.set(buildId, connection);

      connection.onmessage = body => {
        dispatch(addBuildDetails(buildId, JSON.parse(body.data)));
      };
    }

    closeDetailsConnection(buildId) {
      this._closeConnection(this.detailsConnections.get(buildId));
    }

    requestSummaries(dispatch) {
      const connection = webSocket(this.summariesUrl);
      connection.onclose = () => {
         dispatch(summariesConnectionState("closed"));
       };

      connection.onmessage = body =>
      {
         const data = JSON.parse(body.data);
         dispatch(addBuildSummary(data.summaries));
      };

    }

    triggerNewBuild () {
        const fetchOptions = {
            method: "POST"
        };

        fetch(triggerNewUrl(this.baseUrl), fetchOptions);
    }

}
<commit_msg>formatting<commit_after>/* globals Map */
import * as R from "ramda";
import {webSocket} from "./WebSocketFactory.es6";
import {addBuildstepOutput, outputConnectionState, addBuildDetails, addBuildSummary} from "./Actions.es6";
import {summariesConnectionState} from "./actions/BackendActions.es6";

const CLOSED = 3;
const OPEN = 1;

const outputUrl = (baseUrl, buildId, stepId) => "ws://" + baseUrl + "/lambdaui/api/builds/" + buildId + "/" + stepId;
const detailsUrl = (baseUrl, buildId) => "ws://" + baseUrl + "/lambdaui/api/builds/" + buildId;
const summariesUrl = baseUrl => "ws://" + baseUrl + "/lambdaui/api/builds";
const triggerNewUrl = baseUrl => "http://" + baseUrl + "/lambdaui/api/triggerNew";

export class Backend {
    constructor(baseUrl) {
        this.baseUrl = baseUrl;
        this.outputUrl = R.curry(outputUrl)(baseUrl);
        this.detailsUrl = R.curry(detailsUrl)(baseUrl);
        this.detailsConnections = new Map();
        this.summariesUrl = summariesUrl(baseUrl);
    }

    _closeConnection(websocket) {

        if (websocket && websocket.readystate !== CLOSED) {
            websocket.close();
        }
    }

    _hasOpenDetailsConnection(buildId) {
        const connection = this.detailsConnections.get(buildId);
        return connection && connection.readystate === OPEN;
    }

    requestOutput(dispatch, buildId, stepId) {
        this._closeConnection(this.outputConnection);
        this.outputConnection = webSocket(this.outputUrl(buildId, stepId));
        const connection = this.outputConnection;
        /* eslint-disable */
        connection.onmessage = body => {
            const data = JSON.parse(body.data);
            const out = R.view(R.lensPath(["stepResult", "out"]))(data);
            if (out) {
                dispatch(addBuildstepOutput(buildId, stepId, data.stepResult.out.split("\n")));
            }
        };
        connection.onclose = () => dispatch(outputConnectionState("closed"));
        connection.onopen = () => dispatch(outputConnectionState("open"));
        connection.onerror = () => dispatch(outputConnectionState("error"));
    }

    requestDetails(dispatch, buildId) {
        if (this._hasOpenDetailsConnection(buildId)) {
            return;
        }

        const connection = webSocket(this.detailsUrl(buildId));
        this.detailsConnections.set(buildId, connection);

        connection.onmessage = body => {
            dispatch(addBuildDetails(buildId, JSON.parse(body.data)));
        };
    }

    closeDetailsConnection(buildId) {
        this._closeConnection(this.detailsConnections.get(buildId));
    }

    requestSummaries(dispatch) {
        const connection = webSocket(this.summariesUrl);
        connection.onclose = () => {
            dispatch(summariesConnectionState("closed"));
        };

        connection.onmessage = body => {
            const data = JSON.parse(body.data);
            dispatch(addBuildSummary(data.summaries));
        };

    }

    triggerNewBuild() {
        const fetchOptions = {
            method: "POST"
        };

        fetch(triggerNewUrl(this.baseUrl), fetchOptions);
    }

}
<|endoftext|>


<commit_before>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2014 Gilles Bedel
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function displayTranscriptions(sentenceId) {
    $(
        '#sentences_group_' + sentenceId + ' .generatedTranscription'
    ).toggle();
}

$(document).ready(function() {
    var rootUrl = get_tatoeba_root_url();

    $('.editable.transcription').each(function() {
        var div = $(this);

        sentenceId = div.parent().parent().attr('data-sentence-id');
        script = div.attr('data-script');
        saveUrl = rootUrl + '/transcriptions/save/' + sentenceId + '/' + script;

        $(this).editable(saveUrl, {
            type      : 'textarea',
            cancel    : div.attr('data-cancel'),
            submit    : div.attr('data-submit'),
            id        : 'divId',
            data : function(value, settings) {
                return $('
').html(value).text() // added to correct problem with html entities
            },
            callback : function(result, settings) {
                div.parent().replaceWith(result);
            },
            indicator : '',
            tooltip   : div.attr('data-tooltip'),
            cssclass  : 'editInPlaceForm',
            onblur    : 'ignore'
        }).click(function(e) {
            $(this).find('textarea').keydown(function(event) {
                if (event.which == 13)
                    $(this).closest('form').submit();
            });
        });
    });
});
<commit_msg>Don’t loose submitted transcription on error<commit_after>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2014 Gilles Bedel
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function displayTranscriptions(sentenceId) {
    $(
        '#sentences_group_' + sentenceId + ' .generatedTranscription'
    ).toggle();
}

$(document).ready(function() {
    var rootUrl = get_tatoeba_root_url();

    $('.editable.transcription').each(function() {
        var div = $(this);
        var previousValue = {};

        sentenceId = div.parent().parent().attr('data-sentence-id');
        script = div.attr('data-script');
        saveUrl = rootUrl + '/transcriptions/save/' + sentenceId + '/' + script;

        $(this).editable(saveUrl, {
            type      : 'textarea',
            cancel    : div.attr('data-cancel'),
            submit    : div.attr('data-submit'),
            id        : 'divId',
            data : function(value, settings) {
                return $('
').html(value).text() // added to correct problem with html entities
            },
            callback : function(result, settings) {
                div.parent().replaceWith(result);
            },
            onsubmit  : function(settings, self) {
                // Save the submitted value to restore it on error
                $(self).find("textarea").each(function(idx) {
                    previousValue[idx] = $(this).val();
                });
                return true;
            },
            onerror   : function (settings, self, xhr) {
                // Go back to the previous editing state
                $(self).html(self.revert);
                self.editing = false;
                $(self).trigger(settings.event);

                // Restore the previous value
                $(self).find("textarea").each(function(idx) {
                    $(this).val(previousValue[idx]);
                });
                return false; // don't reset the form
            },
            indicator : '',
            tooltip   : div.attr('data-tooltip'),
            cssclass  : 'editInPlaceForm',
            onblur    : 'ignore'
        }).click(function(e) {
            $(this).find('textarea').keydown(function(event) {
                if (event.which == 13)
                    $(this).closest('form').submit();
            });
        });
    });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
//
// -- Zetta Polymer Library
//
//  Copyright (c) 2011-2014 ASPECTRON Inc.
//  All Rights Reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

var path 		= require('path');
var ServeStatic = require('serve-static');
var util 		= require('util');
var _ 			= require('underscore');
var fs 			= require('fs');
var crypto 		= require('crypto');
/*var jsp	= require('uglify-js').parser;
var pro	= require('uglify-js').uglify;
console.log("jsp",jsp);
console.log("pro",pro)
*/
function ZETTA_Polymer(core, options) {
	var self = this;
	options 		= options || {};
	var combiner 	= options.httpCombiner || core.httpCombiner;

	self.initHttp = function(app) {
		var depsComponetsPath = path.join(__dirname,'/bower_components/');
		var componetsPath = path.join(__dirname,'/http/zetta/');
		var scriptsPath   = path.join(__dirname,'/http/scripts/');

		if (combiner && combiner.addHttpFolders) {
			combiner.addHttpFolders([
				scriptsPath,
				componetsPath,
				componetsPath+'icons/',
				depsComponetsPath
			]);
			combiner.addHttpFolderAlias({
				deps: depsComponetsPath,
				ZETTA:componetsPath
			})
		};

		var list = fs.readdirSync(componetsPath);
		var ignoreList = ['.', '..', '.DS_Store'];
		if (_.isArray(app.get('views'))) {
			app.get('views').push(componetsPath);
		}else{
			app.set('views', [app.get('views'), componetsPath]);
		}

		_.each(list, function(file){
			if (_.contains(ignoreList, file))
				return;
			// console.log("file", file)
			app.get('/ZETTA/'+file, function(req, res, next) {
	            res.render(file, {req: req});
	        });
		});

		app.use('/deps', ServeStatic(depsComponetsPath));
		app.use('/ZETTA/scripts', ServeStatic(scriptsPath));
	    app.use('/ZETTA', ServeStatic(componetsPath));
	}
}

module.exports = ZETTA_Polymer;
<commit_msg>ZETTA/scripts folder alias added to combiner<commit_after>#!/usr/bin/env node
//
// -- Zetta Polymer Library
//
//  Copyright (c) 2011-2014 ASPECTRON Inc.
//  All Rights Reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

var path 		= require('path');
var ServeStatic = require('serve-static');
var util 		= require('util');
var _ 			= require('underscore');
var fs 			= require('fs');
var crypto 		= require('crypto');
/*var jsp	= require('uglify-js').parser;
var pro	= require('uglify-js').uglify;
console.log("jsp",jsp);
console.log("pro",pro)
*/
function ZETTA_Polymer(core, options) {
	var self = this;
	options 		= options || {};
	var combiner 	= options.httpCombiner || core.httpCombiner;

	self.initHttp = function(app) {
		var depsComponetsPath = path.join(__dirname,'/bower_components/');
		var componetsPath = path.join(__dirname,'/http/zetta/');
		var scriptsPath   = path.join(__dirname,'/http/scripts/');

		if (combiner && combiner.addHttpFolders) {
			combiner.addHttpFolders([
				scriptsPath,
				componetsPath,
				componetsPath+'icons/',
				depsComponetsPath
			]);
			combiner.addHttpFolderAlias({
				deps: depsComponetsPath,
				ZETTA:componetsPath,
				'ZETTA/scripts': scriptsPath
			})
		};

		var list = fs.readdirSync(componetsPath);
		var ignoreList = ['.', '..', '.DS_Store'];
		if (_.isArray(app.get('views'))) {
			app.get('views').push(componetsPath);
		}else{
			app.set('views', [app.get('views'), componetsPath]);
		}

		_.each(list, function(file){
			if (_.contains(ignoreList, file))
				return;
			// console.log("file", file)
			app.get('/ZETTA/'+file, function(req, res, next) {
	            res.render(file, {req: req});
	        });
		});

		app.use('/deps', ServeStatic(depsComponetsPath));
		app.use('/ZETTA/scripts', ServeStatic(scriptsPath));
	    app.use('/ZETTA', ServeStatic(componetsPath));
	}
}

module.exports = ZETTA_Polymer;
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import {Redirect, Route, Switch} from 'react-router-dom'
import Users from "./users/Users";
import GroupRoutes from "./groups/GroupRoutes";
import MainMenu from "./MainMenu";
import Home from "./Home";
import Folders from "./folders/Folders";

class MainContainer extends Component {
    render() {
        return (

                <MainMenu/>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/users" component={Users}/>
                    <Route path="/groups" component={GroupRoutes}/>
                    <Route path="/folders" component={Folders}/>
                    <Redirect to="/"/>
                </Switch>

        );
    }
}

export default MainContainer;<commit_msg>Revert "renamed component to better reflect its responsibility"<commit_after>import React, {Component} from 'react'
import {Redirect, Route, Switch} from 'react-router-dom'
import Users from "./users/Users";
import Groups from "./groups/Groups";
import MainMenu from "./MainMenu";
import Home from "./Home";
import Folders from "./folders/Folders";

class MainContainer extends Component {
    render() {
        return (

                <MainMenu/>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/users" component={Users}/>
                    <Route path="/groups" component={Groups}/>
                    <Route path="/folders" component={Folders}/>
                    <Redirect to="/"/>
                </Switch>

        );
    }
}

export default MainContainer;<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  generic pattern for model management  */
$cs.pattern.model = $cs.trait({
    protos: {
        /*  define model  */
        model: function () {
            /*  determine parameters  */
            var params = $cs.params("model", arguments, {
                model: { pos: 0, def: null }
            });

            /*  simplify further processing  */
            var model = params.model;
            if (model === null)
                model = undefined;

            /*  sanity check model  */
            var name;
            if (_cs.isdefined(model)) {
                for (name in model) {
                    if (typeof model[name].value === "undefined")
                        model[name].value = "";
                    if (typeof model[name].valid === "undefined")
                        model[name].valid = "string";
                    if (typeof model[name].autoreset === "undefined")
                        model[name].autoreset = false;
                    if (typeof model[name].store === "undefined")
                        model[name].store = false;
                    for (var key in model[name]) {
                        if (key !== "value" && key !== "valid" && key !== "autoreset" && key !== "store")
                            throw _cs.exception("model", "invalid specification key \"" +
                                key + "\" in specification of model field \"" + name + "\"");
                    }
                    if (!$cs.validate(model[name].value, model[name].valid))
                        throw _cs.exception("model", "model field \"" + name + "\" has " +
                            "default value " + _cs.json(model[name].value) + ", which does not validate " +
                            "against validation \"" + model[name].valid + "\"");
                }
            }

            /*  try to load stored model values  */
            var store = this.store("model");
            if (store !== null) {
                if (_cs.isdefined(model)) {
                    for (name in model) {
                        if (model[name].store) {
                            if (_cs.isdefined(store[name]))
                                model[name].value = store[name];
                        }
                    }
                }
            }

            /*  retrieve old model  */
            var model_old = this.property({ name: "ComponentJS:model", bubbling: false });

            /*  store model  */
            if (_cs.isdefined(model)) {
                if (_cs.isdefined(model_old)) {
                    /*  merge model into existing one  */
                    var model_new = {};
                    _cs.extend(model_new, model_old);
                    _cs.extend(model_new, model);
                    this.property("ComponentJS:model", model_new);
                    model = model_new;
                }
                else {
                    /*  set initial model  */
                    this.property("ComponentJS:model", model);
                }

                /*  optionally save stored model values  */
                store = {};
                var save = false;
                for (name in model) {
                    if (model[name].store) {
                        store[name] = model[name].value;
                        save = true;
                    }
                }
                if (save)
                    this.store("model", store);
            }

            /*  return old model  */
            return model_old;
        },

        /*  get/set model value  */
        value: function () {
            /*  determine parameters  */
            var params = $cs.params("value", arguments, {
                name:        { pos: 0, req: true      },
                value:       { pos: 1, def: undefined },
                force:       { pos: 2, def: false     },
                returnowner: {         def: false     }
            });

            /*  determine component owning model with requested value  */
            var owner = null;
            var model = null;
            var comp = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("value", "no model found containing value \"" + params.name + "\"");
                model = owner.property("ComponentJS:model");
                if (_cs.isdefined(model[params.name]))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("value", "no model found containing value \"" + params.name + "\"");

            /*  get new model value  */
            var value_new = params.value;

            /*  get old model value  */
            var ev;
            var value_old = model[params.name].value;
            var result;
            if (typeof value_new === "undefined") {
                if (owner.property({ name: "ComponentJS:model:subscribers:get", bubbling: false }) === true) {
                    /*  send event to observers for value get and allow observers
                        to reject value get operation and/or change old value to get  */
                    ev = owner.publish({
                        name:      "ComponentJS:model:" + params.name + ":get",
                        args:      [ value_old ],
                        capturing: false,
                        spreading: false,
                        bubbling:  false,
                        async:     false
                    });
                    if (ev.processing()) {
                        /*  re-fetch value from model
                            (in case the callback set a new value directly)  */
                        value_old = model[params.name].value;

                        /*  allow value to be overridden by event result  */
                        result = ev.result();
                        if (typeof result !== "undefined")
                            value_old = result;
                    }
                }
            }

            /*  optionally set new model value  */
            if (   typeof value_new !== "undefined"
                && (params.force || value_old !== value_new)) {

                /*  check validity of new value  */
                if (!$cs.validate(value_new, model[params.name].valid))
                    throw _cs.exception("value", "invalid value \"" + value_new +
                        "\" for model field \"" + params.name + "\"");

                /*  send event to observers for value set operation and allow observers
                    to reject value set operation and/or change new value to set  */
                var cont = true;
                if (owner.property({ name: "ComponentJS:model:subscribers:set", bubbling: false }) === true) {
                    ev = owner.publish({
                        name:      "ComponentJS:model:" + params.name + ":set",
                        args:      [ value_new, value_old ],
                        capturing: false,
                        spreading: false,
                        bubbling:  false,
                        async:     false
                    });
                    if (!ev.processing())
                        cont = false;
                    else {
                        /*  allow value to be overridden  */
                        result = ev.result();
                        if (typeof result !== "undefined")
                            value_new = result;
                    }
                }
                if (cont && !model[params.name].autoreset) {
                    /*  set value in model  */
                    model[params.name].value = value_new;

                    /*  synchronize model with underlying store  */
                    if (model[params.name].store) {
                        var store = owner.store("model");
                        store[params.name] = model[params.name].value;
                        owner.store("model", store);
                    }

                    /*  send event to observers after value finally changed  */
                    if (owner.property({ name: "ComponentJS:model:subscribers:changed", bubbling: false }) === true) {
                        owner.publish({
                            name:      "ComponentJS:model:" + params.name + ":changed",
                            args:      [ value_new, value_old ],
                            noresult:  true,
                            capturing: false,
                            spreading: false,
                            bubbling:  false,
                            async:     true
                        });
                    }
                }
            }

            /*  return old model value  */
            return (params.returnowner ? owner : value_old);
        },

        /*  touch a model value and trigger event  */
        touch: function () {
            /*  determine parameters  */
            var params = $cs.params("touch", arguments, {
                name: { pos: 0, req: true }
            });

            /*  simply force value to same value in order to trigger event  */
            this.value({
                name: params.name,
                value: this.value(params.name),
                force: true
            });
        },

        /*  start observing model value change  */
        observe: function () {
            /*  determine parameters  */
            var params = $cs.params("observe", arguments, {
                name:      { pos: 0, req: true  },
                func:      { pos: 1, req: true  },
                touch:     {         def: false },
                operation: {         def: "set" },
                spool:     {         def: null  }
            });

            /*  determine the actual component owning the model
                as we want to subscribe the change event there only  */
            var owner = null;
            var model = null;
            var comp = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("observe", "no model found containing value \"" + params.name + "\"");
                model = owner.property("ComponentJS:model");
                if (_cs.isdefined(model[params.name]))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("observe", "no model found containing value \"" + params.name + "\"");

            /*  subscribe to model value change event  */
            var id = owner.subscribe({
                name:      "ComponentJS:model:" + params.name + ":" + params.operation,
                capturing: false,
                spreading: false,
                bubbling:  false,
                func:      params.func
            });

            /*  mark component for having subscribers of operation
                (for performance optimization reasons)  */
            owner.property("ComponentJS:model:subscribers:" + params.operation, true);

            /*  optionally spool reverse operation  */
            if (params.spool !== null) {
                var info = _cs.spool_spec_parse(this, params.spool);
                info.comp.spool(info.name, this, "unobserve", id);
            }

            /*  if requested, touch the model value once (for an initial observer run)  */
            if (params.touch)
                this.touch(params.name);

            return id;
        },

        /*  stop observing model value change  */
        unobserve: function () {
            /*  determine parameters  */
            var params = $cs.params("unobserve", arguments, {
                id: { pos: 0, req: true }
            });

            /*  determine the actual component owning the model
                as we want to unsubscribe the change event there only  */
            var owner = null;
            var comp = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("unobserve", "no model subscription found");
                if (owner.subscription(params.id))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("unobserve", "no model subscription found");

            /*  subscribe to model value change event  */
            owner.unsubscribe(params.id);
        }
    }
});

<commit_msg>once again: use JSON encoding in error message to make it more clear what the value actually is (as [] would be displayed as an empty string because of its .toString() method)<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  generic pattern for model management  */
$cs.pattern.model = $cs.trait({
    protos: {
        /*  define model  */
        model: function () {
            /*  determine parameters  */
            var params = $cs.params("model", arguments, {
                model: { pos: 0, def: null }
            });

            /*  simplify further processing  */
            var model = params.model;
            if (model === null)
                model = undefined;

            /*  sanity check model  */
            var name;
            if (_cs.isdefined(model)) {
                for (name in model) {
                    if (typeof model[name].value === "undefined")
                        model[name].value = "";
                    if (typeof model[name].valid === "undefined")
                        model[name].valid = "string";
                    if (typeof model[name].autoreset === "undefined")
                        model[name].autoreset = false;
                    if (typeof model[name].store === "undefined")
                        model[name].store = false;
                    for (var key in model[name]) {
                        if (key !== "value" && key !== "valid" && key !== "autoreset" && key !== "store")
                            throw _cs.exception("model", "invalid specification key \"" +
                                key + "\" in specification of model field \"" + name + "\"");
                    }
                    if (!$cs.validate(model[name].value, model[name].valid))
                        throw _cs.exception("model", "model field \"" + name + "\" has " +
                            "default value " + _cs.json(model[name].value) + ", which does not validate " +
                            "against validation \"" + model[name].valid + "\"");
                }
            }

            /*  try to load stored model values  */
            var store = this.store("model");
            if (store !== null) {
                if (_cs.isdefined(model)) {
                    for (name in model) {
                        if (model[name].store) {
                            if (_cs.isdefined(store[name]))
                                model[name].value = store[name];
                        }
                    }
                }
            }

            /*  retrieve old model  */
            var model_old = this.property({ name: "ComponentJS:model", bubbling: false });

            /*  store model  */
            if (_cs.isdefined(model)) {
                if (_cs.isdefined(model_old)) {
                    /*  merge model into existing one  */
                    var model_new = {};
                    _cs.extend(model_new, model_old);
                    _cs.extend(model_new, model);
                    this.property("ComponentJS:model", model_new);
                    model = model_new;
                }
                else {
                    /*  set initial model  */
                    this.property("ComponentJS:model", model);
                }

                /*  optionally save stored model values  */
                store = {};
                var save = false;
                for (name in model) {
                    if (model[name].store) {
                        store[name] = model[name].value;
                        save = true;
                    }
                }
                if (save)
                    this.store("model", store);
            }

            /*  return old model  */
            return model_old;
        },

        /*  get/set model value  */
        value: function () {
            /*  determine parameters  */
            var params = $cs.params("value", arguments, {
                name:        { pos: 0, req: true      },
                value:       { pos: 1, def: undefined },
                force:       { pos: 2, def: false     },
                returnowner: {         def: false     }
            });

            /*  determine component owning model with requested value  */
            var owner = null;
            var model = null;
            var comp = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("value", "no model found containing value \"" + params.name + "\"");
                model = owner.property("ComponentJS:model");
                if (_cs.isdefined(model[params.name]))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("value", "no model found containing value \"" + params.name + "\"");

            /*  get new model value  */
            var value_new = params.value;

            /*  get old model value  */
            var ev;
            var value_old = model[params.name].value;
            var result;
            if (typeof value_new === "undefined") {
                if (owner.property({ name: "ComponentJS:model:subscribers:get", bubbling: false }) === true) {
                    /*  send event to observers for value get and allow observers
                        to reject value get operation and/or change old value to get  */
                    ev = owner.publish({
                        name:      "ComponentJS:model:" + params.name + ":get",
                        args:      [ value_old ],
                        capturing: false,
                        spreading: false,
                        bubbling:  false,
                        async:     false
                    });
                    if (ev.processing()) {
                        /*  re-fetch value from model
                            (in case the callback set a new value directly)  */
                        value_old = model[params.name].value;

                        /*  allow value to be overridden by event result  */
                        result = ev.result();
                        if (typeof result !== "undefined")
                            value_old = result;
                    }
                }
            }

            /*  optionally set new model value  */
            if (   typeof value_new !== "undefined"
                && (params.force || value_old !== value_new)) {

                /*  check validity of new value  */
                if (!$cs.validate(value_new, model[params.name].valid))
                    throw _cs.exception("value", "model field \"" + params.name + "\" receives " +
                        "new value " + _cs.json(value_new) + ", which does not validate " +
                        "against validation \"" + model[params.name].valid + "\"");

                /*  send event to observers for value set operation and allow observers
                    to reject value set operation and/or change new value to set  */
                var cont = true;
                if (owner.property({ name: "ComponentJS:model:subscribers:set", bubbling: false }) === true) {
                    ev = owner.publish({
                        name:      "ComponentJS:model:" + params.name + ":set",
                        args:      [ value_new, value_old ],
                        capturing: false,
                        spreading: false,
                        bubbling:  false,
                        async:     false
                    });
                    if (!ev.processing())
                        cont = false;
                    else {
                        /*  allow value to be overridden  */
                        result = ev.result();
                        if (typeof result !== "undefined")
                            value_new = result;
                    }
                }
                if (cont && !model[params.name].autoreset) {
                    /*  set value in model  */
                    model[params.name].value = value_new;

                    /*  synchronize model with underlying store  */
                    if (model[params.name].store) {
                        var store = owner.store("model");
                        store[params.name] = model[params.name].value;
                        owner.store("model", store);
                    }

                    /*  send event to observers after value finally changed  */
                    if (owner.property({ name: "ComponentJS:model:subscribers:changed", bubbling: false }) === true) {
                        owner.publish({
                            name:      "ComponentJS:model:" + params.name + ":changed",
                            args:      [ value_new, value_old ],
                            noresult:  true,
                            capturing: false,
                            spreading: false,
                            bubbling:  false,
                            async:     true
                        });
                    }
                }
            }

            /*  return old model value  */
            return (params.returnowner ? owner : value_old);
        },

        /*  touch a model value and trigger event  */
        touch: function () {
            /*  determine parameters  */
            var params = $cs.params("touch", arguments, {
                name: { pos: 0, req: true }
            });

            /*  simply force value to same value in order to trigger event  */
            this.value({
                name: params.name,
                value: this.value(params.name),
                force: true
            });
        },

        /*  start observing model value change  */
        observe: function () {
            /*  determine parameters  */
            var params = $cs.params("observe", arguments, {
                name:      { pos: 0, req: true  },
                func:      { pos: 1, req: true  },
                touch:     {         def: false },
                operation: {         def: "set" },
                spool:     {         def: null  }
            });

            /*  determine the actual component owning the model
                as we want to subscribe the change event there only  */
            var owner = null;
            var model = null;
            var comp = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("observe", "no model found containing value \"" + params.name + "\"");
                model = owner.property("ComponentJS:model");
                if (_cs.isdefined(model[params.name]))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("observe", "no model found containing value \"" + params.name + "\"");

            /*  subscribe to model value change event  */
            var id = owner.subscribe({
                name:      "ComponentJS:model:" + params.name + ":" + params.operation,
                capturing: false,
                spreading: false,
                bubbling:  false,
                func:      params.func
            });

            /*  mark component for having subscribers of operation
                (for performance optimization reasons)  */
            owner.property("ComponentJS:model:subscribers:" + params.operation, true);

            /*  optionally spool reverse operation  */
            if (params.spool !== null) {
                var info = _cs.spool_spec_parse(this, params.spool);
                info.comp.spool(info.name, this, "unobserve", id);
            }

            /*  if requested, touch the model value once (for an initial observer run)  */
            if (params.touch)
                this.touch(params.name);

            return id;
        },

        /*  stop observing model value change  */
        unobserve: function () {
            /*  determine parameters  */
            var params = $cs.params("unobserve", arguments, {
                id: { pos: 0, req: true }
            });

            /*  determine the actual component owning the model
                as we want to unsubscribe the change event there only  */
            var owner = null;
            var comp = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("unobserve", "no model subscription found");
                if (owner.subscription(params.id))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("unobserve", "no model subscription found");

            /*  subscribe to model value change event  */
            owner.unsubscribe(params.id);
        }
    }
});

<|endoftext|>


<commit_before>import React from 'react';
import { NavLink } from 'fluxible-router';

class Footer extends React.Component {
    render() {
        return (

About

                  <NavLink className="item" routeName="about" href="/about">About Us</NavLink>
                  <NavLink className="item" routeName="about" href="/about">Contact Us</NavLink>

Terms & Conditions

                  <NavLink className="item" routeName="license" href="/license">License</NavLink>
                  <NavLink className="item" routeName="imprint" href="/imprint">Imprint</NavLink>
                  <NavLink className="item" routeName="dataprotection" href="/dataprotection">Data Protection Conditions</NavLink>

Copyright © 2017 · All Rights Reserved

Build GIT_COMMIT@GIT_BRANCH

        );
    }
}

export default Footer;
<commit_msg>induce build: added github link to footer<commit_after>import React from 'react';
import { NavLink } from 'fluxible-router';

class Footer extends React.Component {
    render() {
        return (

About

                  <NavLink className="item" routeName="about" href="/about">About Us</NavLink>
                  <NavLink className="item" routeName="about" href="/about">Contact Us</NavLink>
                  Github

Terms & Conditions

                  <NavLink className="item" routeName="license" href="/license">License</NavLink>
                  <NavLink className="item" routeName="imprint" href="/imprint">Imprint</NavLink>
                  <NavLink className="item" routeName="dataprotection" href="/dataprotection">Data Protection Conditions</NavLink>

Copyright © 2017 · All Rights Reserved

Build GIT_COMMIT@GIT_BRANCH

        );
    }
}

export default Footer;
<|endoftext|>


<commit_before>window.a_value = 42;
alert('hey tere');
<commit_msg>Remove stray alert.<commit_after>window.a_value = 42;
<|endoftext|>


<commit_before>/**
 * Promisify Firebase methods.
 */

goog.provide('onfire.utils.firebase');
goog.provide('onfire.utils.firebase.EventType');

goog.require('onfire.utils.promise');
goog.require('onfire.utils.detection');

if (onfire.utils.detection.IS_NODEJS) {
    /**
     * @private
     */
    onfire.utils.Firebase_ = /** @type {!function(new:Firebase, string)} */(require('firebase'));
} else {
    onfire.utils.Firebase_ = Firebase;
}

/**
 * Create a Firebase ref in a way that won't generate Closure Compiler errors.
 *
 * @param {string} path
 * @return {!Firebase}
 */
onfire.utils.firebase.newFirebase = function(path) {

    if (onfire.utils.detection.IS_NODEJS) {
        var fb = onfire.utils.Firebase_;
        return new fb(path);
    } else {
        return new Firebase(path);
    }
};

/**
 * Push a value under a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {Firebase.Value=} opt_value
 * @return {!Promise<!Firebase,!Error>|!goog.Promise<!Firebase,!Error>}
 */
onfire.utils.firebase.push = function(ref, opt_value) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        if (goog.isDef(opt_value)) {
            var childRef = ref.push(opt_value, function(err) {
                !err ? resolve(childRef) : reject(err);
            });
        } else {
            // Nothing to put there - just return the autogenerated ID.
            resolve(ref.push());
        }
    });
};

/**
 * Set the value at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {Firebase.Value} value
 * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>}
 */
onfire.utils.firebase.set = function(ref, value) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.set(value, function(err) {
            !err ? resolve() : reject(err);
        });
    });
};

/**
 * Set the value at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {!Object<string,Firebase.Value>} values
 * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>}
 */
onfire.utils.firebase.update = function(ref, values) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.update(values, function(err) {
            !err ? resolve() : reject(err);
        });
    });
};

/**
 * Performs an atomic transaction at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {function(Firebase.Value):(Firebase.Value|undefined)} updateFn
 * @return
    {
        !Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error>
        |
        !goog.Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error>
    }
 */
onfire.utils.firebase.transaction = function(ref, updateFn) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.transaction(updateFn, function(err, isCommitted, snapshot) {
            !err ? resolve({'isCommitted': isCommitted, 'snapshot': snapshot}) : reject(err);
        }, false);
    });
};

/**
 * Set the value at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>}
 */
onfire.utils.firebase.remove = function(ref) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.remove(function(err) {
            !err ? resolve() : reject(err);
        });
    });
};

/**
 * Wait for the first event of a specified type at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {onfire.utils.firebase.EventType} eventType
 * @return {!Promise<!Firebase.DataSnapshot,!Error>|!goog.Promise<!Firebase.DataSnapshot,!Error>}
 */
onfire.utils.firebase.once = function(ref, eventType) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.once(eventType, function(snapshot) {
            resolve(snapshot);
        }, function(err) {
            reject(err);
        });
    });
};

/**
 * @enum {string}
 */
onfire.utils.firebase.EventType = {
    VALUE: 'value',
    CHILD_ADDED: 'child_added',
    CHILD_CHANGED: 'child_changed',
    CHILD_REMOVED: 'child_removed',
    CHILD_MOVED: 'child_moved'
};

onfire.utils.firebase.TIMESTAMP = onfire.utils.Firebase_.ServerValue.TIMESTAMP;
<commit_msg>Add callback annotations<commit_after>/**
 * Promisify Firebase methods.
 */

goog.provide('onfire.utils.firebase');
goog.provide('onfire.utils.firebase.EventType');

goog.require('onfire.utils.promise');
goog.require('onfire.utils.detection');

if (onfire.utils.detection.IS_NODEJS) {
    /**
     * @private
     */
    onfire.utils.Firebase_ = /** @type {!function(new:Firebase, string)} */(require('firebase'));
} else {
    onfire.utils.Firebase_ = Firebase;
}

/**
 * Create a Firebase ref in a way that won't generate Closure Compiler errors.
 *
 * @param {string} path
 * @return {!Firebase}
 */
onfire.utils.firebase.newFirebase = function(path) {

    if (onfire.utils.detection.IS_NODEJS) {
        var fb = onfire.utils.Firebase_;
        return new fb(path);
    } else {
        return new Firebase(path);
    }
};

/**
 * Push a value under a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {Firebase.Value=} opt_value
 * @return {!Promise<!Firebase,!Error>|!goog.Promise<!Firebase,!Error>}
 */
onfire.utils.firebase.push = function(ref, opt_value) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        if (goog.isDef(opt_value)) {
            var childRef = ref.push(opt_value, function(/** Error */err) {
                !err ? resolve(childRef) : reject(err);
            });
        } else {
            // Nothing to put there - just return the autogenerated ID.
            resolve(ref.push());
        }
    });
};

/**
 * Set the value at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {Firebase.Value} value
 * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>}
 */
onfire.utils.firebase.set = function(ref, value) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.set(value, function(/** Error */err) {
            !err ? resolve() : reject(err);
        });
    });
};

/**
 * Set the value at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {!Object<string,Firebase.Value>} values
 * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>}
 */
onfire.utils.firebase.update = function(ref, values) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.update(values, function(/** Error */err) {
            !err ? resolve() : reject(err);
        });
    });
};

/**
 * Performs an atomic transaction at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {function(Firebase.Value):(Firebase.Value|undefined)} updateFn
 * @return
    {
        !Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error>
        |
        !goog.Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error>
    }
 */
onfire.utils.firebase.transaction = function(ref, updateFn) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.transaction(updateFn,
            function(/**Error*/err, /**boolean*/isCommitted, /**!Firebase.DataSnapshot*/snapshot) {
                !err ? resolve({'isCommitted': isCommitted, 'snapshot': snapshot}) : reject(err);
            }, false);
    });
};

/**
 * Set the value at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>}
 */
onfire.utils.firebase.remove = function(ref) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.remove(function(/** Error */err) {
            !err ? resolve() : reject(err);
        });
    });
};

/**
 * Wait for the first event of a specified type at a Firebase reference.
 *
 * @param {!Firebase} ref
 * @param {onfire.utils.firebase.EventType} eventType
 * @return {!Promise<!Firebase.DataSnapshot,!Error>|!goog.Promise<!Firebase.DataSnapshot,!Error>}
 */
onfire.utils.firebase.once = function(ref, eventType) {
    return onfire.utils.promise.newPromise(function(resolve, reject) {
        ref.once(eventType, function(/** !Firebase.DataSnapshot */snapshot) {
            resolve(snapshot);
        }, function(err) {
            reject(err);
        });
    });
};

/**
 * @enum {string}
 */
onfire.utils.firebase.EventType = {
    VALUE: 'value',
    CHILD_ADDED: 'child_added',
    CHILD_CHANGED: 'child_changed',
    CHILD_REMOVED: 'child_removed',
    CHILD_MOVED: 'child_moved'
};

onfire.utils.firebase.TIMESTAMP = onfire.utils.Firebase_.ServerValue.TIMESTAMP;
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import s from './styles'

class TimelineEvent extends Component {

  eventNotificationStyle () {
    const {iconColor} = this.props
    if (iconColor) {
      return {...s.eventType, ...{color: iconColor, borderColor: iconColor}}
    } else {
      return s.eventType
    }
  }

  contentStyle () {
    const {contentStyle} = this.props
    if (contentStyle) {
      return {...s.message, ...contentStyle}
    } else {
      return s.message
    }
  }

  render () {
    return

        {this.props.icon}

{this.props.createdAt}

{this.props.title}

{this.props.buttons}

          {this.props.children}

  }

}

TimelineEvent.propTypes = {
  children: React.PropTypes.node.isRequired,
  title: React.PropTypes.string.isRequired,
  createdAt: React.PropTypes.string.isRequired,
  buttons: React.PropTypes.node,
  icon: React.PropTypes.node,
  iconColor: React.PropTypes.string,
  contentStyle:  React.PropTypes.object
}

export default TimelineEvent
<commit_msg>fix(): Make jslint happy<commit_after>import React, {Component} from 'react'
import s from './styles'

class TimelineEvent extends Component {

  eventNotificationStyle () {
    const {iconColor} = this.props
    if (iconColor) {
      return {...s.eventType, ...{color: iconColor, borderColor: iconColor}}
    } else {
      return s.eventType
    }
  }

  contentStyle () {
    const {contentStyle} = this.props
    if (contentStyle) {
      return {...s.message, ...contentStyle}
    } else {
      return s.message
    }
  }

  render () {
    return

        {this.props.icon}

{this.props.createdAt}

{this.props.title}

{this.props.buttons}

          {this.props.children}

  }

}

TimelineEvent.propTypes = {
  children: React.PropTypes.node.isRequired,
  title: React.PropTypes.string.isRequired,
  createdAt: React.PropTypes.string.isRequired,
  buttons: React.PropTypes.node,
  icon: React.PropTypes.node,
  iconColor: React.PropTypes.string,
  contentStyle: React.PropTypes.object
}

export default TimelineEvent
<|endoftext|>


<commit_before>// @flow
import { Map, fromJS } from 'immutable';
import { filter, sumBy, round } from 'lodash';

export default (data: Map<string, *>): Map<string, *> => {
  const sorted = data.map(person => {
    const personAmounts =
      filter(person.get('amount').split(' '), amount => parseFloat(amount));
    return Map({
      id: person.get('id'),
      name: person.get('name'),
      amount: round(sumBy(personAmounts, amount => Number(amount)), 2)
    });
  }).sortBy(person => person.get('amount')).reverse();

  const totalAmount = sorted.reduce((total, person) => total + person.get('amount'), 0);
  const share = round((totalAmount / sorted.size), 2);

  let payments = Map({});
  let paymentsLeft = Map({});

  sorted.forEach(person => {
    const source = person.get('id');
    paymentsLeft = paymentsLeft.set(source, round(share - person.get('amount'), 2));

    while (paymentsLeft.get(source) > 0) {
      if (!payments.get(source)) {
        payments = payments.set(source, fromJS({
          from: person.get('name'),
          to: []
        }));
      }

      const target = paymentsLeft.findKey(p => p < 0);
      if (target) {
        const amount = Math.abs(paymentsLeft.get(target, 0)) > paymentsLeft.get(source, 0)
          ? paymentsLeft.get(source)
          : Math.abs(paymentsLeft.get(target));

        paymentsLeft = paymentsLeft
          .update(target, value => value + amount)
          .update(source, value => value - amount);

        payments = payments.updateIn([source, 'to'], to => to.push(
          fromJS({
            name: sorted.getIn([target, 'name']),
            amount
          })
        ));
      } else {
        paymentsLeft = paymentsLeft.set(source, 0);
      }
    }
  });

  return Map({
    payments,
    totalAmount,
    share
  });
};
<commit_msg>Round total.<commit_after>// @flow
import { Map, fromJS } from 'immutable';
import { filter, sumBy, round } from 'lodash';

export default (data: Map<string, *>): Map<string, *> => {
  const sorted = data.map(person => {
    const personAmounts =
      filter(person.get('amount').split(' '), amount => parseFloat(amount));
    return Map({
      id: person.get('id'),
      name: person.get('name'),
      amount: round(sumBy(personAmounts, amount => Number(amount)), 2)
    });
  }).sortBy(person => person.get('amount')).reverse();

  const totalAmount = round(sorted.reduce((total, person) => total + person.get('amount'), 0), 2);
  const share = round((totalAmount / sorted.size), 2);

  let payments = Map({});
  let paymentsLeft = Map({});

  sorted.forEach(person => {
    const source = person.get('id');
    paymentsLeft = paymentsLeft.set(source, round(share - person.get('amount'), 2));

    while (paymentsLeft.get(source) > 0) {
      if (!payments.get(source)) {
        payments = payments.set(source, fromJS({
          from: person.get('name'),
          to: []
        }));
      }

      const target = paymentsLeft.findKey(p => p < 0);
      if (target) {
        const amount = Math.abs(paymentsLeft.get(target, 0)) > paymentsLeft.get(source, 0)
          ? paymentsLeft.get(source)
          : Math.abs(paymentsLeft.get(target));

        paymentsLeft = paymentsLeft
          .update(target, value => value + amount)
          .update(source, value => value - amount);

        payments = payments.updateIn([source, 'to'], to => to.push(
          fromJS({
            name: sorted.getIn([target, 'name']),
            amount
          })
        ));
      } else {
        paymentsLeft = paymentsLeft.set(source, 0);
      }
    }
  });

  return Map({
    payments,
    totalAmount,
    share
  });
};
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Island from '../island';
import Section from '../section';
import { IconButton } from '../button';
import cx from 'classnames';
import theme from './theme.css';
import { IconCloseMediumOutline } from '@teamleader/ui-icons';

class Banner extends PureComponent {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    color: PropTypes.oneOf(['white', 'neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua']),
    icon: PropTypes.element,
    onClose: PropTypes.function,
    fullWidth: PropTypes.bool,
  };

  static defaultProps = {
    color: 'white',
  };

  constructor() {
    super(...arguments);
    this.handleOnClick = ::this.handleOnClick;
  }

  handleOnClick() {
    this.props.onClose();
  }

  getCloseButtonColor() {
    const { color } = this.props;

    if (color === 'white') {
      return 'neutral';
    }

    return color;
  }

  render() {
    const { children, className, color, icon, onClose, fullWidth, ...others } = this.props;

    const classNames = cx(theme[color], className);
    const Element = fullWidth ? Section : Island;

    return (
      <Element data-teamleader-ui="banner" color={color} className={classNames} {...others}>

          {icon && {icon}}
          {children}
          {onClose && (
            <IconButton
              className={theme['close-button']}
              icon={<IconCloseMediumOutline />}
              color={this.getCloseButtonColor()}
              onClick={this.handleOnClick}
            />
          )}

      </Element>
    );
  }
}

export default Banner;
<commit_msg>renamed handleOnClick to handleClick<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Island from '../island';
import Section from '../section';
import { IconButton } from '../button';
import cx from 'classnames';
import theme from './theme.css';
import { IconCloseMediumOutline } from '@teamleader/ui-icons';

class Banner extends PureComponent {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    color: PropTypes.oneOf(['white', 'neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua']),
    icon: PropTypes.element,
    onClose: PropTypes.function,
    fullWidth: PropTypes.bool,
  };

  static defaultProps = {
    color: 'white',
  };

  constructor() {
    super(...arguments);
    this.handleClick = ::this.handleClick;
  }

  handleClick() {
    this.props.onClose();
  }

  getCloseButtonColor() {
    const { color } = this.props;

    if (color === 'white') {
      return 'neutral';
    }

    return color;
  }

  render() {
    const { children, className, color, icon, onClose, fullWidth, ...others } = this.props;

    const classNames = cx(theme[color], className);
    const Element = fullWidth ? Section : Island;

    return (
      <Element data-teamleader-ui="banner" color={color} className={classNames} {...others}>

          {icon && {icon}}
          {children}
          {onClose && (
            <IconButton
              className={theme['close-button']}
              icon={<IconCloseMediumOutline />}
              color={this.getCloseButtonColor()}
              onClick={this.handleClick}
            />
          )}

      </Element>
    );
  }
}

export default Banner;
<|endoftext|>