<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */
/**
 * 'File' menu plugin
 * This plugs in the 'File' menu that is the container of menu items like New, Open, Save,
 * Close for notebooks
 */
define(function(require, exports, module) {
  'use strict';
  var fileMenuItems = [
    {
      name: "New Notebook",
      shortcut: ["Alt-N", "Ctrl-N"],
      sortorder: 100,
      id: "new-notebook-menuitem",
      action: function() {
        bkHelper.newSession(true);
      },
      tooltip: "Open a new empty notebook, add the languages of your choice"
    },
    {
      name: "New Default Notebook",
      shortcut: ["Alt-Shift-N", "Ctrl-Shift-N"],
      sortorder: 101,
      id: "new-notebook-menuitem",
      action: function() {
        bkHelper.newSession(false);
      },
      tooltip: "Open a new default notebook"
    },
    {
      name: "New Beaker window",
      sortorder: 105,
      id: "new-beaker-window-menuitem",
      action: function() {
        bkHelper.openWindow('/beaker', 'control-panel');
      },
      tooltip: "Open a new browser tab or window to work on more than one notebook at the same time"
    },
    {
      name: "Open recent",
      sortorder: 120,
      id: "open-recent-menuitem",
      items: function() {
        return bkHelper.getRecentMenuItems();
      }
    },
    {
      name: "Upload (.bkr)",
      id: "import-menuitem",
      sortorder: 125,
      action: bkHelper.importNotebookDialog
    },
    {
      name: "Save",
      shortcut: ["Ctrl-S", "Cmd-S"],
      id: "save-menuitem",
      sortorder: 130,
      action: function() {
        bkHelper.saveNotebook();
      }
    },
    {
      name: "Save as...",
      shortcut: ["Ctrl-Shift-S", "Cmd-Shift-S"],
      id: "save-as-menuitem",
      sortorder: 140,
      tooltip: "Save a file to file system",
      action: function() {
        if (bkHelper.isElectron){
          bkHelper.showElectronSaveDialog().then(function(path) {
            // Save cancelled
            if (path == undefined)
              return;
            return bkHelper.saveNotebookAs(path, 'file');
          })
        } else {
          bkHelper.showFileSaveDialog({
            extension: "bkr"
          }).then(function (ret) {
            if (ret.uri) {
              return bkHelper.saveNotebookAs(ret.uri, ret.uriType);
            }
          });
        }
      }
    },
    {
      name: "Publish...",
      sortorder: 145,
      id: "publish-menuitem",
      action: function () {
        bkHelper.showPublishForm();
      },
      tooltip: "Publish the notebook to Beaker Publications"
    },
    {
      name: "Close",
      id: "close-menuitem",
      sortorder: 160,
      action: function() {
        bkHelper.closeNotebook();
      }
    }
  ];

  var menuItemPromise = bkHelper.newPromise({
    parent: "File",
    id: "file-menu",
    items: fileMenuItems
  });

  exports.getMenuItems = function() {
    return menuItemPromise;
  };
});
<commit_msg>issue #4862 "save-as opens save dialog twice"<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */
/**
 * 'File' menu plugin
 * This plugs in the 'File' menu that is the container of menu items like New, Open, Save,
 * Close for notebooks
 */
define(function(require, exports, module) {
  'use strict';
  var fileMenuItems = [
    {
      name: "New Notebook",
      shortcut: ["Alt-N", "Ctrl-N"],
      sortorder: 100,
      id: "new-notebook-menuitem",
      action: function() {
        bkHelper.newSession(true);
      },
      tooltip: "Open a new empty notebook, add the languages of your choice"
    },
    {
      name: "New Default Notebook",
      shortcut: ["Alt-Shift-N", "Ctrl-Shift-N"],
      sortorder: 101,
      id: "new-notebook-menuitem",
      action: function() {
        bkHelper.newSession(false);
      },
      tooltip: "Open a new default notebook"
    },
    {
      name: "New Beaker window",
      sortorder: 105,
      id: "new-beaker-window-menuitem",
      action: function() {
        bkHelper.openWindow('/beaker', 'control-panel');
      },
      tooltip: "Open a new browser tab or window to work on more than one notebook at the same time"
    },
    {
      name: "Open recent",
      sortorder: 120,
      id: "open-recent-menuitem",
      items: function() {
        return bkHelper.getRecentMenuItems();
      }
    },
    {
      name: "Upload (.bkr)",
      id: "import-menuitem",
      sortorder: 125,
      action: bkHelper.importNotebookDialog
    },
    {
      name: "Save",
      shortcut: ["Ctrl-S", "Cmd-S"],
      id: "save-menuitem",
      sortorder: 130,
      action: function() {
        bkHelper.saveNotebook();
      }
    },
    {
      name: "Save as...",
      shortcut: ["Ctrl-Shift-S", "Cmd-Shift-S"],
      id: "save-as-menuitem",
      sortorder: 140,
      tooltip: "Save a file to file system",
      action: function() {
        if (bkHelper.isElectron){
          bkHelper.showElectronSaveDialog().then(function(path) {
            // Save cancelled
            if (path == undefined)
              return;
            return bkHelper.saveNotebookAs(path, 'file');
          })
        } else {
          return bkHelper.saveNotebookAs();
        }
      }
    },
    {
      name: "Publish...",
      sortorder: 145,
      id: "publish-menuitem",
      action: function () {
        bkHelper.showPublishForm();
      },
      tooltip: "Publish the notebook to Beaker Publications"
    },
    {
      name: "Close",
      id: "close-menuitem",
      sortorder: 160,
      action: function() {
        bkHelper.closeNotebook();
      }
    }
  ];

  var menuItemPromise = bkHelper.newPromise({
    parent: "File",
    id: "file-menu",
    items: fileMenuItems
  });

  exports.getMenuItems = function() {
    return menuItemPromise;
  };
});
<|endoftext|>


<commit_before>function(doc) {
  if (doc.speed != 0) {
    var intervals = [3600 * 24, 3600 * 6, 3600, 1800, 600, 60]
    var value = parseInt(doc.speed / 0.5) * 0.5
    var keys = []

    for (var i in intervals) {
      keys.push(new Date(parseInt(doc.time / intervals[i]) * intervals[i] * 1000))
      keys.push(value)
    }
    var d = keys[0]

    emit([
      doc.anemometerId,
      new Date(d.getUTCFullYear(),d.getMonth(), 1),
      value
    ].concat(keys), 1);
  }
}
<commit_msg>updated frequency view with commonjs module<commit_after>function(doc) {
  emit(require('views/lib/utils').generateKeys(doc.anemometerId, doc), 1)
}
<|endoftext|>


<commit_before>var walkSync = require('walk-sync');
var Petal = require('petal');
var fs = require('fs');
var writeFile = require('broccoli-file-creator');

module.exports = StubGenerator;

function StubGenerator(inputTree, modules) {
  if (!(this instanceof StubGenerator)) {
    return new StubGenerator(inputTree, modules);
  }
  this.inputTree = inputTree;
  this.modules = modules;
  this.stubs = {};
}

StubGenerator.prototype.cleanup = function(){};

StubGenerator.prototype.read = function(readTree) {
  var self = this;
  return readTree(this.inputTree).then(function(srcDir){
    var paths = walkSync(srcDir);
    paths.forEach(function (relativePath) {
      if (relativePath.slice(-3) === '.js') {
        var petal = new Petal(relativePath, fs.readFileSync(srcDir + '/' + relativePath));
        Object.keys(petal.imports).forEach(function(key){
          if (key.slice(0,4) === 'npm:') {
            var moduleName = key.slice(4);
            self.modules[moduleName] = [ 'default' ];
            self.stubs[moduleName] = true;
          }
        });
      }
    });
    return writeFile('browserify_stubs.js', self.generate()).read(readTree);
  });
};

StubGenerator.prototype.generate = function() {
  return Object.keys(this.stubs).map(function(moduleName){
    return "define('npm:" +
      moduleName +
      "', function(){ return require('" +
      moduleName +
      "');})";
  }).join("\n");
};
<commit_msg>use default export<commit_after>var walkSync = require('walk-sync');
var Petal = require('petal');
var fs = require('fs');
var writeFile = require('broccoli-file-creator');

module.exports = StubGenerator;

function StubGenerator(inputTree, modules) {
  if (!(this instanceof StubGenerator)) {
    return new StubGenerator(inputTree, modules);
  }
  this.inputTree = inputTree;
  this.modules = modules;
  this.stubs = {};
}

StubGenerator.prototype.cleanup = function(){};

StubGenerator.prototype.read = function(readTree) {
  var self = this;
  return readTree(this.inputTree).then(function(srcDir){
    var paths = walkSync(srcDir);
    paths.forEach(function (relativePath) {
      if (relativePath.slice(-3) === '.js') {
        var petal = new Petal(relativePath, fs.readFileSync(srcDir + '/' + relativePath));
        Object.keys(petal.imports).forEach(function(key){
          if (key.slice(0,4) === 'npm:') {
            var moduleName = key.slice(4);
            self.modules[moduleName] = [ 'default' ];
            self.stubs[moduleName] = true;
          }
        });
      }
    });
    return writeFile('browserify_stubs.js', self.generate()).read(readTree);
  });
};

