<commit_before>//---
var FOR_READING = 1,
    FOR_WRITING = 2,
    FOR_APPENDING = 8;
var TRISTATE_USE_DEFAULT = -2,
    TRISTATE_TRUE = -1,
    TRISTATE_FALSE = 0;
var _sed = {
    parse: function(name){
        var pattern = /^(.*)(\.[0-9a-fA-F]{40})(\.[a-zA-Z0-9]+)?$/g;
        var matcher = null;

        pattern.lastIndex = 0;

        if(null != (matcher = pattern.exec(name))){
            return {
                "source": matcher[0],
                "prefix": matcher[1],
                "sign": matcher[2],
                "ext": matcher[3],
                "target": matcher[1] + matcher[2]
            }
        }

        return null;
    },
    escape: function(str){
        str = str.replace(/\./g, "\\.");
        str = str.replace(/\-/g, "\\-");
        str = str.replace(/\//g, "\\/");

        return str;
    },
    read : function(pathname, charset){
        var stream = new ActiveXObject("ADODB.Stream");
        var content = "";

        stream.type = 2;
        stream.mode = 3;
        stream.charset = charset;
        stream.open();
        stream.loadFromFile(pathname);

        content = stream.readText;

        stream.close();
        stream = null;

        return content;
    },
    write : function(pathname, content, charset){
        var stream = new ActiveXObject("ADODB.Stream");
        var bom = null;

        stream.type = 2;
        stream.mode = 3;
        stream.charset = charset;
        stream.open();
        stream.writeText(content);

        if("utf-8" == charset){
            //BOM
            bom = new ActiveXObject("ADODB.Stream");
            stream.position = 3;
            bom.type = 1;
            bom.mode = 3;
            bom.open();
            stream.copyTo(bom);
            bom.saveToFile(pathname, 2);
            //-------------------------
            bom.flush();
            bom.close();
        }else{
            stream.saveToFile(pathname, 2);
        }

        stream.flush();
        stream.close();
        stream = null;
        bom = null;
    },
    single: function(data, findPath, charset){
        WScript.echo("SED(" + findPath + ")");

        var content = _sed.read(findPath, charset);
        var regexp = null;

        // WScript.echo(content)

        if(data.ext){
            regexp = new RegExp(_sed.escape(data.prefix) + "(\\.[0-9a-fA-F]{40}){0,1}", "g");
            // WScript.echo("pattern a: " + regexp);
            // WScript.echo("regexp a: " + regexp.test(content) + ", source: " + data.source);
            content = content.replace(regexp, data.target);
        }else{
            regexp = new RegExp("\"" + _sed.escape(data.prefix) + "(\\.[0-9a-fA-F]{40}){0,1}" + "\"", "g");
            // WScript.echo("pattern b: " + regexp);
            // WScript.echo("regexp b: " + regexp.test(content) + ", source: " + data.source);
            content = content.replace(regexp, "\"" + data.target + "\"");
        }

        // WScript.echo("regexp: " + regexp);

        regexp = null;

        _sed.write(findPath, content, charset);
    },
    multiple: function(data, findPath, charset){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var folder = fso.GetFolder(findPath);
        var folders = new Enumerator(folder.SubFolders);
        var files = new Enumerator(folder.Files);

        for(; !files.atEnd(); files.moveNext()){
            var name = files.item();

            WScript.echo("multiple::file = " + name);

            _sed.single(data, name, charset);
        }

        for(; !folders.atEnd(); folders.moveNext()){
            var name = folders.item();

            WScript.echo("multiple::folder = " + name);

            _sed.multiple(data, name, charset);
        }

        fso = null;
    },
    find: function(data, findPath, charset){
        var fso = new ActiveXObject("Scripting.FileSystemObject");

        if(fso.FileExists(findPath)){
            _sed.single(data, findPath, charset);
        }else if(fso.FolderExists(findPath)){
            _sed.multiple(data, findPath, charset);
        }else{
            WScript.echo("find::not found(" + findPath + ")");
        }

        fso = null;
    },
    replace: function(replaceName, findPath, charset){
        replaceName = replaceName.replace(/[\\"]/g, "");
        charset = (charset || "utf-8").toLowerCase();

        var data = _sed.parse(replaceName);

        WScript.echo(replaceName + "; " + findPath);

        if(data){
            _sed.find(data, findPath, charset);
        }else{
            WScript.echo("replace::parse error(" + replaceName + ")");
        }
    }
};

//---
(function main(sed){
    var args = WScript.Arguments;
    var tmp = [];

    for(var i = 0, count = args.count(); i < count; i++){
        tmp.push(args.item(i));
    }

    sed.replace.apply(sed, tmp);
})(_sed);<commit_msg>兼容windows<commit_after>//---
var FOR_READING = 1,
    FOR_WRITING = 2,
    FOR_APPENDING = 8;
var TRISTATE_USE_DEFAULT = -2,
    TRISTATE_TRUE = -1,
    TRISTATE_FALSE = 0;
var _sed = {
    parse: function(name, flag){
        var pattern = /^(.*)(\.[0-9a-fA-F]{40})(\.[a-zA-Z0-9]+)?$/g;
        var matcher = null;

        pattern.lastIndex = 0;

        WScript.echo("sed::parse => " + name);

        if(null != (matcher = pattern.exec(name))){
            WScript.echo("sed::parse => matcher: " + matcher);

            return {
                "source": matcher[0],
                "prefix": matcher[1],
                "sign": matcher[2],
                "ext": matcher[3],
                "flag": flag,
                "target": matcher[1] + matcher[2]
            }
        }

        WScript.echo("sed::parse => matcher: " + matcher);

        return null;
    },
    escape: function(str){
        str = str.replace(/\./g, "\\.");
        str = str.replace(/\-/g, "\\-");
        str = str.replace(/\//g, "\\/");

        return str;
    },
    read : function(pathname, charset){
        var stream = new ActiveXObject("ADODB.Stream");
        var content = "";

        stream.type = 2;
        stream.mode = 3;
        stream.charset = charset;
        stream.open();
        stream.loadFromFile(pathname);

        content = stream.readText;

        stream.close();
        stream = null;

        return content;
    },
    write : function(pathname, content, charset){
        var stream = new ActiveXObject("ADODB.Stream");
        var bom = null;

        stream.type = 2;
        stream.mode = 3;
        stream.charset = charset;
        stream.open();
        stream.writeText(content);

        if("utf-8" == charset){
            //BOM
            bom = new ActiveXObject("ADODB.Stream");
            stream.position = 3;
            bom.type = 1;
            bom.mode = 3;
            bom.open();
            stream.copyTo(bom);
            bom.saveToFile(pathname, 2);
            //-------------------------
            bom.flush();
            bom.close();
        }else{
            stream.saveToFile(pathname, 2);
        }

        stream.flush();
        stream.close();
        stream = null;
        bom = null;
    },
    single: function(data, findPath, charset){
        WScript.echo("SED(" + findPath + ")");

        var content = _sed.read(findPath, charset);
        var regexp = null;

        // WScript.echo(content)

        if(data.ext){
            regexp = new RegExp(_sed.escape(data.prefix) + "(\\.[0-9a-fA-F]{40}){0,1}" + (data.ext).replace(".", "\\."), "g");
            // WScript.echo("pattern a: " + regexp);
            // WScript.echo("regexp a: " + regexp.test(content) + ", source: " + data.source);
            content = content.replace(regexp, data.target + data.ext);
        }else if(data.flag){
            regexp = new RegExp(_sed.escape(data.prefix) + "(\\.[0-9a-fA-F]{40}){0,1}" + "(\\\"|\\.js)", "g");
            // WScript.echo("pattern b: " + regexp);
            // WScript.echo("regexp b: " + regexp.test(content) + ", source: " + data.source);
            content = content.replace(regexp, data.target + "$2");
        }

        // WScript.echo("regexp: " + regexp);

        regexp = null;

        _sed.write(findPath, content, charset);
    },
    multiple: function(data, findPath, charset){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var folder = fso.GetFolder(findPath);
        var folders = new Enumerator(folder.SubFolders);
        var files = new Enumerator(folder.Files);

        for(; !files.atEnd(); files.moveNext()){
            var name = files.item();

            WScript.echo("multiple::file = " + name);

            _sed.single(data, name, charset);
        }

        for(; !folders.atEnd(); folders.moveNext()){
            var name = folders.item();

            WScript.echo("multiple::folder = " + name);

            _sed.multiple(data, name, charset);
        }

        fso = null;
    },
    find: function(data, findPath, charset){
        var fso = new ActiveXObject("Scripting.FileSystemObject");

        if(fso.FileExists(findPath)){
            _sed.single(data, findPath, charset);
        }else if(fso.FolderExists(findPath)){
            _sed.multiple(data, findPath, charset);
        }else{
            WScript.echo("find::not found(" + findPath + ")");
        }

        fso = null;
    },
    replace: function(replaceName, findPath, charset){
        var pattern = /(.+)([a-fA-F0-9]{40})(\\[0-9]{1})?/g;
        var matcher = null;
        var flag = null;

        pattern.lastIndex = 0;

        matcher = pattern.exec(replaceName);

        if(null !== matcher){
            flag = matcher[2] || null;
            if(null !== flag){
                replaceName = replaceName.replace(pattern, "$1$2");
            }
        }

        replaceName = replaceName.replace(/[\\"]/g, "");
        charset = (charset || "utf-8").toLowerCase();

        WScript.echo("sed::replace => " + replaceName);
        WScript.echo("sed::replace => " + flag);
        WScript.echo(replaceName + " => " + findPath);

        var data = _sed.parse(replaceName, flag);

        if(data){
            _sed.find(data, findPath, charset);
        }else{
            WScript.echo("replace::parse error(" + replaceName + ")");
        }
    }
};

//---
(function main(sed){
    var args = WScript.Arguments;
    var tmp = [];

    for(var i = 0, count = args.count(); i < count; i++){
        tmp.push(args.item(i));
    }

    sed.replace.apply(sed, tmp);
})(_sed);<|endoftext|>


<commit_before>import { valuesNames } from './forms.config';

const validateHelpers = (values, fieldName, errorMessage) => {
  if (!values[fieldName] || isNaN(Number(values[fieldName]))) {
    return errorMessage
  }
  return null;
};

const validateForm = (values) => {
  const errors = {};
  errors[valuesNames.RESPIRATION_RATE] = validateHelpers(values, valuesNames.RESPIRATION_RATE, 'You must enter a correct value.');
  errors[valuesNames.OXYGEN_SATURATION] = validateHelpers(values, valuesNames.OXYGEN_SATURATION, 'You must enter a correct value from 0 to 100.');
  errors[valuesNames.HEART_RATE] = validateHelpers(values, valuesNames.HEART_RATE, 'You must enter a correct value.');
  errors[valuesNames.SYSTOLIC_BP] = validateHelpers(values, valuesNames.SYSTOLIC_BP, 'You must enter a correct value.');
  errors[valuesNames.DIASTOLIC_BP] = validateHelpers(values, valuesNames.DIASTOLIC_BP, 'You must enter a correct value.');
  errors[valuesNames.TEMPERATURE] = validateHelpers(values, valuesNames.TEMPERATURE, 'You must enter a correct value.');
  errors[valuesNames.AUTHOR] = !values[valuesNames.AUTHOR] ? 'You must enter a correct value.' : null;

  return errors;
};

export { validateForm }
<commit_msg>update validation #87<commit_after>import { valuesNames } from './forms.config';

const validateHelpers = (values, fieldName, errorMessage) => {
  if (!values[fieldName] || isNaN(Number(values[fieldName]))) {
    return errorMessage
  }
  return null;
};

const validateForm = (values) => {
  const errors = {};
  errors[valuesNames.RESPIRATION_RATE] = validateHelpers(values, valuesNames.RESPIRATION_RATE, 'You must enter a correct value.');
  errors[valuesNames.OXYGEN_SATURATION] = validateHelpers(values, valuesNames.OXYGEN_SATURATION, 'You must enter a correct value from 0 to 100.');
  errors[valuesNames.HEART_RATE] = validateHelpers(values, valuesNames.HEART_RATE, 'You must enter a correct value.');
  errors[valuesNames.SYSTOLIC_BP] = validateHelpers(values, valuesNames.SYSTOLIC_BP, 'You must enter a correct value.');
  errors[valuesNames.DIASTOLIC_BP] = validateHelpers(values, valuesNames.DIASTOLIC_BP, 'You must enter a correct value.');
  errors[valuesNames.TEMPERATURE] = validateHelpers(values, valuesNames.TEMPERATURE, 'You must enter a correct value.');
  errors[valuesNames.LEVEL_OF_CONSCIOUSNESS] = !values[valuesNames.LEVEL_OF_CONSCIOUSNESS] ? 'You must enter a value.' : null;
  errors[valuesNames.AUTHOR] = !values[valuesNames.AUTHOR] ? 'You must enter a correct value.' : null;

  return errors;
};

export { validateForm }
<|endoftext|>


<commit_before>import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { View, TouchableOpacity, TextInput, Animated } from 'react-native'
import DefaultText from '../DefaultText'
import colors from '../../util/colors'
import merge from '../../util/merge'
import animateTo from '../../util/animateTo'
import * as actions from '../../store/reducer/login'
import commonStyle from '../style'
import KeyboardComponent from '../KeyboardComponent'

const style = {
  loginContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
  },
  animatedContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
    ...commonStyle.shadow
  },
  loginButton: {
    flex: 1,
    height: 68,
    padding: 20,
    backgroundColor: colors.bristolBlue
  },
  loginButtonText: {
    color: 'white',
    fontSize: 24,
    textAlign: 'center'
  },
  input: {
    height: 68,
    fontSize: 20,
    color: colors.bristolBlue,
    backgroundColor: 'white',
    textAlign: 'center'
  },
  separator: {
    height: 1,
    backgroundColor: colors.gray5
  }
}

class Login extends KeyboardComponent {
  constructor() {
    super()
  }

  selectPasswordField() {
    this.passwordInputRef.focus()
  }

  componentDidUpdate(lastProps) {
    if (this.props.loginFormOpen && !lastProps.loginFormOpen) {
      const bottom = new Animated.Value(-204)
      this.setState({ bottom })
      animateTo(bottom, 0, 500)
    }
  }

  render() {
    const loginView = (
      <Animated.View style={merge(style.loginContainer, { bottom: this.state.bottom, height: 204 + this.state.keyboardHeight })}>
        <View style={merge(style.loginContainer, { bottom: this.state.keyboardHeight })}>
          <TouchableOpacity style={style.loginButton}
              accessibilityLabel={'Login Button'}
              onPress={() => this.props.login(this.props.username, this.props.password)}>
            <DefaultText style={style.loginButtonText}>Log in</DefaultText>
          </TouchableOpacity>
          { this.props.hideUsernameInput
            ? undefined
            : <TextInput style={style.input}
                accessibilityLabel={'Input Username'}
                autoFocus={true}
                onChangeText={(text) => this.props.usernameUpdated(text)}
                onSubmitEditing={this.selectPasswordField.bind(this)}
                placeholder={'Username'}
                placeholderTextColor={colors.gray4}
                selectTextOnFocus={true}
                value={this.props.username} />
          }
          <View style={style.separator}/>
          <TextInput style={style.input}
              ref={(ref) => this.passwordInputRef = ref}
              accessibilityLabel={'Input Password'}
              autoFocus={this.props.hideUsernameInput}
              onChangeText={(text) => this.props.passwordUpdated(text)}
              onSubmitEditing={() => this.props.login(this.props.username, this.props.password)}
              placeholder={'Password'}
              placeholderTextColor={colors.gray4}
              secureTextEntry={true}
              selectTextOnFocus={true}
              value={this.props.password} />
        </View>
      </Animated.View>
    )
    return this.props.loginFormOpen ? loginView : <View style={{ height: 0 }}/>
  }
}

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(actions, dispatch)

const mapStateToProps = (state) => ({...state.login})

export default connect(mapStateToProps, mapDispatchToProps)(Login)
<commit_msg>verify username for login<commit_after>import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { View, TouchableOpacity, TextInput, Animated } from 'react-native'
import DefaultText from '../DefaultText'
import colors from '../../util/colors'
import merge from '../../util/merge'
import animateTo from '../../util/animateTo'
import * as actions from '../../store/reducer/login'
import commonStyle from '../style'
import KeyboardComponent from '../KeyboardComponent'

const style = {
  loginContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
  },
  animatedContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
    ...commonStyle.shadow
  },
  loginButton: {
    flex: 1,
    height: 68,
    padding: 20,
  },
  loginButtonText: {
    fontSize: 24,
    textAlign: 'center'
  },
  input: {
    height: 68,
    fontSize: 20,
    color: colors.bristolBlue,
    backgroundColor: 'white',
    textAlign: 'center'
  },
  separator: {
    height: 1,
    backgroundColor: colors.gray5
  }
}

// Cyclos doesn't like special characters or empty usernames :(
const isValid = (username) => username && !username.match(/\W/)

class Login extends KeyboardComponent {
  constructor() {
    super()
  }

  selectPasswordField() {
    this.passwordInputRef.focus()
  }

  componentDidUpdate(lastProps) {
    if (this.props.loginFormOpen && !lastProps.loginFormOpen) {
      const bottom = new Animated.Value(-204)
      this.setState({ bottom })
      animateTo(bottom, 0, 500)
    }
  }

  render() {
    const { username, password, hideUsernameInput, login, usernameUpdated, passwordUpdated } = this.props
    const loginView = (
      <Animated.View style={merge(style.loginContainer, { bottom: this.state.bottom, height: 204 + this.state.keyboardHeight })}>
      <View style={merge(style.loginContainer, { bottom: this.state.keyboardHeight })}>
        <TouchableOpacity style={{ ...style.loginButton, backgroundColor: isValid(username) ? colors.bristolBlue : colors.offWhite }}
            accessibilityLabel={'Login Button'}
            onPress={() => isValid(username) && login(username, password)}>
          <DefaultText style={{ ...style.loginButtonText, color: isValid(username) ? 'white' : 'black' }}>Log in</DefaultText>
        </TouchableOpacity>
        { hideUsernameInput
          ? undefined
          : <TextInput style={style.input}
              accessibilityLabel={'Input Username'}
              autoFocus={true}
              onChangeText={(text) => usernameUpdated(text)}
              onSubmitEditing={this.selectPasswordField.bind(this)}
              placeholder={'Username'}
              placeholderTextColor={colors.gray4}
              selectTextOnFocus={true}
              value={username} />
        }
        <View style={style.separator}/>
        <TextInput style={style.input}
            ref={(ref) => this.passwordInputRef = ref}
            accessibilityLabel={'Input Password'}
            autoFocus={hideUsernameInput}
            onChangeText={(text) => passwordUpdated(text)}
            onSubmitEditing={() => login(username, password)}
            placeholder={'Password'}
            placeholderTextColor={colors.gray4}
            secureTextEntry={true}
            selectTextOnFocus={true}
            value={password} />
      </View>
      </Animated.View>
    )
    return this.props.loginFormOpen ? loginView : <View style={{ height: 0 }}/>
  }
}

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(actions, dispatch)

const mapStateToProps = (state) => ({...state.login})

export default connect(mapStateToProps, mapDispatchToProps)(Login)
<|endoftext|>


<commit_before>/* eslint-disable array-callback-return */

import path from 'path';
import fs from 'fs';

const PACKAGE_JSON = path.resolve (process.cwd (), 'package.json');
const BABEL_RC = path.resolve (process.cwd (), '.babelrc');
const WEBPACK_CONFIG = path.resolve (process.cwd (), '.webpackconfig');

export const packageJSON = JSON.parse (
  fs.readFileSync (path.resolve (PACKAGE_JSON), 'utf8')
);

export const babelrc = JSON.parse (
  fs.readFileSync (path.resolve (BABEL_RC), 'utf8')
);

export const webpackConfig = JSON.parse (
  fs.readFileSync (path.resolve (WEBPACK_CONFIG), 'utf8')
);

const _externals = {};
const { peerDependencies, dependencies } = packageJSON;
const set = (_dependencies) => {
  Object.keys (_dependencies).map ((dependency) => {
    _externals[dependency] = dependency;
  });
};

if (dependencies) set (dependencies);
if (peerDependencies) set (peerDependencies);

export const externals = _externals;
<commit_msg>Removed .webpackconfig references in config.js<commit_after>/* eslint-disable array-callback-return */

import path from 'path';
import fs from 'fs';

const PACKAGE_JSON = path.resolve (process.cwd (), 'package.json');
const BABEL_RC = path.resolve (process.cwd (), '.babelrc');

export const packageJSON = JSON.parse (
  fs.readFileSync (path.resolve (PACKAGE_JSON), 'utf8')
);

export const babelrc = JSON.parse (
  fs.readFileSync (path.resolve (BABEL_RC), 'utf8')
);

const _externals = {};
const { peerDependencies, dependencies } = packageJSON;
const set = (_dependencies) => {
  Object.keys (_dependencies).map ((dependency) => {
    _externals[dependency] = dependency;
  });
};

if (dependencies) set (dependencies);
if (peerDependencies) set (peerDependencies);

export const externals = _externals;
<|endoftext|>


<commit_before>define(['Bacon', 'jquery', 'underscore'],
function(Bacon,           $,        _) {

var rz_core; // circular dependency, see get_rz_core

function list_from_list_like(list_like)
{
    var list = [],
        i;

    for (i = 0 ; i < list_like.length ; ++i) {
        list.push(list_like[i]);
    }
    return list;
}

function root_nodes_ids() {
    return _.pluck(root_nodes, 'id');
}

function Selection() {
}

function new_selection(nodes, root_nodes)
{
    var ret = new Selection();

    ret.nodes = nodes;
    ret.root_nodes = root_nodes;
    return ret;
}

function get_rz_core()
{
    // circular dependency on rz_core, so require.js cannot solve it.
    if (rz_core === undefined) {
        rz_core = require('rz_core');
        listen_on_diff_bus(rz_core.main_graph.diffBus);
    }
    return rz_core;
}

function get_main_graph()
{
    return get_rz_core().main_graph;
}

function get_main_graph_view()
{
    return get_rz_core().main_graph_view;
}

var root_nodes, // these are the nodes that are requested via update
    selected_nodes,      // these are the nodes that are highlighted, generally the neighbours of selection_request
    selected_nodes__by_id,
    root_nodes__by_id,
    selectionChangedBus = new Bacon.Bus();

function listen_on_diff_bus(diffBus)
{
    diffBus
        .onValue(function (diff) {
            // update due to potentially removed nodes first
            root_nodes = root_nodes.filter(function (n) {
                return get_main_graph().find_node__by_id(n.id) !== null;
            });
            // reselect based on current graph
            inner_select_nodes(root_nodes);
        });
}

function sortedArrayDiff(a, b, a_cmp_b)
{
    var a_i = 0,
        b_i = 0,
        ret = [];

    while (a_i < a.length && b_i < b.length) {
        while (a_i < a.length && a_cmp_b(a[a_i], b[b_i]) == -1) {
            ret.push(a[a_i]);
            a_i += 1;
        }
        while (b_i < b.length && a_i < a.length && a_cmp_b(a[a_i], b[b_i]) == 0) {
            b_i += 1;
            a_i += 1;
        }
        while (b_i < b.length && a_i < a.length && a_cmp_b(a[a_i], b[b_i]) == 1) {
            b_i += 1;
        }
    }
    for (; a_i < a.length ; ++a_i) {
        ret.push(a[a_i]);
    }
    return ret;
}

function nodes_to_id_dict(nodes)
{
    return nodes.reduce(
            function(d, v) {
                d[v.id] = v;
                return d;
            }, {});
}

function updateSelectedNodesBus(nodes, new_selected_nodes)
{
    if (_.isEqual(root_nodes, nodes) && _.isEqual(selected_nodes, new_selected_nodes)) {
        return;
    }
    root_nodes = nodes;
    root_nodes__by_id = nodes_to_id_dict(nodes);
    selected_nodes = new_selected_nodes;
    selected_nodes__by_id = nodes_to_id_dict(selected_nodes);
    selectionChangedBus.push(new_selection(selected_nodes, root_nodes));
}

/* add nodes in nodes_b to a copy of nodes_a in order, skipping duplicates */
function sum_nodes(nodes_a, nodes_b)
{
    var set_a_id = _.object(nodes_a.map(function (n) { return [n.id, 1]; })),
        ret = nodes_a.slice(0);

    for (var k in nodes_b) {
        if (set_a_id[nodes_b[k].id] === undefined) {
            ret.push(nodes_b[k]);
        }
    }
    return ret;
}

function links_to_nodes(links)
{
    return _.flatten(_.map(links, function (link) { return [link.__src, link.__dst]; }));
}

function byVisitors(node_selector, link_selector) {
    var new_selection = get_main_graph().find__by_visitors(node_selector, link_selector);

    inner_select_nodes(sum_nodes(new_selection.nodes, links_to_nodes(new_selection.links)));
}

function connectedComponent(nodes) {
    var connected = get_main_graph().getConnectedNodesAndLinks(nodes, 1),
        i,
        node,
        link,
        data;

    for (i = 0 ; i < connected.nodes.length ; ++i) {
        data = connected.nodes[i];
        node = data.node;
        switch (data.type) {
        case 'exit':
            node.state = 'exit';
            break;
        case 'enter':
            node.state = 'enter';
            break;
        };
    }
    for (i = 0 ; i < connected.links.length ; ++i) {
        data = connected.links[i];
        link = data.link;
        switch (data.type) {
        case 'exit':
            link.state = 'exit';
            break;
        case 'enter':
            link.state = 'enter';
            break;
        };
    }
    // XXX side effect, should not be here
    nodes.forEach(function (n) { n.state = 'chosen'; });
    return connected.nodes.map(function (d) { return d.node; }).concat(nodes.slice());
}

var node_selected = function(node) {
    return selected_nodes__by_id[node.id] !== undefined;
}

var node_root_selected = function(node) {
    return root_nodes__by_id[node.id] !== undefined;
}

var node_first_selected = function(node) {
    return node.id === root_nodes[0].id;
}

var link_selected = function(link) {
    return node_selected(link.__src) && node_selected(link.__dst);
}

var selected_class__node = function(node, temporary) {
    return !temporary && selected_nodes.length > 0 ?
        (node_first_selected(node) ? 'first-selected' :
            (node_root_selected(node) ? 'root-selected' :
                (node_selected(node) ? "selected" : "notselected"))) : "";
}

var selected_class__link = function(link, temporary) {
    return !temporary && selected_nodes.length > 0 ? (link_selected(link) ? "selected" : "notselected") : "";
}

var clear = function()
{
    updateSelectedNodesBus([], []);
}

function arr_compare(a1, a2)
{
    if (a1.length != a2.length) {
        return false;
    }
    for (var i = 0 ; i < a1.length ; ++i) {
        if (a1[i] != a2[i]) {
            return false;
        }
    }
    return true;
}

var inner_select_nodes = function(nodes)
{
    inner_select(nodes, connectedComponent(nodes));
}

var select_nodes = function(nodes)
{
    var new_nodes = nodes;
    var not_same = !arr_compare(new_nodes, root_nodes);

    if (not_same) {
        inner_select_nodes(new_nodes);
    }
}

var inner_select = function(new_root_nodes, new_selected_nodes)
{
    if (arr_compare(new_root_nodes, root_nodes) && arr_compare(new_selected_nodes, selected_nodes)) {
        // no change
        return;
    }
    get_main_graph_view().nodes__user_visible(new_selected_nodes);
    updateSelectedNodesBus(new_root_nodes, new_selected_nodes);
}

function nodes_from_link(link)
{
    return [link.__src, link.__dst];
}

var select_link = function(link)
{
    var new_root_nodes = nodes_from_link(link);

    inner_select(new_root_nodes, new_root_nodes);
}

function invert(initial, inverted)
{
    return _.union(_.difference(initial, inverted), _.difference(inverted, initial));
}

var invert_link = function(link)
{
    var link_nodes = nodes_from_link(link),
        new_root_nodes = invert(root_nodes, link_nodes),
        new_selected_nodes = invert(selected_nodes, link_nodes);

    inner_select(new_root_nodes, new_selected_nodes);
}

var invert_nodes = function(nodes)
{
    select_nodes(invert(root_nodes, nodes));
}

var setup_toolbar = function(main_graph)
{
    var merge_root_selection = function() {
            main_graph.nodes__merge(root_nodes_ids());
        },
        delete_root_selection = function() {
            var ids = root_nodes_ids();

            if (confirm('you are deleting ' + ids.length + ' nodes, are you sure?')) {
                main_graph.nodes__delete(ids);
            }
        },
        link_fan_root_selection = function() {
            main_graph.nodes__link_fan(root_nodes_ids());
        },
        merge_btn = $('#btn_merge'),
        delete_btn = $('#btn_delete'),
        link_fan_btn = $('#btn_link_fan'),
        multiple_node_operations = $('#tool-bar-multiple-node-operations');

    merge_btn.asEventStream('click').onValue(merge_root_selection);
    delete_btn.asEventStream('click').onValue(delete_root_selection);
    link_fan_btn.asEventStream('click').onValue(link_fan_root_selection);

    selectionChangedBus.map(function (selection) { return selection.root_nodes.length > 1; })
        .skipDuplicates()
        .onValue(function (visible) {
            if (visible) {
                multiple_node_operations.show();
            } else {
                multiple_node_operations.hide();
            }
        });
}

var is_empty = function() {
    return root_nodes.length == 0;
}

// initialize
clear();

return {
    byVisitors: byVisitors,
    connectedComponent: connectedComponent,
    is_empty: is_empty,
    clear: clear,
    select_nodes: select_nodes,
    invert_nodes: invert_nodes,
    select_link: select_link,
    invert_link: invert_link,
    selected_class__node: selected_class__node,
    selected_class__link: selected_class__link,
    node_selected: node_selected,
    link_selected: link_selected,
    selectionChangedBus: selectionChangedBus,
    setup_toolbar: setup_toolbar,

    __get_root_nodes: function() { return root_nodes; },
    __get_selected_nodes: function() { return selected_nodes; },
};

});
<commit_msg>client/view/selection: on diff for link editing don't select too many nodes<commit_after>define(['Bacon', 'jquery', 'underscore'],
function(Bacon,           $,        _) {

var rz_core; // circular dependency, see get_rz_core

function list_from_list_like(list_like)
{
    var list = [],
        i;

    for (i = 0 ; i < list_like.length ; ++i) {
        list.push(list_like[i]);
    }
    return list;
}

function root_nodes_ids() {
    return _.pluck(root_nodes, 'id');
}

function Selection() {
}

function new_selection(nodes, root_nodes)
{
    var ret = new Selection();

    ret.nodes = nodes;
    ret.root_nodes = root_nodes;
    return ret;
}

function get_rz_core()
{
    // circular dependency on rz_core, so require.js cannot solve it.
    if (rz_core === undefined) {
        rz_core = require('rz_core');
        listen_on_diff_bus(rz_core.main_graph.diffBus);
    }
    return rz_core;
}

function get_main_graph()
{
    return get_rz_core().main_graph;
}

function get_main_graph_view()
{
    return get_rz_core().main_graph_view;
}

var root_nodes, // these are the nodes that are requested via update
    selected_nodes,      // these are the nodes that are highlighted, generally the neighbours of selection_request
    selected_nodes__by_id,
    root_nodes__by_id,
    selectionChangedBus = new Bacon.Bus();

function listen_on_diff_bus(diffBus)
{
    diffBus
        .onValue(function (diff) {
            // update due to potentially removed nodes first
            root_nodes = root_nodes.filter(function (n) {
                return get_main_graph().find_node__by_id(n.id) !== null;
            });
            selected_nodes = selected_nodes.filter(function (n) {
                return get_main_graph().find_node__by_id(n.id) !== null;
            });
            // reselect based on current graph
            inner_select(root_nodes, selected_nodes);
        });
}

function sortedArrayDiff(a, b, a_cmp_b)
{
    var a_i = 0,
        b_i = 0,
        ret = [];

    while (a_i < a.length && b_i < b.length) {
        while (a_i < a.length && a_cmp_b(a[a_i], b[b_i]) == -1) {
            ret.push(a[a_i]);
            a_i += 1;
        }
        while (b_i < b.length && a_i < a.length && a_cmp_b(a[a_i], b[b_i]) == 0) {
            b_i += 1;
            a_i += 1;
        }
        while (b_i < b.length && a_i < a.length && a_cmp_b(a[a_i], b[b_i]) == 1) {
            b_i += 1;
        }
    }
    for (; a_i < a.length ; ++a_i) {
        ret.push(a[a_i]);
    }
    return ret;
}

function nodes_to_id_dict(nodes)
{
    return nodes.reduce(
            function(d, v) {
                d[v.id] = v;
                return d;
            }, {});
}

function updateSelectedNodesBus(nodes, new_selected_nodes)
{
    if (_.isEqual(root_nodes, nodes) && _.isEqual(selected_nodes, new_selected_nodes)) {
        return;
    }
    root_nodes = nodes;
    root_nodes__by_id = nodes_to_id_dict(nodes);
    selected_nodes = new_selected_nodes;
    selected_nodes__by_id = nodes_to_id_dict(selected_nodes);
    selectionChangedBus.push(new_selection(selected_nodes, root_nodes));
}

/* add nodes in nodes_b to a copy of nodes_a in order, skipping duplicates */
function sum_nodes(nodes_a, nodes_b)
{
    var set_a_id = _.object(nodes_a.map(function (n) { return [n.id, 1]; })),
        ret = nodes_a.slice(0);

    for (var k in nodes_b) {
        if (set_a_id[nodes_b[k].id] === undefined) {
            ret.push(nodes_b[k]);
        }
    }
    return ret;
}

function links_to_nodes(links)
{
    return _.flatten(_.map(links, function (link) { return [link.__src, link.__dst]; }));
}

function byVisitors(node_selector, link_selector) {
    var new_selection = get_main_graph().find__by_visitors(node_selector, link_selector);

    inner_select_nodes(sum_nodes(new_selection.nodes, links_to_nodes(new_selection.links)));
}

function connectedComponent(nodes) {
    var connected = get_main_graph().getConnectedNodesAndLinks(nodes, 1),
        i,
        node,
        link,
        data;

    for (i = 0 ; i < connected.nodes.length ; ++i) {
        data = connected.nodes[i];
        node = data.node;
        switch (data.type) {
        case 'exit':
            node.state = 'exit';
            break;
        case 'enter':
            node.state = 'enter';
            break;
        };
    }
    for (i = 0 ; i < connected.links.length ; ++i) {
        data = connected.links[i];
        link = data.link;
        switch (data.type) {
        case 'exit':
            link.state = 'exit';
            break;
        case 'enter':
            link.state = 'enter';
            break;
        };
    }
    // XXX side effect, should not be here
    nodes.forEach(function (n) { n.state = 'chosen'; });
    return connected.nodes.map(function (d) { return d.node; }).concat(nodes.slice());
}

var node_selected = function(node) {
    return selected_nodes__by_id[node.id] !== undefined;
}

var node_root_selected = function(node) {
    return root_nodes__by_id[node.id] !== undefined;
}

var node_first_selected = function(node) {
    return node.id === root_nodes[0].id;
}

var link_selected = function(link) {
    return node_selected(link.__src) && node_selected(link.__dst);
}

var selected_class__node = function(node, temporary) {
    return !temporary && selected_nodes.length > 0 ?
        (node_first_selected(node) ? 'first-selected' :
            (node_root_selected(node) ? 'root-selected' :
                (node_selected(node) ? "selected" : "notselected"))) : "";
}

var selected_class__link = function(link, temporary) {
    return !temporary && selected_nodes.length > 0 ? (link_selected(link) ? "selected" : "notselected") : "";
}

var clear = function()
{
    updateSelectedNodesBus([], []);
}

function arr_compare(a1, a2)
{
    if (a1.length != a2.length) {
        return false;
    }
    for (var i = 0 ; i < a1.length ; ++i) {
        if (a1[i] != a2[i]) {
            return false;
        }
    }
    return true;
}

var inner_select_nodes = function(nodes)
{
    inner_select(nodes, connectedComponent(nodes));
}

var select_nodes = function(nodes)
{
    var new_nodes = nodes;
    var not_same = !arr_compare(new_nodes, root_nodes);

    if (not_same) {
        inner_select_nodes(new_nodes);
    }
}

var inner_select = function(new_root_nodes, new_selected_nodes)
{
    if (arr_compare(new_root_nodes, root_nodes) && arr_compare(new_selected_nodes, selected_nodes)) {
        // no change
        return;
    }
    get_main_graph_view().nodes__user_visible(new_selected_nodes);
    updateSelectedNodesBus(new_root_nodes, new_selected_nodes);
}

function nodes_from_link(link)
{
    return [link.__src, link.__dst];
}

var select_link = function(link)
{
    var new_root_nodes = nodes_from_link(link);

    inner_select(new_root_nodes, new_root_nodes);
}

function invert(initial, inverted)
{
    return _.union(_.difference(initial, inverted), _.difference(inverted, initial));
}

var invert_link = function(link)
{
    var link_nodes = nodes_from_link(link),
        new_root_nodes = invert(root_nodes, link_nodes),
        new_selected_nodes = invert(selected_nodes, link_nodes);

    inner_select(new_root_nodes, new_selected_nodes);
}

var invert_nodes = function(nodes)
{
    select_nodes(invert(root_nodes, nodes));
}

var setup_toolbar = function(main_graph)
{
    var merge_root_selection = function() {
            main_graph.nodes__merge(root_nodes_ids());
        },
        delete_root_selection = function() {
            var ids = root_nodes_ids();

            if (confirm('you are deleting ' + ids.length + ' nodes, are you sure?')) {
                main_graph.nodes__delete(ids);
            }
        },
        link_fan_root_selection = function() {
            main_graph.nodes__link_fan(root_nodes_ids());
        },
        merge_btn = $('#btn_merge'),
        delete_btn = $('#btn_delete'),
        link_fan_btn = $('#btn_link_fan'),
        multiple_node_operations = $('#tool-bar-multiple-node-operations');

    merge_btn.asEventStream('click').onValue(merge_root_selection);
    delete_btn.asEventStream('click').onValue(delete_root_selection);
    link_fan_btn.asEventStream('click').onValue(link_fan_root_selection);

    selectionChangedBus.map(function (selection) { return selection.root_nodes.length > 1; })
        .skipDuplicates()
        .onValue(function (visible) {
            if (visible) {
                multiple_node_operations.show();
            } else {
                multiple_node_operations.hide();
            }
        });
}

var is_empty = function() {
    return root_nodes.length == 0;
}

// initialize
clear();

return {
    byVisitors: byVisitors,
    connectedComponent: connectedComponent,
    is_empty: is_empty,
    clear: clear,
    select_nodes: select_nodes,
    invert_nodes: invert_nodes,
    select_link: select_link,
    invert_link: invert_link,
    selected_class__node: selected_class__node,
    selected_class__link: selected_class__link,
    node_selected: node_selected,
    link_selected: link_selected,
    selectionChangedBus: selectionChangedBus,
    setup_toolbar: setup_toolbar,

    __get_root_nodes: function() { return root_nodes; },
    __get_selected_nodes: function() { return selected_nodes; },
};

});
<|endoftext|>


<commit_before>/*
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import dis from '../../../dispatcher/dispatcher';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import RoomViewStore from '../../../stores/RoomViewStore';
import PropTypes from "prop-types";
import {RoomPermalinkCreator} from "../../../utils/permalinks/Permalinks";
import {replaceableComponent} from "../../../utils/replaceableComponent";

function cancelQuoting() {
    dis.dispatch({
        action: 'reply_to_event',
        event: null,
    });
}

@replaceableComponent("views.rooms.ReplyPreview")
export default class ReplyPreview extends React.Component {
    static propTypes = {
        permalinkCreator: PropTypes.instanceOf(RoomPermalinkCreator).isRequired,
    };

    constructor(props) {
        super(props);
        this.unmounted = false;

        this.state = {
            event: RoomViewStore.getQuotingEvent(),
        };

        this._onRoomViewStoreUpdate = this._onRoomViewStoreUpdate.bind(this);
        this._roomStoreToken = RoomViewStore.addListener(this._onRoomViewStoreUpdate);
    }

    componentWillUnmount() {
        this.unmounted = true;

        // Remove RoomStore listener
        if (this._roomStoreToken) {
            this._roomStoreToken.remove();
        }
    }

    _onRoomViewStoreUpdate() {
        if (this.unmounted) return;

        const event = RoomViewStore.getQuotingEvent();
        if (this.state.event !== event) {
            this.setState({ event });
        }
    }

    render() {
        if (!this.state.event) return null;

        const ReplyTile = sdk.getComponent('rooms.ReplyTile');

        return

                    { _t('Replying') }

                    <ReplyTile
                        isRedacted={this.state.event.isRedacted()}
                         mxEvent={this.state.event}
                        permalinkCreator={this.props.permalinkCreator}
                    />

;
    }
}
<commit_msg>Remove extra space<commit_after>/*
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import dis from '../../../dispatcher/dispatcher';
import * as sdk from '../../../index';
import { _t } from '../../../languageHandler';
import RoomViewStore from '../../../stores/RoomViewStore';
import PropTypes from "prop-types";
import {RoomPermalinkCreator} from "../../../utils/permalinks/Permalinks";
import {replaceableComponent} from "../../../utils/replaceableComponent";

function cancelQuoting() {
    dis.dispatch({
        action: 'reply_to_event',
        event: null,
    });
}

@replaceableComponent("views.rooms.ReplyPreview")
export default class ReplyPreview extends React.Component {
    static propTypes = {
        permalinkCreator: PropTypes.instanceOf(RoomPermalinkCreator).isRequired,
    };

    constructor(props) {
        super(props);
        this.unmounted = false;

        this.state = {
            event: RoomViewStore.getQuotingEvent(),
        };

        this._onRoomViewStoreUpdate = this._onRoomViewStoreUpdate.bind(this);
        this._roomStoreToken = RoomViewStore.addListener(this._onRoomViewStoreUpdate);
    }

    componentWillUnmount() {
        this.unmounted = true;

        // Remove RoomStore listener
        if (this._roomStoreToken) {
            this._roomStoreToken.remove();
        }
    }

    _onRoomViewStoreUpdate() {
        if (this.unmounted) return;

        const event = RoomViewStore.getQuotingEvent();
        if (this.state.event !== event) {
            this.setState({ event });
        }
    }

    render() {
        if (!this.state.event) return null;

        const ReplyTile = sdk.getComponent('rooms.ReplyTile');

        return

                    { _t('Replying') }

                    <ReplyTile
                        isRedacted={this.state.event.isRedacted()}
                        mxEvent={this.state.event}
                        permalinkCreator={this.props.permalinkCreator}
                    />

;
    }
}
<|endoftext|>


<commit_before>var P = require("parsimmon");

module.exports = function(ps) {
    return P.alt(
        ps.Block,
        ps.If,
        ps.Let,
        ps.TopUnaryExpr,
        ps.Match,
        ps.BinExpr,
        ps.Literal
    );
};
<commit_msg>Forgot to stop using the thing I deleted again<commit_after>var P = require("parsimmon");

module.exports = function(ps) {
    return P.alt(
        ps.If,
        ps.Let,
        ps.TopUnaryExpr,
        ps.Match,
        ps.BinExpr,
        ps.Literal
    );
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import {fromJS, Map} from 'immutable';

const CreateService = ( {cloudProviderAppState, projectNameAppState, repositoryAppState, applicationAppState, userAppState, requestPostUserProject} ) => {
  const handleCreateUserProject = (e) => {
    e.preventDefault();
    requestPostUserProject(fromJS({
      "authorization": userAppState.get('user_session').toJS().token,
      "user_project":{
        "user_id": userAppState.get('user_session').toJS().id,
        "project_name": projectNameAppState.get("project_name"),
        "roles": (applicationAppState.get("application_name")=='Ghost')?
          [
            ["role": applicationAppState.get("application_name").toLowerCase(), "sudo": "yes"]
          ]: [
            ["role": "web", "sudo": "yes"]
          ],
        "server_provider": "digital_ocean",
        "configuration": (applicationAppState.get("application_name")=='Ghost')?
        {
          "server_name": projectNameAppState.get("project_name"),
          "ghost_user_name": projectNameAppState.get("project_name").split(".")[0],
          "ghost_user_group": projectNameAppState.get("project_name").split(".")[0],
          "ghost_repo": "https://github.com/"+repositoryAppState.get("repository").toJS().name
        }: {
          "server_name": projectNameAppState.get("project_name"),
          "nginx_remove_default_vhost": "true",
          "server_user": projectNameAppState.get("project_name").split(".")[0],
          "server_group": projectNameAppState.get("project_name").split(".")[0],
          "github_repo": "https://github.com/"+repositoryAppState.get("repository").toJS().name
        },
        "repository": {
          "provider": repositoryAppState.get("repository").toJS().provider,
          "name": repositoryAppState.get("repository").toJS().name
        },
        "ssh_keys": cloudProviderAppState.get('cloud_provider_ssh_keys').filter(value =>
          value.get('enable') == true
        ).map(value =>
          Map({
            user_id: userAppState.get('user_session').toJS().id,
            title: value.get('title'),
            fingerprint: value.get('fingerprint'),
            key: value.get('key')
          })
        ).toJS()
      }
    }));
  };
  const btnCreateService =
    repositoryAppState.get('integration') &&
    repositoryAppState.get('repository') &&
    projectNameAppState.get('project_name') &&
    applicationAppState.get('application_name') ?

           Create Service :

           Create Service;
    return (

        {btnCreateService}

  );
};

CreateService.propTypes = {
  cloudProviderAppState: PropTypes.object.isRequired,
  projectNameAppState: PropTypes.object.isRequired,
  repositoryAppState: PropTypes.object.isRequired,
  applicationAppState: PropTypes.object.isRequired,
  userAppState: PropTypes.object.isRequired,
  requestPostUserProject: PropTypes.func.isRequired
};

export default CreateService;
<commit_msg>Fix the project struct<commit_after>import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import {fromJS, Map} from 'immutable';

const CreateService = ( {cloudProviderAppState, projectNameAppState, repositoryAppState, applicationAppState, userAppState, requestPostUserProject} ) => {
  const handleCreateUserProject = (e) => {
    e.preventDefault();
    requestPostUserProject(fromJS({
      "authorization": userAppState.get('user_session').toJS().token,
      "user_project":{
        "user_id": userAppState.get('user_session').toJS().id,
        "project_name": projectNameAppState.get("project_name"),
        "roles":[
          {
            "role": (applicationAppState.get("application_name") == 'Ghost') ? applicationAppState.get("application_name").toLowerCase() : "web",
            "sudo": "yes"
          }
        ],
        "server_provider": "digital_ocean",
        "configuration": (applicationAppState.get("application_name")=='Ghost')?
        {
          "server_name": projectNameAppState.get("project_name"),
          "ghost_user_name": projectNameAppState.get("project_name").split(".")[0],
          "ghost_user_group": projectNameAppState.get("project_name").split(".")[0],
          "ghost_repo": "https://github.com/"+repositoryAppState.get("repository").toJS().name
        }: {
          "server_name": projectNameAppState.get("project_name"),
          "nginx_remove_default_vhost": "true",
          "server_user": projectNameAppState.get("project_name").split(".")[0],
          "server_group": projectNameAppState.get("project_name").split(".")[0],
          "github_repo": "https://github.com/"+repositoryAppState.get("repository").toJS().name
        },
        "repository": {
          "provider": repositoryAppState.get("repository").toJS().provider,
          "name": repositoryAppState.get("repository").toJS().name
        },
        "ssh_keys": cloudProviderAppState.get('cloud_provider_ssh_keys').filter(value =>
          value.get('enable') == true
        ).map(value =>
          Map({
            user_id: userAppState.get('user_session').toJS().id,
            title: value.get('title'),
            fingerprint: value.get('fingerprint'),
            key: value.get('key')
          })
        ).toJS()
      }
    }));
  };
  const btnCreateService =
    repositoryAppState.get('integration') &&
    repositoryAppState.get('repository') &&
    projectNameAppState.get('project_name') &&
    applicationAppState.get('application_name') ?

           Create Service :

           Create Service;
    return (

        {btnCreateService}

  );
};

CreateService.propTypes = {
  cloudProviderAppState: PropTypes.object.isRequired,
  projectNameAppState: PropTypes.object.isRequired,
  repositoryAppState: PropTypes.object.isRequired,
  applicationAppState: PropTypes.object.isRequired,
  userAppState: PropTypes.object.isRequired,
  requestPostUserProject: PropTypes.func.isRequired
};

export default CreateService;
<|endoftext|>


<commit_before>import React from 'react'

// constants
const STATUS = {
  IDLE: 'IDLE',
  LOADING: 'LOADING',
  DEBOUNCED: 'DEBOUNCED'
}

class CopyButton extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      status: STATUS.IDLE
    }
  }
}<commit_msg>add basic render function to copy button<commit_after>import React from 'react'

import Button from './Button'

// constants
const BUTTON_COLOR = '#84ACFC'

const STATUS = {
  IDLE: 'IDLE',
  LOADING: 'LOADING',
  DEBOUNCED: 'DEBOUNCED'
}

const textMap = {
  [STATUS.IDLE]: 'Copy Imgur Link',
  [STATUS.LOADING]: 'Loading...',
  [STATUS.DEBOUNCED]: 'Coppied'
}

class CopyButton extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      status: STATUS.IDLE
    }
  }

  handleClick () {
    switch (this.state.status)
  }

  render () {
    return (
      <div>
        <Button onClick={() => {}} title={textMap[this.state.status]} bg={BUTTON_COLOR}/>
      </div>
    )
  }
}

export default CopyButton<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');

var sdk = require('../../../index');
var dis = require('../../../dispatcher');
var Signup = require("../../../Signup");
var ServerConfig = require("../../views/login/ServerConfig");
var RegistrationForm = require("../../views/login/RegistrationForm");
var CaptchaForm = require("../../views/login/CaptchaForm");

var MIN_PASSWORD_LENGTH = 6;

module.exports = React.createClass({
    displayName: 'Registration',

    propTypes: {
        onLoggedIn: React.PropTypes.func.isRequired,
        clientSecret: React.PropTypes.string,
        sessionId: React.PropTypes.string,
        registrationUrl: React.PropTypes.string,
        idSid: React.PropTypes.string,
        hsUrl: React.PropTypes.string,
        isUrl: React.PropTypes.string,
        email: React.PropTypes.string,
        username: React.PropTypes.string,
        guestAccessToken: React.PropTypes.string,
        disableUsernameChanges: React.PropTypes.bool,
        // registration shouldn't know or care how login is done.
        onLoginClick: React.PropTypes.func.isRequired
    },

    getInitialState: function() {
        return {
            busy: false,
            errorText: null,
            enteredHomeserverUrl: this.props.hsUrl,
            enteredIdentityServerUrl: this.props.isUrl
        };
    },

    componentWillMount: function() {
        this.dispatcherRef = dis.register(this.onAction);
        // attach this to the instance rather than this.state since it isn't UI
        this.registerLogic = new Signup.Register(
            this.props.hsUrl, this.props.isUrl
        );
        this.registerLogic.setClientSecret(this.props.clientSecret);
        this.registerLogic.setSessionId(this.props.sessionId);
        this.registerLogic.setRegistrationUrl(this.props.registrationUrl);
        this.registerLogic.setIdSid(this.props.idSid);
        this.registerLogic.setGuestAccessToken(this.props.guestAccessToken);
        this.registerLogic.recheckState();
    },

    componentWillUnmount: function() {
        dis.unregister(this.dispatcherRef);
    },

    componentDidMount: function() {
        // may have already done an HTTP hit (e.g. redirect from an email) so
        // check for any pending response
        var promise = this.registerLogic.getPromise();
        if (promise) {
            this.onProcessingRegistration(promise);
        }
    },

    onHsUrlChanged: function(newHsUrl) {
        this.registerLogic.setHomeserverUrl(newHsUrl);
    },

    onIsUrlChanged: function(newIsUrl) {
        this.registerLogic.setIdentityServerUrl(newIsUrl);
    },

    onAction: function(payload) {
        if (payload.action !== "registration_step_update") {
            return;
        }
        this.forceUpdate(); // registration state has changed.
    },

    onFormSubmit: function(formVals) {
        var self = this;
        this.setState({
            errorText: "",
            busy: true
        });
        this.onProcessingRegistration(this.registerLogic.register(formVals));
    },

    // Promise is resolved when the registration process is FULLY COMPLETE
    onProcessingRegistration: function(promise) {
        var self = this;
        promise.done(function(response) {
            if (!response || !response.access_token) {
                console.warn(
                    "FIXME: Register fulfilled without a final response, " +
                    "did you break the promise chain?"
                );
                // no matter, we'll grab it direct
                response = self.registerLogic.getCredentials();
            }
            if (!response || !response.user_id || !response.access_token) {
                console.error("Final response is missing keys.");
                self.setState({
                    errorText: "There was a problem processing the response."
                });
                return;
            }
            self.props.onLoggedIn({
                userId: response.user_id,
                homeserverUrl: self.registerLogic.getHomeserverUrl(),
                identityServerUrl: self.registerLogic.getIdentityServerUrl(),
                accessToken: response.access_token
            });
            self.setState({
                busy: false
            });
        }, function(err) {
            if (err.message) {
                self.setState({
                    errorText: err.message
                });
            }
            self.setState({
                busy: false
            });
            console.log(err);
        });
    },

    onFormValidationFailed: function(errCode) {
        var errMsg;
        switch (errCode) {
            case "RegistrationForm.ERR_PASSWORD_MISSING":
                errMsg = "Missing password.";
                break;
            case "RegistrationForm.ERR_PASSWORD_MISMATCH":
                errMsg = "Passwords don't match.";
                break;
            case "RegistrationForm.ERR_PASSWORD_LENGTH":
                errMsg = `Password too short (min ${MIN_PASSWORD_LENGTH}).`;
                break;
            case "RegistrationForm.ERR_EMAIL_INVALID":
                errMsg = "This doesn't look like a valid email address";
                break;
            case "RegistrationForm.ERR_USERNAME_INVALID":
                errMsg = "User names may only contain letters, numbers, dots, hyphens and underscores.";
                break;
            case "RegistrationForm.ERR_USERNAME_BLANK":
                errMsg = "You need to enter a user name";
                break;
            default:
                console.error("Unknown error code: %s", errCode);
                errMsg = "An unknown error occurred.";
                break;
        }
        this.setState({
            errorText: errMsg
        });
    },

    onCaptchaLoaded: function(divIdName) {
        this.registerLogic.tellStage("m.login.recaptcha", {
            divId: divIdName
        });
        this.setState({
            busy: false // requires user input
        });
    },

    _getRegisterContentJsx: function() {
        var currStep = this.registerLogic.getStep();
        var registerStep;
        switch (currStep) {
            case "Register.COMPLETE":
                break; // NOP
            case "Register.START":
            case "Register.STEP_m.login.dummy":
                registerStep = (
                    <RegistrationForm
                        showEmail={true}
                        defaultUsername={this.props.username}
                        defaultEmail={this.props.email}
                        disableUsernameChanges={this.props.disableUsernameChanges}
                        minPasswordLength={MIN_PASSWORD_LENGTH}
                        onError={this.onFormValidationFailed}
                        onRegisterClick={this.onFormSubmit} />
                );
                break;
            case "Register.STEP_m.login.email.identity":
                registerStep = (

                        Please check your email to continue registration.

                );
                break;
            case "Register.STEP_m.login.recaptcha":
                registerStep = (
                    <CaptchaForm onCaptchaLoaded={this.onCaptchaLoaded} />
                );
                break;
            default:
                console.error("Unknown register state: %s", currStep);
                break;
        }
        var busySpinner;
        if (this.state.busy) {
            var Spinner = sdk.getComponent("elements.Spinner");
            busySpinner = (
                <Spinner />
            );
        }
        return (

Create an account

                {registerStep}

{this.state.errorText}

                {busySpinner}
                <ServerConfig ref="serverConfig"
                    withToggleButton={true}
                    defaultHsUrl={this.state.enteredHomeserverUrl}
                    defaultIsUrl={this.state.enteredIdentityServerUrl}
                    onHsUrlChanged={this.onHsUrlChanged}
                    onIsUrlChanged={this.onIsUrlChanged}
                    delayTimeMs={1000} />

                    I already have an account

        );
    },

    render: function() {
        var LoginHeader = sdk.getComponent('login.LoginHeader');
        return (

                    <LoginHeader />
                    {this._getRegisterContentJsx()}

        );
    }
});
<commit_msg>Don't show a spinner while we're waiting for the user to do something<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');

var sdk = require('../../../index');
var dis = require('../../../dispatcher');
var Signup = require("../../../Signup");
var ServerConfig = require("../../views/login/ServerConfig");
var RegistrationForm = require("../../views/login/RegistrationForm");
var CaptchaForm = require("../../views/login/CaptchaForm");

var MIN_PASSWORD_LENGTH = 6;

module.exports = React.createClass({
    displayName: 'Registration',

    propTypes: {
        onLoggedIn: React.PropTypes.func.isRequired,
        clientSecret: React.PropTypes.string,
        sessionId: React.PropTypes.string,
        registrationUrl: React.PropTypes.string,
        idSid: React.PropTypes.string,
        hsUrl: React.PropTypes.string,
        isUrl: React.PropTypes.string,
        email: React.PropTypes.string,
        username: React.PropTypes.string,
        guestAccessToken: React.PropTypes.string,
        disableUsernameChanges: React.PropTypes.bool,
        // registration shouldn't know or care how login is done.
        onLoginClick: React.PropTypes.func.isRequired
    },

    getInitialState: function() {
        return {
            busy: false,
            errorText: null,
            enteredHomeserverUrl: this.props.hsUrl,
            enteredIdentityServerUrl: this.props.isUrl
        };
    },

    componentWillMount: function() {
        this.dispatcherRef = dis.register(this.onAction);
        // attach this to the instance rather than this.state since it isn't UI
        this.registerLogic = new Signup.Register(
            this.props.hsUrl, this.props.isUrl
        );
        this.registerLogic.setClientSecret(this.props.clientSecret);
        this.registerLogic.setSessionId(this.props.sessionId);
        this.registerLogic.setRegistrationUrl(this.props.registrationUrl);
        this.registerLogic.setIdSid(this.props.idSid);
        this.registerLogic.setGuestAccessToken(this.props.guestAccessToken);
        this.registerLogic.recheckState();
    },

    componentWillUnmount: function() {
        dis.unregister(this.dispatcherRef);
    },

    componentDidMount: function() {
        // may have already done an HTTP hit (e.g. redirect from an email) so
        // check for any pending response
        var promise = this.registerLogic.getPromise();
        if (promise) {
            this.onProcessingRegistration(promise);
        }
    },

    onHsUrlChanged: function(newHsUrl) {
        this.registerLogic.setHomeserverUrl(newHsUrl);
    },

    onIsUrlChanged: function(newIsUrl) {
        this.registerLogic.setIdentityServerUrl(newIsUrl);
    },

    onAction: function(payload) {
        if (payload.action !== "registration_step_update") {
            return;
        }
        // If the registration state has changed, this means the
        // user now needs to do something. It would be better
        // to expose the explicitly in the register logic.
        this.setState({
            busy: false
        });
    },

    onFormSubmit: function(formVals) {
        var self = this;
        this.setState({
            errorText: "",
            busy: true
        });
        this.onProcessingRegistration(this.registerLogic.register(formVals));
    },

    // Promise is resolved when the registration process is FULLY COMPLETE
    onProcessingRegistration: function(promise) {
        var self = this;
        promise.done(function(response) {
            if (!response || !response.access_token) {
                console.warn(
                    "FIXME: Register fulfilled without a final response, " +
                    "did you break the promise chain?"
                );
                // no matter, we'll grab it direct
                response = self.registerLogic.getCredentials();
            }
            if (!response || !response.user_id || !response.access_token) {
                console.error("Final response is missing keys.");
                self.setState({
                    errorText: "There was a problem processing the response."
                });
                return;
            }
            self.props.onLoggedIn({
                userId: response.user_id,
                homeserverUrl: self.registerLogic.getHomeserverUrl(),
                identityServerUrl: self.registerLogic.getIdentityServerUrl(),
                accessToken: response.access_token
            });
            self.setState({
                busy: false
            });
        }, function(err) {
            if (err.message) {
                self.setState({
                    errorText: err.message
                });
            }
            self.setState({
                busy: false
            });
            console.log(err);
        });
    },

    onFormValidationFailed: function(errCode) {
        var errMsg;
        switch (errCode) {
            case "RegistrationForm.ERR_PASSWORD_MISSING":
                errMsg = "Missing password.";
                break;
            case "RegistrationForm.ERR_PASSWORD_MISMATCH":
                errMsg = "Passwords don't match.";
                break;
            case "RegistrationForm.ERR_PASSWORD_LENGTH":
                errMsg = `Password too short (min ${MIN_PASSWORD_LENGTH}).`;
                break;
            case "RegistrationForm.ERR_EMAIL_INVALID":
                errMsg = "This doesn't look like a valid email address";
                break;
            case "RegistrationForm.ERR_USERNAME_INVALID":
                errMsg = "User names may only contain letters, numbers, dots, hyphens and underscores.";
                break;
            case "RegistrationForm.ERR_USERNAME_BLANK":
                errMsg = "You need to enter a user name";
                break;
            default:
                console.error("Unknown error code: %s", errCode);
                errMsg = "An unknown error occurred.";
                break;
        }
        this.setState({
            errorText: errMsg
        });
    },

    onCaptchaLoaded: function(divIdName) {
        this.registerLogic.tellStage("m.login.recaptcha", {
            divId: divIdName
        });
        this.setState({
            busy: false // requires user input
        });
    },

    _getRegisterContentJsx: function() {
        var currStep = this.registerLogic.getStep();
        var registerStep;
        switch (currStep) {
            case "Register.COMPLETE":
                break; // NOP
            case "Register.START":
            case "Register.STEP_m.login.dummy":
                registerStep = (
                    <RegistrationForm
                        showEmail={true}
                        defaultUsername={this.props.username}
                        defaultEmail={this.props.email}
                        disableUsernameChanges={this.props.disableUsernameChanges}
                        minPasswordLength={MIN_PASSWORD_LENGTH}
                        onError={this.onFormValidationFailed}
                        onRegisterClick={this.onFormSubmit} />
                );
                break;
            case "Register.STEP_m.login.email.identity":
                registerStep = (

                        Please check your email to continue registration.

                );
                break;
            case "Register.STEP_m.login.recaptcha":
                registerStep = (
                    <CaptchaForm onCaptchaLoaded={this.onCaptchaLoaded} />
                );
                break;
            default:
                console.error("Unknown register state: %s", currStep);
                break;
        }
        var busySpinner;
        if (this.state.busy) {
            var Spinner = sdk.getComponent("elements.Spinner");
            busySpinner = (
                <Spinner />
            );
        }
        return (

Create an account

                {registerStep}

{this.state.errorText}

                {busySpinner}
                <ServerConfig ref="serverConfig"
                    withToggleButton={true}
                    defaultHsUrl={this.state.enteredHomeserverUrl}
                    defaultIsUrl={this.state.enteredIdentityServerUrl}
                    onHsUrlChanged={this.onHsUrlChanged}
                    onIsUrlChanged={this.onIsUrlChanged}
                    delayTimeMs={1000} />

                    I already have an account

        );
    },

    render: function() {
        var LoginHeader = sdk.getComponent('login.LoginHeader');
        return (

                    <LoginHeader />
                    {this._getRegisterContentJsx()}

        );
    }
});
<|endoftext|>


<commit_before>// @flow
import * as React from 'react';
import { Editor } from 'slate-react';
import { Value } from 'slate';
import Text from './core/Text';
import SlatePlainSerializer from 'slate-plain-serializer';
import isNumeric from 'validator/lib/isNumeric';
import hotKey from '../browser/hotKey';

type EditorDataProps = {|
  defaultData: ?Object,
  onChange: (data: Object) => void,
|};

type EditorDataState = {|
  editorValue: Object,
|};

class EditorData extends React.PureComponent<EditorDataProps, EditorDataState> {
  static mapDataToEditorValue(data: Object) {
    const text = Object.keys(data)
      .map(key => {
        const value = data[key];
        return `${key}: ${value}`;
      })
      .join(', ');
    // TODO: Consider keys and values model. Plain text is ok for now.
    return Value.fromJSON({
      document: {
        nodes: [
          {
            object: 'block',
            type: 'line',
            nodes: [{ object: 'text', leaves: [{ text }] }],
          },
        ],
      },
    });
  }

  state = {
    editorValue: EditorData.mapDataToEditorValue(this.props.defaultData || {}),
  };

  getCaretPosition(): string {
    const { editorValue: value } = this.state;
    if (!value.selection.isCollapsed) return '';
    if (value.selection.focus.isAtStartOfNode(value.document)) return 'start';
    if (value.selection.focus.isAtEndOfNode(value.document)) return 'end';
    return '';
  }

  handleEditorFocus = (event: any, change: Object) => {
    // https://github.com/ianstormtaylor/slate/issues/1989
    change.focus();
  };

  handleEditorKeyDown = (event: KeyboardEvent) => {
    const { mod, key } = hotKey(event);
    if (key === 'Enter') {
      // Do nothing on enter. It's line.
      event.preventDefault();
      return true;
    }
    if (!mod) return;
    if (key === 'y' || key === 'z') {
      // Prevent default browser history action.
      event.preventDefault();
    }
    if (key === 'ArrowLeft' || key === 'ArrowRight') {
      // Prevent default browser history action.
      event.stopPropagation();
    }
  };

  handleEditorChange = ({ value }: { value: Object }) => {
    this.setState({ editorValue: value });
    const documentChanged = value.document !== this.state.editorValue.document;
    if (documentChanged) {
      const data = SlatePlainSerializer.serialize(value)
        // Because SlatePlainSerializer adds \n
        .replace(/\n/g, '')
        .split(',')
        .map(keyValue => {
          const [key, value] = keyValue.split(':').map(s => s.trim());
          const isEmpty = v => v == null || v === '';
          if (isEmpty(key) || isEmpty(value)) return null;
          return { key, value };
        })
        .filter(item => item != null)
        .map(item => {
          if (isNumeric(item.value))
            return { ...item, value: Number(item.value) };
          return item;
        })
        .reduce((data, current) => {
          return {
            ...data,
            [current.key]: current.value,
          };
        }, {});
      this.props.onChange(data);
    }
  };

  handleRenderNode = (props: Object) => {
    const { node, attributes, children } = props;
    switch (node.type) {
      case 'line': {
        return (
          <Text {...attributes} color="gray">
            {children}
          </Text>
        );
      }
    }
  };

  render() {
    const caretPosition = this.getCaretPosition();
    return (
      <Editor
        autoCorrect={false}
        spellCheck={false}
        value={this.state.editorValue}
        onFocus={this.handleEditorFocus}
        onKeyDown={this.handleEditorKeyDown}
        onChange={this.handleEditorChange}
        renderNode={this.handleRenderNode}
        className={`caret-position caret-position-${caretPosition}`}
      />
    );
  }
}

export default EditorData;
<commit_msg>Change EditorData separator<commit_after>// @flow
import * as React from 'react';
import { Editor } from 'slate-react';
import { Value } from 'slate';
import Text from './core/Text';
import SlatePlainSerializer from 'slate-plain-serializer';
import isNumeric from 'validator/lib/isNumeric';
import hotKey from '../browser/hotKey';

type EditorDataProps = {|
  defaultData: ?Object,
  onChange: (data: Object) => void,
|};

type EditorDataState = {|
  editorValue: Object,
|};

const separator = ';';

class EditorData extends React.PureComponent<EditorDataProps, EditorDataState> {
  static mapDataToEditorValue(data: Object) {
    const text = Object.keys(data)
      .map(key => {
        const value = data[key];
        return `${key}: ${value}`;
      })
      .join(`${separator} `);
    // TODO: Consider keys and values model. Plain text is ok for now.
    return Value.fromJSON({
      document: {
        nodes: [
          {
            object: 'block',
            type: 'line',
            nodes: [{ object: 'text', leaves: [{ text }] }],
          },
        ],
      },
    });
  }

  state = {
    editorValue: EditorData.mapDataToEditorValue(this.props.defaultData || {}),
  };

  getCaretPosition(): string {
    const { editorValue: value } = this.state;
    if (!value.selection.isCollapsed) return '';
    if (value.selection.focus.isAtStartOfNode(value.document)) return 'start';
    if (value.selection.focus.isAtEndOfNode(value.document)) return 'end';
    return '';
  }

  handleEditorFocus = (event: any, change: Object) => {
    // https://github.com/ianstormtaylor/slate/issues/1989
    change.focus();
  };

  handleEditorKeyDown = (event: KeyboardEvent) => {
    const { mod, key } = hotKey(event);
    if (key === 'Enter') {
      // Do nothing on enter. It's line.
      event.preventDefault();
      return true;
    }
    if (!mod) return;
    if (key === 'y' || key === 'z') {
      // Prevent default browser history action.
      event.preventDefault();
    }
    if (key === 'ArrowLeft' || key === 'ArrowRight') {
      // Prevent default browser history action.
      event.stopPropagation();
    }
  };

  handleEditorChange = ({ value }: { value: Object }) => {
    this.setState({ editorValue: value });
    const documentChanged = value.document !== this.state.editorValue.document;
    if (documentChanged) {
      const data = SlatePlainSerializer.serialize(value)
        // Because SlatePlainSerializer adds \n
        .replace(/\n/g, '')
        .split(separator)
        .map(keyValue => {
          const [key, value] = keyValue.split(':').map(s => s.trim());
          const isEmpty = v => v == null || v === '';
          if (isEmpty(key) || isEmpty(value)) return null;
          return { key, value };
        })
        .filter(item => item != null)
        .map(item => {
          if (isNumeric(item.value))
            return { ...item, value: Number(item.value) };
          return item;
        })
        .reduce((data, current) => {
          return {
            ...data,
            [current.key]: current.value,
          };
        }, {});
      this.props.onChange(data);
    }
  };

  handleRenderNode = (props: Object) => {
    const { node, attributes, children } = props;
    switch (node.type) {
      case 'line': {
        return (
          <Text {...attributes} color="gray">
            {children}
          </Text>
        );
      }
    }
  };

  render() {
    const caretPosition = this.getCaretPosition();
    return (
      <Editor
        autoCorrect={false}
        spellCheck={false}
        value={this.state.editorValue}
        onFocus={this.handleEditorFocus}
        onKeyDown={this.handleEditorKeyDown}
        onChange={this.handleEditorChange}
        renderNode={this.handleRenderNode}
        className={`caret-position caret-position-${caretPosition}`}
      />
    );
  }
}

export default EditorData;
<|endoftext|>


<commit_before>'use strict';

// Activities controller

var activityApp = angular.module('activities');

angular.module('activities').controller('ActivitiesController', ['$scope', '$stateParams', 'Authentication', 'Activities', '$modal', '$log',
	function($scope, $stateParams, Authentication, Activities, $modal, $log) {

		this.authentication = Authentication;

		// Find a list of Activities
		this.activities = Activities.query();

		// Open a modal window to Create a Activity Record
		this.modalCreate = function (size) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/create-activity.client.view.html',
	      controller: function ($scope, $modalInstance) {

				  $scope.ok = function () {

				  	// BUGFIX: Not working, Modal can not be closed when ok
				  	// if (createActivityForm.$valid) {
				    // 	$modalInstance.close();
				  	// }
				  	$modalInstance.close();

				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };
	      },
	      size: size,
	    });

	    modalInstance.result.then(function (selectedItem) {
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

		// Open a modal window to Update a Activity Record
		this.modalUpdate = function (size, selectedActivity) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/edit-activity.client.view.html',
	      controller: function ($scope, $modalInstance, activity) {
	      	$scope.activity = activity;

			$scope.ok = function () {

			  	// BUGFIX: Not working, Modal can not be closed when ok
			  	// if (updateActivityForm.$valid) {
			    // 	$modalInstance.close($scope.activity);
			  	// }
			  	$modalInstance.close($scope.activity);

			};

			$scope.cancel = function () {
			    $modalInstance.dismiss('cancel');
			};
	      },
	      size: size,
	      resolve: {
	        activity: function () {
	          return selectedActivity;
	        }
	      }
	    });

	    modalInstance.result.then(function (selectedItem) {
	      $scope.selected = selectedItem;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

		// Open a modal window to Add an Activity Entry Record
		this.modalPush = function (size, selectedActivity) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/create-activity-entry.client.view.html',
	      controller: function ($scope, $modalInstance, activity) {
	      	$scope.activity = activity;

				  $scope.ok = function () {

				  	// BUGFIX: Not working, Modal can not be closed when ok
				  	// if (updateActivityForm.$valid) {
				    // 	$modalInstance.close($scope.activity);
				  	// }
				  	$modalInstance.close($scope.activity);

				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };
	      },
	      size: size,
	      resolve: {
	        activity: function () {
	          return selectedActivity;
	        }
	      }
	    });

	    modalInstance.result.then(function (selectedItem) {
	      $scope.selected = selectedItem;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

		// Open a modal window to Update an Activity Entry Record
		this.modalPushUpdate = function (size, selectedEntry, selectedActivity) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/edit-activity-entry.client.view.html',
	      controller: function ($scope, $modalInstance, entry, activity) {
	      	$scope.entry = entry;
	      	$scope.activity = activity;

				  $scope.ok = function () {

				  	// BUGFIX: Not working, Modal can not be closed when ok
				  	// if (updateActivityForm.$valid) {
				    // 	$modalInstance.close($scope.activity);
				  	// }
				  	$modalInstance.close($scope.entry);
				  	$modalInstance.close($scope.activity);

				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };
	      },
	      size: size,
	      resolve: {
	        entry: function () {
	          return selectedEntry;
	        },
	        activity: function() {
	          return selectedActivity;
	        }
	      }
	    });

	    modalInstance.result.then(function (selectedItem) {
	      $scope.selected = selectedItem;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

	  // Heat Map Data Object
	  var heatMapMonthStartSmDevice = new Date();
	  heatMapMonthStartSmDevice.setMonth(heatMapMonthStartSmDevice.getMonth()-4);
	  $scope.heatMapMonthStartSmDevice = heatMapMonthStartSmDevice;

	  var heatMapMonthStartXsDevice = new Date();
	  heatMapMonthStartXsDevice.setMonth(heatMapMonthStartXsDevice.getMonth()-2);
	  $scope.heatMapMonthStartXsDevice = heatMapMonthStartXsDevice;

	  $scope.heatMapDataObject = {};

		// Bar Chart
		$scope.options = {
		  chart: {
		      type: 'discreteBarChart',
		      height: 450,
		      margin : {
		          top: 20,
		          right: 20,
		          bottom: 60,
		          left: 55
		      },
		      x: function(d){return d.label;},
		      y: function(d){return d.value;},
		      showValues: false,
		      showXAxis: false,
		      transitionDuration: 0,
		      xAxis: {
		          axisLabel: 'entries',
		          axisLabelDistance: 500
		      },
		      yAxis: {
		          axisLabel: 'hours',
  						axisLabelDistance: 40
		      },
		      rotateLabels: 90
		  }
		};

		// Data Object for Bar Chart
    $scope.data = [
      {
        key: 'Cumulative Return',
        values: [ ]
      }
  	];

	  // Find existing Activity
		$scope.findOne = function() {
			$scope.activity = Activities.get({
				activityId: $stateParams.activityId
			});

			// Activity Data Object Callback Function
			$scope.activity.$promise.then(function(data) {
				for(var j in data.entries) {

					// Heat Map
					var timestamp = Date.parse(data.entries[j].entryDatePicker)/1000;
					$scope.heatMapDataObject[timestamp] = 1;

					// Bar Chart
					$scope.data[0].values.push({'label': data.entries[j].entryDatePicker.split('T')[0],'value':data.entries[j].entryDuration / 60 / 60 });
				}
			});
		};

	}
]);<commit_msg>Refactoring<commit_after>'use strict';

// Activities controller

var activityApp = angular.module('activities');

angular.module('activities').controller('ActivitiesController', ['$scope', '$stateParams', 'Authentication', 'Activities', '$modal', '$log',
	function($scope, $stateParams, Authentication, Activities, $modal, $log) {

		this.authentication = Authentication;

		// Find a list of Activities
		this.activities = Activities.query();

		// Open a modal window to Create a Activity Record
		this.modalCreate = function (size) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/create-activity.client.view.html',
	      controller: function ($scope, $modalInstance) {

				  $scope.ok = function () {

				  	// BUG: Not working, Modal can not be closed when ok
				  	// if (createActivityForm.$valid) {
				    // 	$modalInstance.close();
				  	// }
				  	$modalInstance.close();

				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };
	      },
	      size: size,
	    });

	    modalInstance.result.then(function (selectedItem) {
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

		// Open a modal window to Update a Activity Record
		this.modalUpdate = function (size, selectedActivity) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/edit-activity.client.view.html',
	      controller: function ($scope, $modalInstance, activity) {
	      	$scope.activity = activity;

			$scope.ok = function () {

			  	// BUG: Not working, Modal can not be closed when ok
			  	// if (updateActivityForm.$valid) {
			    // 	$modalInstance.close($scope.activity);
			  	// }
			  	$modalInstance.close($scope.activity);

			};

			$scope.cancel = function () {
			    $modalInstance.dismiss('cancel');
			};
	      },
	      size: size,
	      resolve: {
	        activity: function () {
	          return selectedActivity;
	        }
	      }
	    });

	    modalInstance.result.then(function (selectedItem) {
	      $scope.selected = selectedItem;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

		// Open a modal window to Add an Activity Entry Record
		this.modalPush = function (size, selectedActivity) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/create-activity-entry.client.view.html',
	      controller: function ($scope, $modalInstance, activity) {
	      	$scope.activity = activity;

				  $scope.ok = function () {

				  	// BUG: Not working, Modal can not be closed when ok
				  	// if (updateActivityForm.$valid) {
				    // 	$modalInstance.close($scope.activity);
				  	// }
				  	$modalInstance.close($scope.activity);

				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };
	      },
	      size: size,
	      resolve: {
	        activity: function () {
	          return selectedActivity;
	        }
	      }
	    });

	    modalInstance.result.then(function (selectedItem) {
	      $scope.selected = selectedItem;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

		// Open a modal window to Update an Activity Entry Record
		this.modalPushUpdate = function (size, selectedEntry, selectedActivity) {

	    var modalInstance = $modal.open({
	      templateUrl: 'modules/activities/views/edit-activity-entry.client.view.html',
	      controller: function ($scope, $modalInstance, entry, activity) {
	      	$scope.entry = entry;
	      	$scope.activity = activity;

				  $scope.ok = function () {

				  	// BUG: Not working, Modal can not be closed when ok
				  	// if (updateActivityForm.$valid) {
				    // 	$modalInstance.close($scope.activity);
				  	// }
				  	$modalInstance.close($scope.entry);
				  	$modalInstance.close($scope.activity);

				  };

				  $scope.cancel = function () {
				    $modalInstance.dismiss('cancel');
				  };
	      },
	      size: size,
	      resolve: {
	        entry: function () {
	          return selectedEntry;
	        },
	        activity: function() {
	          return selectedActivity;
	        }
	      }
	    });

	    modalInstance.result.then(function (selectedItem) {
	      $scope.selected = selectedItem;
	    }, function () {
	      $log.info('Modal dismissed at: ' + new Date());
	    });
	  };

	  // Heat Map Data Object
	  var heatMapMonthStartSmDevice = new Date();
	  heatMapMonthStartSmDevice.setMonth(heatMapMonthStartSmDevice.getMonth()-4);
	  $scope.heatMapMonthStartSmDevice = heatMapMonthStartSmDevice;

	  var heatMapMonthStartXsDevice = new Date();
	  heatMapMonthStartXsDevice.setMonth(heatMapMonthStartXsDevice.getMonth()-2);
	  $scope.heatMapMonthStartXsDevice = heatMapMonthStartXsDevice;

	  $scope.heatMapDataObject = {};

		// Bar Chart
		$scope.options = {
		  chart: {
		      type: 'discreteBarChart',
		      height: 450,
		      margin : {
		          top: 20,
		          right: 20,
		          bottom: 60,
		          left: 55
		      },
		      x: function(d){return d.label;},
		      y: function(d){return d.value;},
		      showValues: false,
		      showXAxis: false,
		      transitionDuration: 0,
		      xAxis: {
		          axisLabel: 'entries',
		          axisLabelDistance: 500
		      },
		      yAxis: {
		          axisLabel: 'hours',
  						axisLabelDistance: 40
		      },
		      rotateLabels: 90
		  }
		};

		// Data Object for Bar Chart
    $scope.data = [
      {
        key: 'Cumulative Return',
        values: [ ]
      }
  	];

	  // Find existing Activity
		$scope.findOne = function() {
			$scope.activity = Activities.get({
				activityId: $stateParams.activityId
			});

			// Activity Data Object Callback Function
			$scope.activity.$promise.then(function(data) {
				for(var j in data.entries) {

					// Heat Map
					var timestamp = Date.parse(data.entries[j].entryDatePicker)/1000;
					$scope.heatMapDataObject[timestamp] = 1;

					// Bar Chart
					// BUG: if key exists add value to existing one
					$scope.data[0].values.push({'label': data.entries[j].entryDatePicker.split('T')[0],'value':data.entries[j].entryDuration / 60 / 60 });
				}
			});
		};

	}
]);<|endoftext|>