StubGenerator.prototype.generate = function() {
  return Object.keys(this.stubs).map(function(moduleName){
    return "define('npm:" +
      moduleName +
      "', function(){ return { default: require('" +
      moduleName +
      "')};})";
  }).join("\n");
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
import '../../server/env';

import { assign, get, isArray, pick } from 'lodash';
import PQueue from 'p-queue';

import cache from '../../server/lib/cache';
import * as github from '../../server/lib/github';
import logger from '../../server/lib/logger';
import models, { Op } from '../../server/models';

const { Collective } = models;

const CONCURRENCY = 2;

// TODO: As number of collectives grow, we need to consider fetching 100 at a time,
// otherwise, we end up fetching a lot of data.
// Note: Picking attributes doesn't work with Histories table because Histories
// ends up recording on the attributes that were pulled out

const noContentToArray = value => (isArray(value) ? value : []);

const sortObjectByValue = (obj, path) => {
  const sortable = [];
  for (const key in obj) {
    sortable.push([key, obj[key], path ? get(obj[key], path) : obj[key]]);
  }

  sortable.sort((a, b) => {
    return a[2] > b[2] ? -1 : a[2] < b[2] ? 1 : 0;
  });

  const orderedList = {};
  for (let i = 0; i < sortable.length; i++) {
    orderedList[sortable[i][0]] = sortable[i][1];
  }

  return orderedList;
};

const getAllContributors = async repo => {
  const cacheKey = `repos_contributors_${repo.owner}_${repo.repo}`;
  const fromCache = await cache.get(cacheKey);
  if (fromCache) {
    return fromCache;
  }

  const octokit = github.getOctokit();

  const fetchParameters = { page: 1, per_page: 100 }; // eslint-disable-line camelcase

  let contributors = [];
  let fetchContributors;
  do {
    // https://octokit.github.io/rest.js/v18#repos-list-contributors
    // https://developer.github.com/v3/repos/#list-contributors
    logger.verbose(`Fetching contributors for ${repo.owner}/${repo.repo}, page ${fetchParameters.page}`);
    fetchContributors = await octokit.repos
      .listContributors({ ...repo, ...fetchParameters })
      .then(github.getData)
      .then(noContentToArray)
      .then(c => c.map(repo => pick(repo, ['login', 'contributions'])));
    contributors = [...contributors, ...fetchContributors];
    fetchParameters.page++;
  } while (fetchContributors.length === fetchParameters.per_page);

  cache.set(cacheKey, contributors, 60 * 60 /* 60 minutes */);

  return contributors;
};

const getRepoData = repo => {
  logger.verbose(`Fetching repo data for ${repo.owner}/${repo.repo}`);
  return getAllContributors(repo).then(contributors => {
    const contributorData = {};
    for (const contributor of contributors) {
      contributorData[contributor.login] = contributor.contributions;
    }
    return { contributorData };
  });
};

const getOrgData = org => {
  logger.verbose(`Fetching org data for ${org}`);
  return github.getAllOrganizationPublicRepos(org).then(async repos => {
    const contributorData = {};
    const repoData = {};
    for (const repo of repos) {
      if (repo.fork) {
        continue;
      }
      const contributors = await getAllContributors({ owner: repo.owner.login, repo: repo.name });
      for (const contributor of contributors) {
        if (contributorData[contributor.login]) {
          contributorData[contributor.login] += contributor.contributions;
        } else {
          contributorData[contributor.login] = contributor.contributions;
        }
      }
      repoData[repo.name] = { stars: repo.stargazers_count };
    }
    return { contributorData, repoData };
  });
};

const updateCollectiveGithubData = async (collective, githubData) => {
  const data = assign(collective.data || {}, {
    githubContributors: sortObjectByValue(githubData.contributorData),
  });

  if (githubData.repoData) {
    data.repos = sortObjectByValue(githubData.repoData, 'stars');
  }

  await collective.update({ data });

  logger.info(`Successfully updated contribution data for '${collective.name}'`);
};

const run = async () => {
  const queue = new PQueue({ concurrency: CONCURRENCY });

  let collectives = await Collective.findAll({
    where: {
      type: 'COLLECTIVE',
      deactivatedAt: { [Op.is]: null },
    },
    order: [['createdAt', 'DESC']],
  });

  logger.info(`Found ${collectives.length} total collective(s)`);

  collectives = collectives.filter(
    collective =>
      get(collective, 'settings.githubOrg') || get(collective, 'settings.githubRepo') || collective.githubHandle,
  );

  logger.info(`Found ${collectives.length} collective(s) with GitHub settings`);

  for (const collective of collectives) {
    let org = get(collective, 'settings.githubOrg');
    let repo = get(collective, 'settings.githubRepo');

    if (collective.githubHandle) {
      if (collective.githubHandle.includes('/')) {
        repo = collective.githubHandle;
      } else {
        org = collective.githubHandle;
      }
    }

    if (org) {
      queue
        .add(() => getOrgData(org).then(data => updateCollectiveGithubData(collective, data)))
        .catch(e => {
          logger.error(`Error while fetching org data for collective '${collective.slug}'`);
          logger.debug(e);
        });
    } else {
      const split = repo.split('/');
      if (split.length !== 2) {
        logger.warn(collective.name, 'Incorrect format of githubRepo');
        continue;
      }
      const options = {
        owner: split[0],
        repo: split[1],
      };
      queue
        .add(() => getRepoData(options).then(data => updateCollectiveGithubData(collective, data)))
        .catch(e => {
          logger.error(`Error while fetching ${options.owner}/${options.repo} for collective '${collective.slug}'`);
          logger.debug(e);
        });
    }
  }

  queue.onIdle().then(() => {
    logger.info('Done.');
    process.exit();
  });
};

run();
<commit_msg>remove "update-contributions" daily cron<commit_after><|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var Couve = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('Couve', () => Couve);
<commit_msg>Update index.android.js<commit_after>'use strict'

var React = require('react-native')
var Mapbox = require('react-native-mapbox-gl')
var secrets = require('./secrets')
var mapRef = 'mapRef'

var {
  AppRegistry,
  StyleSheet,
  View
} = React

var Couve = React.createClass({
  mixins: [Mapbox.Mixin],

  getInitialState () {
    return {
      center: {
        latitude: -26.4537736,
        longitude: -49.1179425
      },
      zoom: 15
    }
  },

  onRegionChange (location) {
    this.setState({ currentZoom: location.zoom })
  },

  onRegionWillChange (location) {
    console.log(location)
  },

  onUpdateUserLocation (location) {
    console.log(location)
  },

  onLongPress (location) {
    console.log('Long pressed', location)
  },

  render: function () {
    StatusBarIOS.setHidden(true)
    return (
      <View style={styles.container}>
        <Mapbox
          style={styles.map}
          direction={0}
          rotateEnabled={true}
          scrollEnabled={true}
          zoomEnabled={true}
          showsUserLocation={true}
          ref={mapRef}
          accessToken={secrets.development.mapboxToken}
          styleURL={this.mapStyles.emerald}
          userTrackingMode={this.userTrackingMode.none}
          centerCoordinate={this.state.center}
          zoomLevel={this.state.zoom}
          onRegionChange={this.onRegionChange}
          onRegionWillChange={this.onRegionWillChange}
          onUpdateUserLocation={this.onUpdateUserLocation}
          onLongPress={this.onLongPress}
        />
      </View>
    )
  }
})

var styles = StyleSheet.create({
  container: {
    flex: 1
  },
  map: {
    flex: 1
  }
})

AppRegistry.registerComponent('Couve', () => Couve)
<|endoftext|>


<commit_before>import React,  { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  Button,
  Image,
  TouchableHighlight
} from 'react-native';
import Realm from 'realm';
import SortableListView from 'react-native-sortable-listview';
import Utils from './src/utils';
import Repository from './src/Repository';
import {DateOnly} from './src/util/time';
import DayModel from './src/DayModel';
import DayBadge from './src/components/DayBadge';

import SixBus from './src/global/SixBus';
import SixController from './src/global/SixController';

import Icon from 'react-native-vector-icons/Ionicons';
import moment from 'moment';

export class RowComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editing: false,
      text: props.data.description,
    }
    this.saveDescription = this.saveDescription.bind(this);
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      text: nextProps.data.description
    });
  }
  saveDescription() {
    this.props.saveDesc(this.props.data, this.state.text);
    this.setState({editing: false});
  }
  render() {
    let task = this.props.data;

    return (
      <View style={styles.itemWrapper}>
        {this.state.editing ?
          <View style={styles.edit}>
            <TextInput
              style={styles.editText}
              value={this.state.text}
              blurOnSubmit={true}
              autoFocus={true}
              autoCapitalize={'sentences'}
              onBlur={this.saveDescription}
              onEndEditing={this.saveDescription}
              onChangeText={(text) => this.setState({text})} />
            <TouchableHighlight
              underlayColor={'#F5FCFF'}
              onPress={this.saveDescription}
            >
              <Icon name="md-close" style={styles.editIcon} />
            </TouchableHighlight>
          </View> :

          <View style={styles.item}>
            <TouchableHighlight
              style={{flex:1}}
              underlayColor={'#F5FCFF'}
              onPress={() => {
                this.props.toggle();
                this.forceUpdate();
              }}
              delayLongPress={100}
              {...this.props.sortHandlers}
            >
              <View
            style={{flex:1, flexDirection: 'row'}}
              >
                {task.completed ?
                <Icon name="ios-checkmark-circle" style={styles.itemIcon} /> :
                <Icon name="ios-checkmark-circle-outline" style={styles.itemIcon} />
                }
                <Text style={styles.itemText}>{task.description}</Text>
              </View>
            </TouchableHighlight>
            <TouchableHighlight
              style={styles.editIconWrapper}
              underlayColor={'#F5FCFF'}
              onPress={() => {
                this.setState({editing: true});
              }}
            >
              <Icon name="md-create" style={styles.editIcon} />
            </TouchableHighlight>
          </View>
        }

      </View>
    );
  }
}

export default class Six extends Component {
  constructor() {
    super();
    this.repository = new Repository();
    this.bus = new SixBus();
    this.controller = new SixController(this.bus);

    this.state = {
      days: this.repository.get('Day'),
      currDay: this.repository.get('Day')[0],
      tasks: this.repository.get('Task')
    }
  }

  render() {
    var _scrollView: ScrollView;

    return (
      <View style={styles.container}>
        <ScrollView
          ref={(scrollView) => { _scrollView = scrollView; }}
          automaticallyAdjustContentInsets={false}
          horizontal={true}
          style={styles.scrollView}>
          {this.state.days.map((day, i) => <DayBadge key={i} day={day} setDay={this.setCurrentDay.bind(this, i)}/>)}
        </ScrollView>

        <Text style={styles.welcome}>Day: {this.state.currDay.date.toDateString()}</Text>
        <SortableListView
          style={{flex: 3}}
          data={this.state.currDay.tasks}
          onRowMoved={e => {
            this.repository.move(this.state.currDay, e.from, e.to);
          }}
          renderRow={row => <RowComponent data={row}
                              toggle={() => this.repository.toggleTaskCompleted(row)}
                              saveDesc={(task, desc) => this.repository.updateTaskDescription(task, desc)} />}
        />
      </View>
    );
  }
  setCurrentDay(ix) {
    this.setState({
      currDay: this.repository.get('Day')[ix]
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button: {
    color: '#841584'
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  scrollView: {
    marginTop: 20,
    flex: 10,
    maxHeight: 128
  },
  horizontalScrollView: {
    height: 50,
  },
  block: {
    flex: 1,
    margin: 8,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center'
  },
  itemWrapper: {
    flex: 1,
    alignSelf: 'stretch',
    paddingVertical: 5,
  },
  item: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  itemIcon: {
    fontSize: 40,
    color: '#6A85B1',
    marginHorizontal: 5,
    width: 30,
  },
  itemText: {
    fontSize: 32,
    flex: 1,
  },
  edit: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  editText: {
    fontSize: 32,
    flex: 1,
    maxHeight: 50,
  },
  editIconWrapper: {
    flex:1,
    maxWidth: 45,
    paddingHorizontal: 5,
  },
  editIcon: {
    fontSize: 40,
    color: '#6A85B1',
    marginHorizontal: 5,
    width: 30,
  },
});

AppRegistry.registerComponent('Six', () => Six);
<commit_msg>Restyle item edit icon to be more subtle<commit_after>import React,  { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  Button,
  Image,
  TouchableHighlight
} from 'react-native';
import Realm from 'realm';
import SortableListView from 'react-native-sortable-listview';
import Utils from './src/utils';
import Repository from './src/Repository';
import {DateOnly} from './src/util/time';
import DayModel from './src/DayModel';
import DayBadge from './src/components/DayBadge';

import SixBus from './src/global/SixBus';
import SixController from './src/global/SixController';

import Icon from 'react-native-vector-icons/Ionicons';
import moment from 'moment';

export class RowComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editing: false,
      text: props.data.description,
    }
    this.saveDescription = this.saveDescription.bind(this);
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      text: nextProps.data.description
    });
  }
  saveDescription() {
    this.props.saveDesc(this.props.data, this.state.text);
    this.setState({editing: false});
  }
  render() {
    let task = this.props.data;

    return (
      <View style={styles.itemWrapper}>
        {this.state.editing ?
          <View style={styles.edit}>
            <TextInput
              style={styles.editText}
              value={this.state.text}
              blurOnSubmit={true}
              autoFocus={true}
              autoCapitalize={'sentences'}
              onBlur={this.saveDescription}
              onEndEditing={this.saveDescription}
              onChangeText={(text) => this.setState({text})} />
            <TouchableHighlight
              underlayColor={'#F5FCFF'}
              onPress={this.saveDescription}
            >
              <Icon name="md-close" style={styles.editIcon} />
            </TouchableHighlight>
          </View> :

          <View style={styles.item}>
            <TouchableHighlight
              style={{flex:1}}
              underlayColor={'#F5FCFF'}
              onPress={() => {
                this.props.toggle();
                this.forceUpdate();
              }}
              delayLongPress={100}
              {...this.props.sortHandlers}
            >
              <View
            style={{flex:1, flexDirection: 'row'}}
              >
                {task.completed ?
                <Icon name="ios-checkmark-circle" style={styles.itemIcon} /> :
                <Icon name="ios-checkmark-circle-outline" style={styles.itemIcon} />
                }
                <Text style={styles.itemText}>{task.description}</Text>
              </View>
            </TouchableHighlight>
            <TouchableHighlight
              style={styles.editIconWrapper}
              underlayColor={'#F5FCFF'}
              onPress={() => {
                this.setState({editing: true});
              }}
            >
              <Icon name="md-create" style={styles.editIcon} />
            </TouchableHighlight>
          </View>
        }

      </View>
    );
  }
}

export default class Six extends Component {
  constructor() {
    super();
    this.repository = new Repository();
    this.bus = new SixBus();
    this.controller = new SixController(this.bus);

    this.state = {
      days: this.repository.get('Day'),
      currDay: this.repository.get('Day')[0],
      tasks: this.repository.get('Task')
    }
  }

  render() {
    var _scrollView: ScrollView;

    return (
      <View style={styles.container}>
        <ScrollView
          ref={(scrollView) => { _scrollView = scrollView; }}
          automaticallyAdjustContentInsets={false}
          horizontal={true}
          style={styles.scrollView}>
          {this.state.days.map((day, i) => <DayBadge key={i} day={day} setDay={this.setCurrentDay.bind(this, i)}/>)}
        </ScrollView>

        <Text style={styles.welcome}>Day: {this.state.currDay.date.toDateString()}</Text>
        <SortableListView
          style={{flex: 3}}
          data={this.state.currDay.tasks}
          onRowMoved={e => {
            this.repository.move(this.state.currDay, e.from, e.to);
          }}
          renderRow={row => <RowComponent data={row}
                              toggle={() => this.repository.toggleTaskCompleted(row)}
                              saveDesc={(task, desc) => this.repository.updateTaskDescription(task, desc)} />}
        />
      </View>
    );
  }
  setCurrentDay(ix) {
    this.setState({
      currDay: this.repository.get('Day')[ix]
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button: {
    color: '#841584'
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  scrollView: {
    marginTop: 20,
    flex: 10,
    maxHeight: 128
  },
  horizontalScrollView: {
    height: 50,
  },
  block: {
    flex: 1,
    margin: 8,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center'
  },
  itemWrapper: {
    flex: 1,
    alignSelf: 'stretch',
    paddingVertical: 5,
  },
  item: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  itemIcon: {
    fontSize: 40,
    color: '#6A85B1',
    marginHorizontal: 5,
    width: 30,
  },
  itemText: {
    fontSize: 32,
    flex: 1,
  },
  edit: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  editText: {
    fontSize: 32,
    flex: 1,
    maxHeight: 50,
  },
  editIconWrapper: {
    flex:1,
    maxWidth: 45,
    paddingHorizontal: 5,
  },
  editIcon: {
    fontSize: 30,
    color: '#CCC',
    marginHorizontal: 10,
    width: 30,
  },
});

AppRegistry.registerComponent('Six', () => Six);
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var { AppRegistry, StyleSheet, TouchableOpacity, Text, View } = React;
var moment = require('moment');
var _ = require('lodash');

class Timer extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>
          {this.state.timeElpased}
        </Text>
        <View style={styles.buttonContainer}>
          <TouchableOpacity onPress={this._onAction('stop')} style={styles.button}>
            <Text style={{ textAlign: 'center' }}>
              Stop
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={[styles.button, { backgroundColor: '#9ED795' }]}>
            <Text style={{ textAlign: 'center' }}>
              Start
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  _onAction(type) {
    return (ev) => {
      this['_onAction' + _.capitalize(type)](ev);
    };
  }

  _onActionStop(ev) {
    clearInterval(this.timer);
  }

  componentDidMount() {
    this._startCountingSeconds();
  }

  _startCountingSeconds() {
    this.timer = setInterval(() => {
      this._secondHasPassed();
    }, 1000);
  }

  _secondHasPassed() {
    this.duration.add(1, 'second');
    this.setState({
      timeElpased: this._formatTime()
    });
  }

  _formatTime() {
    return `${this.duration.minutes()} : ${this.duration.seconds()}`;
  }

  constructor(props) {
    super(props);
    this.duration = moment.duration();
    this.state = {
      timeElpased: this._formatTime()
    };
  }
};

var styles = StyleSheet.create({
  button: {
    padding: 10,
    fontSize: 20,
    backgroundColor: '#E4555F',
  },
  buttonContainer: {
    width: 100,
    margin: 5
  },
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('timer', () => Timer);
<commit_msg>ability to start the timer<commit_after>'use strict';

var React = require('react-native');
var { AppRegistry, StyleSheet, TouchableOpacity, Text, View } = React;
var moment = require('moment');
var _ = require('lodash');

class Timer extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>
          {this.state.timeElpased}
        </Text>
        <View style={styles.buttonContainer}>
          <TouchableOpacity onPress={this._onAction('stop')} style={styles.button}>
            <Text style={{ textAlign: 'center' }}>
              Stop
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            onPress={this._onAction('start')}
            style={[styles.button, { backgroundColor: '#9ED795' }]}>
            <Text style={{ textAlign: 'center' }}>
              Start
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  _onAction(type) {
    return (ev) => {
      this['_onAction' + _.capitalize(type)](ev);
    };
  }

  _onActionStart(ev) {
    this._startCountingSeconds();
  }

  _onActionStop(ev) {
    clearInterval(this.timer);
  }

  componentDidMount() {
    this._startCountingSeconds();
  }

  _startCountingSeconds() {
    this.timer = setInterval(() => {
      this._secondHasPassed();
    }, 1000);
  }

  _secondHasPassed() {
    this.duration.add(1, 'second');
    this.setState({
      timeElpased: this._formatTime()
    });
  }

  _formatTime() {
    return `${this.duration.minutes()} : ${this.duration.seconds()}`;
  }

  constructor(props) {
    super(props);
    this.duration = moment.duration();
    this.state = {
      timeElpased: this._formatTime()
    };
  }
};

var styles = StyleSheet.create({
  button: {
    padding: 10,
    fontSize: 20,
    backgroundColor: '#E4555F',
  },
  buttonContainer: {
    width: 100,
    margin: 5
  },
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('timer', () => Timer);
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var module = require('RCTRealtimeMessagingAndroid');
var RCTRealtimeMessaging = new module();

var messages = [];

var {
  AppRegistry,
  Image,
  StyleSheet,
  Text,
  Navigator,
  TextInput,
  ScrollView,
  TouchableHighlight,
  ListView,
  View
} = React;

var RealtimeRCT = React.createClass({

  doConnect: function(){
    this._log('Trying to connect!');

    RCTRealtimeMessaging.RTEventListener("onConnected",this._onConnected),
    RCTRealtimeMessaging.RTEventListener("onDisconnected",this._onDisconnected),
    RCTRealtimeMessaging.RTEventListener("onSubscribed",this._onSubscribed),
    RCTRealtimeMessaging.RTEventListener("onUnSubscribed",this._onUnSubscribed),
    RCTRealtimeMessaging.RTEventListener("onException",this._onException),
    RCTRealtimeMessaging.RTEventListener("onMessage",this._onMessage),
    RCTRealtimeMessaging.RTEventListener("onPresence",this._onPresence);

    RCTRealtimeMessaging.RTConnect(
    {
      appKey:this.state.appKey,
      token:this.state.token,
      connectionMetadata:this.state.connectionMetadata,
      clusterUrl:this.state.clusterUrl,
      projectId:'<YOUR_GOOGLE_PROJECT_NUMBER>'
    });
  },

  componentDidMount: function(){
    RCTRealtimeMessaging.RTPushNotificationListener(this._onNotification);
  },

  componentWillUnmount: function() {
    RCTRealtimeMessaging.RTDisconnect();
  },

  doDisconnect:function(){
    RCTRealtimeMessaging.RTDisconnect();
  },

  doSubscribe: function(){
    RCTRealtimeMessaging.RTSubscribeWithNotifications(this.state.channel, true);
  },

  doUnSubscribe: function(){
    RCTRealtimeMessaging.RTUnsubscribe(this.state.channel);
  },

  doSendMessage: function(){
    RCTRealtimeMessaging.RTSendMessage(this.state.message, this.state.channel);
  },

  doPresence: function(){
    RCTRealtimeMessaging.RTPresence(
       this.state.channel
     );
  },

  _onException: function(exceptionEvent){
    this._log("Exception:" + exceptionEvent.error);
  },

  _onConnected: function()
  {
    this._log("Connected");
  },

  _onDisconnected: function(){
    this._log("Disconnected");
  },

  _onSubscribed: function(subscribedEvent)
  {
    this._log("Subscribed channel " + subscribedEvent.channel);
  },

  _onUnSubscribed: function(unSubscribedEvent)
  {
    this._log("Unsubscribed channel " + unSubscribedEvent.channel);
  },

  _onNotification: function(data)
  {
    this._log("Received notification: " + JSON.stringify(data));
  },

  _onMessage: function(messageEvent)
  {
    this._log("Received message: ["+messageEvent.message+"] on channel [" + messageEvent.channel+"]");
  },

  _onPresence: function(presenceEvent){
    if (presenceEvent.error) {
      this._log("Error getting presence: " + presenceEvent.error);
    }else
    {
      this._log("Presence data: " + JSON.stringify(presenceEvent.result));
    };
  },

  getInitialState: function() {
    return {
      clusterUrl: "http://ortc-developers.realtime.co/server/2.1/",
      token: "SomeAuthenticatedToken",
      appKey: "YOUR_REALTIME_APPKEY",
      channel: "CHANNEL",
      connectionMetadata: "ReactNative Example",
      message: "This is the message",
      topWidth:0,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  },

  _renderRow: function(rowData: string, sectionID: number, rowID: number) {
    return (
      <TouchableHighlight>
        <View>
          <View style={styles.row}>
            <Text style={styles.text}>
              {rowData}
            </Text>
          </View>
          <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    );
  },

  _log: function(message: string)
  {
    var time = this.getFormattedDate();
    time += " - " + message
    var temp = [];
    temp[0] = time;

    for (var i = 0; i < messages.length; i++) {
      temp[i+1] =  messages[i];
    };
    messages = temp;

    this.setState({
      dataSource: this.getDataSource(messages)
    });
  },

  getFormattedDate: function() {
    var date = new Date();
    var str = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return str;
  },

  getDataSource: function(messages: Array<any>): ListView.DataSource {
    return this.state.dataSource.cloneWithRows(messages);
  },

  render: function() {
    return (
      <ScrollView style={styles.container}>

        <Text clusterUrl = {this.state.clusterUrl} >
            clusterUrl:
        </Text>
        <TextInput
          style={styles.textInput}
          placeholder={this.state.clusterUrl}
          onChangeText={(text) => this.setState({server: text})}
        />

        <View style={styles.custom}>
          <View style={styles.margin}>
            <Text server = {this.state.server} >
                Authentication Token:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.token}
              onChangeText={(text) => this.setState({token: text})}
            />

            <Text server = {this.state.server} >
                Application Key:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.appKey}
              onChangeText={(text) => this.setState({appKey: text})}
            />
          </View>

          <View style={styles.margin}>
            <Text server = {this.state.server} >
                Channel:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.channel}
              onChangeText={(text) => this.setState({channel: text})}
            />

            <Text server = {this.state.server} >
                Connection Metadata:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.connectionMetadata}
              onChangeText={(text) => this.setState({connectionMetadata: text})}
            />
          </View>

        </View>
        <Text server = {this.state.server} >
            Message:
        </Text>
        <TextInput
          style={styles.textInput}
          placeholder={this.state.message}
          onChangeText={(text) => this.setState({message: text})}
        />

        <View style={styles.rowView}>

          <TouchableHighlight style={styles.button} onPress={this.doConnect}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Connect</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doDisconnect}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Disconnect</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doSubscribe}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Subscribe</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doUnSubscribe}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Unsubscribe</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doSendMessage}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Send</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doPresence}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Presence</Text>
            </View>
          </TouchableHighlight>

        </View>
        <ListView
          style={styles.list}
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
        />
      </ScrollView>

    )}
  });

var styles = StyleSheet.create({
  container: {
    marginTop: 30,
    margin: 5,
    backgroundColor: '#FFFFFF',
  },
  list: {
    flexDirection: 'column',
    backgroundColor: '#F6F6F6',
    height:150,
  },
  rowView:{
    alignItems: 'stretch',
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent:'center',
  },
  button:{
    margin: 5,
  },
  margin:{

  },
  custom:{
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent:'space-between',
  },
  textInput:{
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    borderRadius: 4,
    padding: 5,
    fontSize: 15,
  },

  halfTextInput:{
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    borderRadius: 4,
    padding: 5,
    fontSize: 15,
    width: 153,
  },
  tryAgain: {
    backgroundColor: '#336699',
    padding: 13,
    borderRadius: 5,
  },
  tryAgainText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: '500',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: '#F6F6F6',
  },
  separator: {
    height: 1,
    backgroundColor: '#CCCCCC',
  },
  thumb: {
    width: 64,
    height: 64,
  },
  text: {
    flex: 1,
    fontSize: 13,
  },
});

AppRegistry.registerComponent('RealtimeRCT', () => RealtimeRCT);
<commit_msg>- imports update<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

import React, { Component } from 'react';
import realtime from './RCTRealtimeMessagingAndroid';
var RCTRealtimeMessaging = new realtime();

var messages = [];

import {
  AppRegistry,
  Image,
  StyleSheet,
  Text,
  Navigator,
  TextInput,
  ScrollView,
  TouchableHighlight,
  ListView,
  View
} from 'react-native';

var RealtimeRCT = React.createClass({

  doConnect: function(){
    this._log('Trying to connect!');

    RCTRealtimeMessaging.RTEventListener("onConnected",this._onConnected),
    RCTRealtimeMessaging.RTEventListener("onDisconnected",this._onDisconnected),
    RCTRealtimeMessaging.RTEventListener("onSubscribed",this._onSubscribed),
    RCTRealtimeMessaging.RTEventListener("onUnSubscribed",this._onUnSubscribed),
    RCTRealtimeMessaging.RTEventListener("onException",this._onException),
    RCTRealtimeMessaging.RTEventListener("onMessage",this._onMessage),
    RCTRealtimeMessaging.RTEventListener("onPresence",this._onPresence);

    RCTRealtimeMessaging.RTConnect(
    {
      appKey:this.state.appKey,
      token:this.state.token,
      connectionMetadata:this.state.connectionMetadata,
      clusterUrl:this.state.clusterUrl,
      projectId:'<YOUR_GOOGLE_PROJECT_NUMBER>'
    });
  },

  componentDidMount: function(){
    RCTRealtimeMessaging.RTPushNotificationListener(this._onNotification);
  },

  componentWillUnmount: function() {
    RCTRealtimeMessaging.RTDisconnect();
  },

  doDisconnect:function(){
    RCTRealtimeMessaging.RTDisconnect();
  },

  doSubscribe: function(){
    RCTRealtimeMessaging.RTSubscribeWithNotifications(this.state.channel, true);
  },

  doUnSubscribe: function(){
    RCTRealtimeMessaging.RTUnsubscribe(this.state.channel);
  },

  doSendMessage: function(){
    RCTRealtimeMessaging.RTSendMessage(this.state.message, this.state.channel);
  },

  doPresence: function(){
    RCTRealtimeMessaging.RTPresence(
       this.state.channel
     );
  },

  _onException: function(exceptionEvent){
    this._log("Exception:" + exceptionEvent.error);
  },

  _onConnected: function()
  {
    this._log("Connected");
  },

  _onDisconnected: function(){
    this._log("Disconnected");
  },

  _onSubscribed: function(subscribedEvent)
  {
    this._log("Subscribed channel " + subscribedEvent.channel);
  },

  _onUnSubscribed: function(unSubscribedEvent)
  {
    this._log("Unsubscribed channel " + unSubscribedEvent.channel);
  },

  _onNotification: function(data)
  {
    this._log("Received notification: " + JSON.stringify(data));
  },

  _onMessage: function(messageEvent)
  {
    this._log("Received message: ["+messageEvent.message+"] on channel [" + messageEvent.channel+"]");
  },

  _onPresence: function(presenceEvent){
    if (presenceEvent.error) {
      this._log("Error getting presence: " + presenceEvent.error);
    }else
    {
      this._log("Presence data: " + JSON.stringify(presenceEvent.result));
    };
  },

  getInitialState: function() {
    return {
      clusterUrl: "http://ortc-developers.realtime.co/server/2.1/",
      token: "SomeAuthenticatedToken",
      appKey: "YOUR_REALTIME_APPKEY",
      channel: "CHANNEL",
      connectionMetadata: "ReactNative Example",
      message: "This is the message",
      topWidth:0,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  },

  _renderRow: function(rowData: string, sectionID: number, rowID: number) {
    return (
      <TouchableHighlight>
        <View>
          <View style={styles.row}>
            <Text style={styles.text}>
              {rowData}
            </Text>
          </View>
          <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    );
  },

  _log: function(message: string)
  {
    var time = this.getFormattedDate();
    time += " - " + message
    var temp = [];
    temp[0] = time;

    for (var i = 0; i < messages.length; i++) {
      temp[i+1] =  messages[i];
    };
    messages = temp;

    this.setState({
      dataSource: this.getDataSource(messages)
    });
  },

  getFormattedDate: function() {
    var date = new Date();
    var str = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return str;
  },

  getDataSource: function(messages: Array<any>): ListView.DataSource {
    return this.state.dataSource.cloneWithRows(messages);
  },

  render: function() {
    return (
      <ScrollView style={styles.container}>

        <Text clusterUrl = {this.state.clusterUrl} >
            clusterUrl:
        </Text>
        <TextInput
          style={styles.textInput}
          placeholder={this.state.clusterUrl}
          onChangeText={(text) => this.setState({server: text})}
        />

        <View style={styles.custom}>
          <View style={styles.margin}>
            <Text server = {this.state.server} >
                Authentication Token:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.token}
              onChangeText={(text) => this.setState({token: text})}
            />

            <Text server = {this.state.server} >
                Application Key:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.appKey}
              onChangeText={(text) => this.setState({appKey: text})}
            />
          </View>

          <View style={styles.margin}>
            <Text server = {this.state.server} >
                Channel:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.channel}
              onChangeText={(text) => this.setState({channel: text})}
            />

            <Text server = {this.state.server} >
                Connection Metadata:
            </Text>
            <TextInput
              style={styles.halfTextInput}
              placeholder={this.state.connectionMetadata}
              onChangeText={(text) => this.setState({connectionMetadata: text})}
            />
          </View>

        </View>
        <Text server = {this.state.server} >
            Message:
        </Text>
        <TextInput
          style={styles.textInput}
          placeholder={this.state.message}
          onChangeText={(text) => this.setState({message: text})}
        />

        <View style={styles.rowView}>

          <TouchableHighlight style={styles.button} onPress={this.doConnect}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Connect</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doDisconnect}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Disconnect</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doSubscribe}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Subscribe</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doUnSubscribe}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Unsubscribe</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doSendMessage}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Send</Text>
            </View>
          </TouchableHighlight>

          <TouchableHighlight style={styles.button} onPress={this.doPresence}>
            <View style={styles.tryAgain}>
              <Text style={styles.tryAgainText}>Presence</Text>
            </View>
          </TouchableHighlight>

        </View>
        <ListView
          style={styles.list}
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
        />
      </ScrollView>

    )}
  });

var styles = StyleSheet.create({
  container: {
    marginTop: 30,
    margin: 5,
    backgroundColor: '#FFFFFF',
  },
  list: {
    flexDirection: 'column',
    backgroundColor: '#F6F6F6',
    height:150,
  },
  rowView:{
    alignItems: 'stretch',
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent:'center',
  },
  button:{
    margin: 5,
  },
  margin:{

  },
  custom:{
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent:'space-between',
  },
  textInput:{
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    borderRadius: 4,
    padding: 5,
    fontSize: 15,
  },

  halfTextInput:{
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    borderRadius: 4,
    padding: 5,
    fontSize: 15,
    width: 153,
  },
  tryAgain: {
    backgroundColor: '#336699',
    padding: 13,
    borderRadius: 5,
  },
  tryAgainText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: '500',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: '#F6F6F6',
  },
  separator: {
    height: 1,
    backgroundColor: '#CCCCCC',
  },
  thumb: {
    width: 64,
    height: 64,
  },
  text: {
    flex: 1,
    fontSize: 13,
  },
});

AppRegistry.registerComponent('RealtimeRCT', () => RealtimeRCT);
<|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* 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 should = require('should');

var adUtils = require('../../../../lib/commands/arm/ad/adUtils._js');

describe('ad-utils', function () {
  it('should report error when either no values or more than one parameter values provided', function () {
    //throw when no parameter value was provided
    (function () {
      adUtils.validateParameters({ upn: '' });
    }).should.throw();

    //throw when more than one parameter values were provided
    (function () {
      adUtils.validateParameters({ upn: 'test1@foo.com', spn: 'test2@bar.com' });
    }).should.throw();

    //No exceptions when there is only one parameter value provided
    adUtils.validateParameters({ upn: 'test1@foo.com', spn: '' });

    //No exceptions when there is no parameter at all.
    adUtils.validateParameters({});

  });
});<commit_msg>fix for adUtils-test.js<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* 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 should = require('should');

var adUtils;

try {
  adUtils = require('../../../../lib/commands/arm/ad/adUtils._js');
} catch (err) {
  if (err.code === 'MODULE_NOT_FOUND') {
    adUtils = require('../../../../lib/commands/arm/ad/adUtils.js');
  } else {
    throw error;
  }
}

describe('ad-utils', function () {
  it('should report error when either no values or more than one parameter values provided', function () {
    //throw when no parameter value was provided
    (function () {
      adUtils.validateParameters({ upn: '' });
    }).should.throw();

    //throw when more than one parameter values were provided
    (function () {
      adUtils.validateParameters({ upn: 'test1@foo.com', spn: 'test2@bar.com' });
    }).should.throw();

    //No exceptions when there is only one parameter value provided
    adUtils.validateParameters({ upn: 'test1@foo.com', spn: '' });

    //No exceptions when there is no parameter at all.
    adUtils.validateParameters({});

  });
});<|endoftext|>


<commit_before>/**
 * ConnectTheDots front-end code
 * Graph drawing adapted from https://bl.ocks.org/mbostock/4062045
 */
// (function() {
  var BACKGROUND_COLOR = '#fff',
      DISPLAY_RESOLUTION = 1.4,
      GRAPH_PADDING = .05,
      NODE_RADIUS = 6,
      NODE_STROKE = 2,
      EDGE_WIDTH = 1,
      ROUNDING_PRECISION = 3,
      TABLE_ROWS = 40,
      STICKY_OFFSET_TOP = 300,
      STICKY_OFFSET_BOTTOM = 80;

  // map link data (indices) to node ids, populate node neighbors
  data.nodes.forEach(function(n) {
    n.neighbors = [];
  });

  data.links.forEach(function(e) {
    data.nodes[e.source].neighbors.push(data.nodes[e.target].id);
    data.nodes[e.target].neighbors.push(data.nodes[e.source].id);

    e.source = data.nodes[e.source].id;
    e.target = data.nodes[e.target].id;
  });

  // setup SVG dimensions
  var svg = d3.select('svg'),
      container = d3.select('.ctd-container'),
      table = d3.select('.ctd-table');

  var padding = parseFloat(container.style('padding-left').slice(0, -2)),
      width = container.node().getBoundingClientRect().width - 2 * padding,
      height = width / DISPLAY_RESOLUTION,
      initWidth = width, initHeight = height,
      scale = {factor: 1, init: 1, dx: 0, dy: 0};

  svg.attr('width', width)
     .attr('height', height)
     .style('background-color', BACKGROUND_COLOR);

  // setup simulation
  var center = d3.forceCenter(width / 2, height / 2);

  var simulation = d3.forceSimulation()
                     .force('charge', d3.forceManyBody())
                     .force('link', d3.forceLink().id(function(d) { return d.id; }))
                     .force('center', center);

  var ticksElapsed = 0,
      stableAt = Math.ceil(
                   Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())
                 ); // number of ticks before graph reaches equilibrium

  // setup graphical elements and bind data
  var edge = svg.append('g')
                .classed('edges', true)
                .attr('aria-hidden', 'true')
                .selectAll('line').data(data.links)
                                  .enter().append('line')
                                  .style('opacity', 0)
                                  .attr('stroke-width', EDGE_WIDTH);

  var node = svg.append('g')
                .classed('nodes', true)
                .attr('role', 'group')
                .attr('aria-label', 'Network graph')
                .selectAll('circle').data(data.nodes)
                                    .enter().append('circle')
                                    .style('opacity', 0)
                                    .attr('r', NODE_RADIUS)
                                    .attr('stroke-width', NODE_STROKE)
                                    .attr('id', function(d) { return d.id; })
                                    .attr('role', 'img')
                                    .attr('aria-label', function(d) {
                                      return 'Node ' + d.id + ' has a degree of ' + d.degree +
                                      ' and a centrality of ' + parseFloat(d.centrality.toFixed(ROUNDING_PRECISION));
                                    });

  var row = table.append('tbody').selectAll('tr'),
      sort = {column: 'degree', order: -1};
  sortTable(sort.column, sort.order);

  var headers = table.select('thead').selectAll('th');
  headers.on('click', function() {
    var column = this.getAttribute('data-column');

    if (column === sort.column) {
      if (sort.order === 'asc') {
        sort.order = 'desc';
      } else {
        sort.order = 'asc';
      }
    } else {
      sort.column = column;
      sort.order = 'desc';
    }

    headers.classed('ctd-sort--asc', false)
           .classed('ctd-sort--desc', false);
    this.className = 'ctd-sort--' + sort.order;

    sortTable(sort.column, sort.order);
  });

  var progress = d3.select('.ctd-progress'),
      download = d3.select('.ctd-download > button'),
      tooltip = d3.select('.ctd-tooltip').style('display', 'none');

  // start simulation
  simulation.nodes(data.nodes)
            .on('tick', tickUpdate)
            .force('link').links(data.links);

  // event handlers for dragging and setting active node
  var activeNode;
  node.on('mouseover', mouseoverNode)
      .on('mouseout', mouseoutNode)
      .on('click', setActiveNode)
      .call(d3.drag().on('start', dragStart)
                     .on('drag', dragUpdate)
                     .on('end', dragEnd));

  svg.on('click', function() { if (d3.event.target.tagName !== 'circle') clearActiveNode(); });

  /**
   * Highlight a node in the graph and table
   */
  function mouseoverNode(d) {
    if (!activeNode) showTooltip(d);

    node.filter(function(n) { return n.id === d.id; }).classed('hover', true);
    row.filter(function(r) { return r.id === d.id; }).classed('hover', true);

    node.filter(function(n) { return n.id !== d.id && d.neighbors.indexOf(n.id) < 0; })
        .classed('blur', true);
    edge.filter(function(e) { return e.source.id !== d.id && e.target.id !== d.id; })
        .classed('blur', true);
  }

  /**
   * De-highlight a node in the graph and table
   */
  function mouseoutNode(d) {
    if (!activeNode) tooltip.classed('in', false);

    node.classed('hover', false)
        .classed('blur', false);
    edge.classed('blur', false);
    row.classed('hover', false);
  }

  /**
   * Set the active node
   */
  function setActiveNode(d) {
    if (activeNode !== d.id) {
      activeNode = d.id;

      node.classed('active', false);
      row.classed('active', false);

      node.filter(function(d) { return d.id === activeNode; }).classed('active', true);
      row.filter(function(d) { return d.id === activeNode; }).classed('active', true);

      showTooltip(d);
    }
  }

  /**
   * Clear the active node
   */
  function clearActiveNode() {
    activeNode = null;
    node.classed('active', false);
    row.classed('active', false);
    tooltip.classed('in', false);
  }

  /**
   * Handle node drag events
   */
  function dragStart(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
    setActiveNode(d);
  }

  function dragUpdate(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragEnd(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }

  /**
   * Show the tooltip for a particular node
   */
  function showTooltip(d) {
    tooltip.datum(d)
           .select('.tooltip-inner').html(function(d) {
             return '' + d.id + '
Degree: ' + d.degree +
             '
Centrality: ' + parseFloat(d.centrality.toFixed(ROUNDING_PRECISION));
           });

    tooltip.classed('fade', true)
           .classed('in', true);

    positionTooltip();
  }

  /**
   * Position the tooltip based on the currently bound node
   */
  function positionTooltip() {
    tooltip.style('left', function(d) {
             return d ? d.x * scale.factor + scale.dx - getTooltipSize().width / 2 + padding + 'px' : 0;
           })
           .style('top', function(d) {
             return d ? d.y * scale.factor + scale.dy - getTooltipSize().height + 'px' : 0;
           });
  }

  /**
   * Return the current dimensions of the tooltip
   */
  function getTooltipSize() {
    var bbox = tooltip.node().getBoundingClientRect();
    return {width: bbox.width, height: bbox.height};
  }

  /**
   * Sort table by column name and ascending/descending order
   */
  function sortTable(column, order) {
    var subset = data.nodes.sort(function(a, b) {
                   if (order === 'asc') {
                     return d3.ascending(a[column], b[column]) || d3.ascending(a.id, b.id);
                   } else {
                     return d3.descending(a[column], b[column]) || d3.ascending(a.id, b.id);
                   }
                 }).slice(0, TABLE_ROWS);

    var update = row.data(subset, function(d) { return d.id; });

    var enter = update.enter().append('tr')
                              .attr('id', function(d) { return d.id; })
                              .on('mouseover', mouseoverNode)
                              .on('mouseout', mouseoutNode)
                              .on('click', setActiveNode);

    enter.append('td').html(function(d) { return d.id; });
    enter.append('td').html(function(d) { return d.degree; });
    enter.append('td').html(function(d) { return parseFloat(d.centrality.toFixed(ROUNDING_PRECISION)); });

    update.exit().remove();

    row = enter.merge(update).order();
  }

  /**
   * Update positions of nodes/edges at each tick
   */
  function tickUpdate() {
    ticksElapsed++;
    if (ticksElapsed < stableAt) {
      progress.style('width', width * ticksElapsed / stableAt + 'px');
    } else if (ticksElapsed === stableAt) {
      rescaleGraph();
      progress.remove();
      node.style('opacity', 1);
      edge.style('opacity', 1);
      download.style('visibility', 'visible')
              .style('opacity', 1);
      tooltip.style('display', 'block');
    }

    // set node positions, bounded within graph area
    node.attr('cx', function(d) {
          var xMin = (NODE_RADIUS + width * GRAPH_PADDING - scale.dx) / scale.factor,
              xMax = (width * (1 - GRAPH_PADDING) - NODE_RADIUS - scale.dx) / scale.factor;
          return d.x = Math.max(xMin, Math.min(xMax, d.x));
        })
        .attr('cy', function(d) {
          var yMin = (NODE_RADIUS + height * GRAPH_PADDING - scale.dy) / scale.factor,
              yMax = (height * (1 - GRAPH_PADDING) - NODE_RADIUS - scale.dy) / scale.factor;
          return d.y = Math.max(yMin, Math.min(yMax, d.y));
        });

    // set edge positions
    edge.attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

    positionTooltip();
  }

  /**
   * Rescale the graph to fit some proportion of the SVG bounds
   */
  function rescaleGraph(k) {
    if (k) {
      scale.factor = k;
    } else {
      var bbox = svg.select('.nodes').node().getBBox();
      scale.factor = Math.min(width / bbox.width, height / bbox.height) * (1 - 2 * GRAPH_PADDING);
      scale.init = scale.factor;
    }

    scale.dx = -width / 2 * (scale.factor - 1),
    scale.dy = -height / 2 * (scale.factor - 1);

    svg.selectAll('g')
       .attr('transform', 'translate(' + scale.dx + ', ' + scale.dy + ') scale(' + scale.factor + ')');
  }

  // rescale graph on window resize
  window.onresize = _.debounce(function() {
    padding = parseFloat(container.style('padding-left').slice(0, -2)),
    width = container.node().getBoundingClientRect().width - 2 * padding,
    height = width / DISPLAY_RESOLUTION;

    svg.attr('width', width)
       .attr('height', height);

    rescaleGraph(scale.init * width / initWidth);

    center.x(width / 2)
          .y(height / 2);

    simulation.restart();

    $('.ctd-meta').css('width', width);
  }, 250);

  // sticky scrolling behavior on graph/table
  $('.ctd-container').affix({
    offset: {
      top: STICKY_OFFSET_TOP,
      bottom: document.querySelector('.tool > .container-fluid').getBoundingClientRect().height +
      document.querySelector('footer > nav').getBoundingClientRect().height + STICKY_OFFSET_BOTTOM
    }
  });

  $('.ctd-meta').css('width', width);

  $('.ctd-table').floatThead({
    floatContainerClass: 'ctd-thwrap',
    enableAria: true
  });

  // event handlers for export buttons
  document.querySelector('.btn-download--png').addEventListener('click', function() {
    saveSvgAsPng(document.querySelector('svg'), getFilename(filename, 'png'), {scale: 2.0});
  });

  document.querySelector('.btn-download--svg').addEventListener('click', function() {
    svgAsDataUri(document.querySelector('svg'), {}, function(uri) {
      var a = document.createElement('a');
      a.download = getFilename(filename, 'svg');
      a.href = uri;
      document.body.appendChild(a);
      a.click();
      a.parentNode.removeChild(a);
    });
  });

  document.querySelector('.btn-download--gexf').addEventListener('click', function() {
    var a = document.createElement('a');
    a.download = getFilename(filename, 'gexf');
    a.href = window.location.href.split(/[#?]/)[0] + '/graph.gexf';
    document.body.appendChild(a);
    a.click();
    a.parentNode.removeChild(a);
  });

  document.querySelector('.btn-download--table').addEventListener('click', function() {
    var a = document.createElement('a');
    a.download = getFilename(filename, 'csv');
    a.href = window.location.href.split(/[#?]/)[0] + '/table.csv';
    document.body.appendChild(a);
    a.click();
    a.parentNode.removeChild(a);
  });

  /**
   * Return a suggested filename for the exported graph
   */
  function getFilename(name, extension) {
    return name.replace(/[^a-z0-9]/gi, '-').toLowerCase() + '.' + extension;
  }
// })();<commit_msg>Uncommented closure.<commit_after>/**
 * ConnectTheDots front-end code
 * Graph drawing adapted from https://bl.ocks.org/mbostock/4062045
 */
(function() {
  var BACKGROUND_COLOR = '#fff',
      DISPLAY_RESOLUTION = 1.4,
      GRAPH_PADDING = .05,
      NODE_RADIUS = 6,
      NODE_STROKE = 2,
      EDGE_WIDTH = 1,
      ROUNDING_PRECISION = 3,
      TABLE_ROWS = 40,
      STICKY_OFFSET_TOP = 300,
      STICKY_OFFSET_BOTTOM = 80;

  // map link data (indices) to node ids, populate node neighbors
  data.nodes.forEach(function(n) {
    n.neighbors = [];
  });

  data.links.forEach(function(e) {
    data.nodes[e.source].neighbors.push(data.nodes[e.target].id);
    data.nodes[e.target].neighbors.push(data.nodes[e.source].id);

    e.source = data.nodes[e.source].id;
    e.target = data.nodes[e.target].id;
  });

  // setup SVG dimensions
  var svg = d3.select('svg'),
      container = d3.select('.ctd-container'),
      table = d3.select('.ctd-table');

  var padding = parseFloat(container.style('padding-left').slice(0, -2)),
      width = container.node().getBoundingClientRect().width - 2 * padding,
      height = width / DISPLAY_RESOLUTION,
      initWidth = width, initHeight = height,
      scale = {factor: 1, init: 1, dx: 0, dy: 0};

  svg.attr('width', width)
     .attr('height', height)
     .style('background-color', BACKGROUND_COLOR);

  // setup simulation
  var center = d3.forceCenter(width / 2, height / 2);

  var simulation = d3.forceSimulation()
                     .force('charge', d3.forceManyBody())
                     .force('link', d3.forceLink().id(function(d) { return d.id; }))
                     .force('center', center);

  var ticksElapsed = 0,
      stableAt = Math.ceil(
                   Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())
                 ); // number of ticks before graph reaches equilibrium

  // setup graphical elements and bind data
  var edge = svg.append('g')
                .classed('edges', true)
                .attr('aria-hidden', 'true')
                .selectAll('line').data(data.links)
                                  .enter().append('line')
                                  .style('opacity', 0)
                                  .attr('stroke-width', EDGE_WIDTH);

  var node = svg.append('g')
                .classed('nodes', true)
                .attr('role', 'group')
                .attr('aria-label', 'Network graph')
                .selectAll('circle').data(data.nodes)
                                    .enter().append('circle')
                                    .style('opacity', 0)
                                    .attr('r', NODE_RADIUS)
                                    .attr('stroke-width', NODE_STROKE)
                                    .attr('id', function(d) { return d.id; })
                                    .attr('role', 'img')
                                    .attr('aria-label', function(d) {
                                      return 'Node ' + d.id + ' has a degree of ' + d.degree +
                                      ' and a centrality of ' + parseFloat(d.centrality.toFixed(ROUNDING_PRECISION));
                                    });

  var row = table.append('tbody').selectAll('tr'),
      sort = {column: 'degree', order: -1};
  sortTable(sort.column, sort.order);

  var headers = table.select('thead').selectAll('th');
  headers.on('click', function() {
    var column = this.getAttribute('data-column');

    if (column === sort.column) {
      if (sort.order === 'asc') {
        sort.order = 'desc';
      } else {
        sort.order = 'asc';
      }
    } else {
      sort.column = column;
      sort.order = 'desc';
    }

    headers.classed('ctd-sort--asc', false)
           .classed('ctd-sort--desc', false);
    this.className = 'ctd-sort--' + sort.order;

    sortTable(sort.column, sort.order);
  });

  var progress = d3.select('.ctd-progress'),
      download = d3.select('.ctd-download > button'),
      tooltip = d3.select('.ctd-tooltip').style('display', 'none');

  // start simulation
  simulation.nodes(data.nodes)
            .on('tick', tickUpdate)
            .force('link').links(data.links);

  // event handlers for dragging and setting active node
  var activeNode;
  node.on('mouseover', mouseoverNode)
      .on('mouseout', mouseoutNode)
      .on('click', setActiveNode)
      .call(d3.drag().on('start', dragStart)
                     .on('drag', dragUpdate)
                     .on('end', dragEnd));

  svg.on('click', function() { if (d3.event.target.tagName !== 'circle') clearActiveNode(); });

  /**
   * Highlight a node in the graph and table
   */
  function mouseoverNode(d) {
    if (!activeNode) showTooltip(d);

    node.filter(function(n) { return n.id === d.id; }).classed('hover', true);
    row.filter(function(r) { return r.id === d.id; }).classed('hover', true);

    node.filter(function(n) { return n.id !== d.id && d.neighbors.indexOf(n.id) < 0; })
        .classed('blur', true);
    edge.filter(function(e) { return e.source.id !== d.id && e.target.id !== d.id; })
        .classed('blur', true);
  }

  /**
   * De-highlight a node in the graph and table
   */
  function mouseoutNode(d) {
    if (!activeNode) tooltip.classed('in', false);

    node.classed('hover', false)
        .classed('blur', false);
    edge.classed('blur', false);
    row.classed('hover', false);
  }

  /**
   * Set the active node
   */
  function setActiveNode(d) {
    if (activeNode !== d.id) {
      activeNode = d.id;

      node.classed('active', false);
      row.classed('active', false);

      node.filter(function(d) { return d.id === activeNode; }).classed('active', true);
      row.filter(function(d) { return d.id === activeNode; }).classed('active', true);

      showTooltip(d);
    }
  }

  /**
   * Clear the active node
   */
  function clearActiveNode() {
    activeNode = null;
    node.classed('active', false);
    row.classed('active', false);
    tooltip.classed('in', false);
  }

  /**
   * Handle node drag events
   */
  function dragStart(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
    setActiveNode(d);
  }

  function dragUpdate(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragEnd(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }

  /**
   * Show the tooltip for a particular node
   */
  function showTooltip(d) {
    tooltip.datum(d)
           .select('.tooltip-inner').html(function(d) {
             return '' + d.id + '
Degree: ' + d.degree +
             '
Centrality: ' + parseFloat(d.centrality.toFixed(ROUNDING_PRECISION));
           });

    tooltip.classed('fade', true)
           .classed('in', true);

    positionTooltip();
  }

  /**
   * Position the tooltip based on the currently bound node
   */
  function positionTooltip() {
    tooltip.style('left', function(d) {
             return d ? d.x * scale.factor + scale.dx - getTooltipSize().width / 2 + padding + 'px' : 0;
           })
           .style('top', function(d) {
             return d ? d.y * scale.factor + scale.dy - getTooltipSize().height + 'px' : 0;
           });
  }

  /**
   * Return the current dimensions of the tooltip
   */
  function getTooltipSize() {
    var bbox = tooltip.node().getBoundingClientRect();
    return {width: bbox.width, height: bbox.height};
  }

  /**
   * Sort table by column name and ascending/descending order
   */
  function sortTable(column, order) {
    var subset = data.nodes.sort(function(a, b) {
                   if (order === 'asc') {
                     return d3.ascending(a[column], b[column]) || d3.ascending(a.id, b.id);
                   } else {
                     return d3.descending(a[column], b[column]) || d3.ascending(a.id, b.id);
                   }
                 }).slice(0, TABLE_ROWS);

    var update = row.data(subset, function(d) { return d.id; });

    var enter = update.enter().append('tr')
                              .attr('id', function(d) { return d.id; })
                              .on('mouseover', mouseoverNode)
                              .on('mouseout', mouseoutNode)
                              .on('click', setActiveNode);

    enter.append('td').html(function(d) { return d.id; });
    enter.append('td').html(function(d) { return d.degree; });
    enter.append('td').html(function(d) { return parseFloat(d.centrality.toFixed(ROUNDING_PRECISION)); });

    update.exit().remove();

    row = enter.merge(update).order();
  }

  /**
   * Update positions of nodes/edges at each tick
   */
  function tickUpdate() {
    ticksElapsed++;
    if (ticksElapsed < stableAt) {
      progress.style('width', width * ticksElapsed / stableAt + 'px');
    } else if (ticksElapsed === stableAt) {
      rescaleGraph();
      progress.remove();
      node.style('opacity', 1);
      edge.style('opacity', 1);
      download.style('visibility', 'visible')
              .style('opacity', 1);
      tooltip.style('display', 'block');
    }

    // set node positions, bounded within graph area
    node.attr('cx', function(d) {
          var xMin = (NODE_RADIUS + width * GRAPH_PADDING - scale.dx) / scale.factor,
              xMax = (width * (1 - GRAPH_PADDING) - NODE_RADIUS - scale.dx) / scale.factor;
          return d.x = Math.max(xMin, Math.min(xMax, d.x));
        })
        .attr('cy', function(d) {
          var yMin = (NODE_RADIUS + height * GRAPH_PADDING - scale.dy) / scale.factor,
              yMax = (height * (1 - GRAPH_PADDING) - NODE_RADIUS - scale.dy) / scale.factor;
          return d.y = Math.max(yMin, Math.min(yMax, d.y));
        });

    // set edge positions
    edge.attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

    positionTooltip();
  }

  /**
   * Rescale the graph to fit some proportion of the SVG bounds
   */
  function rescaleGraph(k) {
    if (k) {
      scale.factor = k;
    } else {
      var bbox = svg.select('.nodes').node().getBBox();
      scale.factor = Math.min(width / bbox.width, height / bbox.height) * (1 - 2 * GRAPH_PADDING);
      scale.init = scale.factor;
    }

    scale.dx = -width / 2 * (scale.factor - 1),
    scale.dy = -height / 2 * (scale.factor - 1);

    svg.selectAll('g')
       .attr('transform', 'translate(' + scale.dx + ', ' + scale.dy + ') scale(' + scale.factor + ')');
  }

  // rescale graph on window resize
  window.onresize = _.debounce(function() {
    padding = parseFloat(container.style('padding-left').slice(0, -2)),
    width = container.node().getBoundingClientRect().width - 2 * padding,
    height = width / DISPLAY_RESOLUTION;

    svg.attr('width', width)
       .attr('height', height);

    rescaleGraph(scale.init * width / initWidth);

    center.x(width / 2)
          .y(height / 2);

    simulation.restart();

    $('.ctd-meta').css('width', width);
  }, 250);

  // sticky scrolling behavior on graph/table
  $('.ctd-container').affix({
    offset: {
      top: STICKY_OFFSET_TOP,
      bottom: document.querySelector('.tool > .container-fluid').getBoundingClientRect().height +
      document.querySelector('footer > nav').getBoundingClientRect().height + STICKY_OFFSET_BOTTOM
    }
  });

  $('.ctd-meta').css('width', width);

  $('.ctd-table').floatThead({
    floatContainerClass: 'ctd-thwrap',
    enableAria: true
  });

  // event handlers for export buttons
  document.querySelector('.btn-download--png').addEventListener('click', function() {
    saveSvgAsPng(document.querySelector('svg'), getFilename(filename, 'png'), {scale: 2.0});
  });

  document.querySelector('.btn-download--svg').addEventListener('click', function() {
    svgAsDataUri(document.querySelector('svg'), {}, function(uri) {
      var a = document.createElement('a');
      a.download = getFilename(filename, 'svg');
      a.href = uri;
      document.body.appendChild(a);
      a.click();
      a.parentNode.removeChild(a);
    });
  });

  document.querySelector('.btn-download--gexf').addEventListener('click', function() {
    var a = document.createElement('a');
    a.download = getFilename(filename, 'gexf');
    a.href = window.location.href.split(/[#?]/)[0] + '/graph.gexf';
    document.body.appendChild(a);
    a.click();
    a.parentNode.removeChild(a);
  });

  document.querySelector('.btn-download--table').addEventListener('click', function() {
    var a = document.createElement('a');
    a.download = getFilename(filename, 'csv');
    a.href = window.location.href.split(/[#?]/)[0] + '/table.csv';
    document.body.appendChild(a);
    a.click();
    a.parentNode.removeChild(a);
  });

  /**
   * Return a suggested filename for the exported graph
   */
  function getFilename(name, extension) {
    return name.replace(/[^a-z0-9]/gi, '-').toLowerCase() + '.' + extension;
  }
})();<|endoftext|>


<commit_before>define(
  'ephox.darwin.api.Darwin',

  [
  ],

  function () {
    return {

    };
  }
);
<commit_msg>TBIO-2087: moved into api file<commit_after>define(
  'ephox.darwin.api.Darwin',

  [
    'ephox.fred.PlatformDetection',
    'ephox.fussy.api.Point',
    'ephox.fussy.api.WindowSelection',
    'ephox.oath.proximity.Awareness',
    'ephox.perhaps.Option',
    'ephox.sugar.api.Node',
    'global!Math'
  ],

  function (PlatformDetection, Point, WindowSelection, Awareness, Option, Node, Math) {
    var platform = PlatformDetection.detect();

    var getSpot = function () {
	    return WindowSelection.get(window).bind(function (sel) {
	      return WindowSelection.rectangleAt(window, sel.start(), sel.soffset(), sel.finish(), sel.foffset());
	    });
	  };

    // In Firefox, it isn't giving you the next element ... it's giving you the current element. So if the box of where it gives you has the same y value
    // minus some error, try again with a bigger jump.
    var firefoxAgain = function (spot) {
      return Point.find(window, spot.left, spot.bottom + 5).bind(function (pt) {
        return pt.start().fold(Option.none, function (e, eo) {
          var box = getBox(e, eo);
          if (Math.abs(box.top - spot.top) < 10) {
            return firefoxAgain({ left: spot.left, bottom: spot.bottom + 5, top: spot.top + 5 }).orThunk(function () {
              return Option.some(pt);
            });
          } else if (box.top > spot.bottom + 5) {
            return Point.find(window, spot.left, box.top + 1).orThunk(function () { return Option.some(pt); });
          }
          else return Option.some(pt);
        }, Option.none);
      });
    };

    // The process is that you incrementally go down ... if you find the next element, but your top is not at that element's bounding rect.
    // then try again with the same x but the box's y
    var webkitAgain = function (spot) {
      return Point.find(window, spot.left, spot.bottom + 5).bind(function (pt) {
        return pt.start().fold(Option.none, function (e, eo) {
          var box = getBox(e, eo);
          // If the box that it returned does not contain the spot, move the spot to within the box and try again
          // this is an attempt to get a more reliable offset
          if (box.top > spot.bottom + 5) {
            return Point.find(window, spot.left, box.top + 1).orThunk(function () { return Option.some(pt); });
          } else {
            return Option.some(pt);
          }
        }, Option.none);

      });
    };

    var ieAgain = function (spot) {
      return Point.find(window, spot.left, spot.bottom + 5);
    };

    var calc = function (spot) {
      if (platform.browser.isChrome() || platform.browser.isSafari()) return webkitAgain(spot);
      else if (platform.browser.isFirefox()) return firefoxAgain(spot);
      else if (platform.browser.isIE()) return ieAgain(spot);
      else return Option.none();
    };

    var getBox = function (element, offset) {
      if (Node.isElement(element)) return element.dom().getBoundingClientRect();
      else {
        if (offset === 0 && offset < Awareness.getEnd(element)) {
          var rng = document.createRange();
          rng.setStart(element.dom(), offset);
          rng.setEnd(element.dom(), offset + 1);
          return rng.getBoundingClientRect();
        } else if (offset > 1) {
          var rng2 = document.createRange();
          rng2.setStart(element.dom(), offset - 1);
          rng2.setEnd(element.dom(), offset);
          return rng2.getBoundingClientRect();
        } else {
          throw 'cattle';
        }
      }
    };

    var handler = function (event) {
      getSpot().each(function (spot) {
        // updateLogbook('x: ' + spot.left + ', y: ' + spot.bottom);
      });

      if (event.raw().which === 40) {
        getSpot().bind(function (spot) {
          return calc(spot);
        }).fold(function () {
          console.log('did not handle');
        }, function (pt) {
          console.log('handled: ', pt);
          WindowSelection.set(window, pt);
          // updateLogbook(10);
        });
        // down
        event.kill();
      }

    };

    return {
      handler: handler
    };
  }
);
<|endoftext|>


<commit_before>jsio('from base import *');
jsio('import logging');
var logger = logging.getLogger('net.env');

function getObj(objectName, transportName, envName) {
	jsio('from .env.' + (envName || jsio.__env.name) + '.' + transportName + ' import ' + objectName + ' as result');
	return result;
}

exports.getListener = bind(this, getObj, 'Listener');
exports.getConnector = bind(this, getObj, 'Connector');
<commit_msg>add some more helpful logging for debugging failed env imports<commit_after>jsio('from base import *');
jsio('import logging');
var logger = logging.getLogger('net.env');

function getObj(objectName, transportName, envName) {
	try {
		jsio('from .env.' + (envName || jsio.__env.name) + '.' + transportName + ' import ' + objectName + ' as result');
	} catch(e) {
		throw logger.error('Invalid transport (', transportName, ') or environment (', envName, ')');
	}
	return result;
}

exports.getListener = bind(this, getObj, 'Listener');
exports.getConnector = bind(this, getObj, 'Connector');
<|endoftext|>


<commit_before>(function (global, cjsmEval) {

	/***** imports *****/

	var reduceLeadingDots = getReduceLeadingDotsImpl;
	var joinPaths = getJoinPathsImpl;
	var fetchText = getFetchTextImpl;

	/***** exports *****/

	var pipeline  = {
		normalize: normalize,
		resolve: resolve,
		fetch: fetch,
		translate: translate,
		link: link
	};

	System.set('beck/init/pipeline', ToModule(pipeline));

	var removeCommentsRx, findRValueRequiresRx;

	removeCommentsRx = /\/\*[\s\S]*?\*\/|\/\/.*?[\n\r]/g;
	findRValueRequiresRx = /require\s*\(\s*(["'])(.*?[^\\])\1\s*\)|[^\\]?(["'])/g;

	function normalize (name, referer) {
		var normalized, mctx;
		if (typeof referer == 'object') referer = referer.name;
		normalized = reduceLeadingDots(String(name), referer || '');
		mctx = {
			name: normalized,
			relName: name,
			refererName: referer
		};
		return {
			normalized: normalized,
			metadata: mctx
		};
	}

	function resolve (normalized, options) {
		var mctx = options.metadata;
		mctx.url = joinPaths('./', normalized);
		return mctx.url;
	}

	function fetch (resolved, fulfill, reject, options) {
		fetchText(
			resolved,
			function (source) {
				fulfill(addSourceUrl(resolved, source));
			},
			reject
		);
	}

	function translate (source, options) {
		return source;
	}

	function link (source, options) {
		return parseCjsm(source, options);
	}

	function addSourceUrl (url, source) {
		return source
			+ '\n/*\n////@ sourceURL='
			+ url.replace(/\s/g, '%20')
			+ '\n*/\n';
	}

	function parseCjsm (source, options) {
		var mctx, currQuote;

		mctx = options.metadata;
		mctx.deps = [];
		mctx.depsMap = {};

		// remove comments, then look for require() or quotes
		source = source.replace(removeCommentsRx, '');
		source.replace(findRValueRequiresRx, function (m, rq, id, qq) {
			// if we encounter a string in the source, don't look for require()
			if (qq) {
				currQuote = currQuote == qq ? void 0 : currQuote;
			}
			// if we're not inside a quoted string
			else if (!currQuote) {
				// push [relative] id into deps list and deps map
				if (!(id in mctx.depsMap)) {
					mctx.depsMap[id] = mctx.deps.push(id) - 1;
				}
			}
			return ''; // uses least RAM/CPU
		});

		return {
			imports: mctx.deps,
			execute: createCjsmFactory(source, options)
		};
	}

	// Note: does not support computed module ids in require() calls or
	// async require(id, cb, eb) as in AMD!
	function createCjsmFactory (source, options) {
		// just create a factory
		return function () {
			var mctx, deps, require, exports, module, glob;

			mctx = options.metadata;
			deps = arguments;
			require = function (id) { return deps[mctx.depsMap[id]]; };
			exports = {};
			module = { id: mctx.name, uri: mctx.url, exports: exports };
			glob = ('global' in options && options.global)
				|| ('global' in mctx && mctx.global)
				|| global;

			cjsmEval(require, exports, module, glob, source);

			return module.exports;
		};
	}

	function getReduceLeadingDotsImpl () {
		reduceLeadingDots = System.get('beck/init/path').reduceLeadingDots;
		return reduceLeadingDots.apply(this, arguments);
	}

	function getJoinPathsImpl () {
		joinPaths = System.get('beck/init/path').joinPaths;
		return joinPaths.apply(this, arguments);
	}

	function getFetchTextImpl () {
		fetchText = System.get('beck/init/fetchText');
		return fetchText.apply(this, arguments);
	}

}(
	typeof global != 'undefined' ? global : this.global || this.window,
	function (require, exports, module, global) { eval(arguments[4]); }
));<commit_msg>Attempt to resolve dynamic require() and throw if fails.<commit_after>(function (global, cjsmEval) {

	/***** imports *****/

	var reduceLeadingDots = getReduceLeadingDotsImpl;
	var joinPaths = getJoinPathsImpl;
	var fetchText = getFetchTextImpl;

	/***** exports *****/

	var pipeline  = {
		normalize: normalize,
		resolve: resolve,
		fetch: fetch,
		translate: translate,
		link: link
	};

	System.set('beck/init/pipeline', ToModule(pipeline));

	var removeCommentsRx, findRValueRequiresRx, absUrlRx;

	removeCommentsRx = /\/\*[\s\S]*?\*\/|\/\/.*?[\n\r]/g;
	findRValueRequiresRx = /require\s*\(\s*(["'])(.*?[^\\])\1\s*\)|[^\\]?(["'])/g;
	absUrlRx = /^\/|^[^:]+:\/\//;

	function normalize (name, referer) {
		var normalized, mctx;
		if (typeof referer == 'object') referer = referer.name;
		normalized = reduceLeadingDots(String(name), referer || '');
		mctx = {
			name: normalized,
			relName: name,
			refererName: referer
		};
		return {
			normalized: normalized,
			metadata: mctx
		};
	}

	function resolve (normalized, options) {
		var mctx = options.metadata;
		mctx.url = joinPaths('./', normalized);
		return mctx.url;
	}

	function fetch (resolved, fulfill, reject, options) {
		fetchText(
			resolved,
			function (source) {
				fulfill(addSourceUrl(resolved, source));
			},
			reject
		);
	}

	function translate (source, options) {
		return source;
	}

	function link (source, options) {
		return parseCjsm(source, options);
	}

	function isAbsUrl (url) {
		return absUrlRx.test(url);
	}

	function addSourceUrl (url, source) {
		return source
			+ '\n/*\n////@ sourceURL='
			+ url.replace(/\s/g, '%20')
			+ '\n*/\n';
	}

	function parseCjsm (source, options) {
		var mctx, currQuote;

		mctx = options.metadata;
		mctx.deps = [];
		mctx.depsMap = {};

		// remove comments, then look for require() or quotes
		source = source.replace(removeCommentsRx, '');
		source.replace(findRValueRequiresRx, function (m, rq, id, qq) {
			// if we encounter a string in the source, don't look for require()
			if (qq) {
				currQuote = currQuote == qq ? void 0 : currQuote;
			}
			// if we're not inside a quoted string
			else if (!currQuote) {
				// push [relative] id into deps list and deps map
				if (!(id in mctx.depsMap)) {
					mctx.depsMap[id] = mctx.deps.push(id) - 1;
				}
			}
			return ''; // uses least RAM/CPU
		});

		return {
			imports: mctx.deps,
			execute: createCjsmFactory(source, options)
		};
	}

	// Note: does not support computed module ids in require() calls or
	// async require(id, cb, eb) as in AMD!
	function createCjsmFactory (source, options) {
		// just create a factory
		return function () {
			var mctx, deps, require, exports, module, glob;

			mctx = options.metadata;
			deps = arguments;
			require = function (id) {
				var dep;
				if (id in mctx.depsMap) {
					dep = deps[mctx.depsMap[id]];
				}
				// TODO: figure out if/how to resolve relative require()s
				else if (isAbsUrl(id) && System.has(id)) {
					dep = System.get(id);
				}
				else {
					throw new Error('Module not resolved: ' + id + '. Dynamic require() not supported.');
				}
				return dep;
			};
			exports = {};
			module = { id: mctx.name, uri: mctx.url, exports: exports };
			glob = ('global' in options && options.global)
				|| ('global' in mctx && mctx.global)
				|| global;

			cjsmEval(require, exports, module, glob, source);

			return module.exports;
		};
	}

	function getReduceLeadingDotsImpl () {
		reduceLeadingDots = System.get('beck/init/path').reduceLeadingDots;
		return reduceLeadingDots.apply(this, arguments);
	}

	function getJoinPathsImpl () {
		joinPaths = System.get('beck/init/path').joinPaths;
		return joinPaths.apply(this, arguments);
	}

	function getFetchTextImpl () {
		fetchText = System.get('beck/init/fetchText');
		return fetchText.apply(this, arguments);
	}

}(
	typeof global != 'undefined' ? global : this.global || this.window,
	function (require, exports, module, global) { eval(arguments[4]); }
));<|endoftext|>