<commit_before>'use strict';
const Mongoose = require('mongoose'),
      Schema = Mongoose.Schema;

const EventSchema = new Schema({
  name: String,
  noteID: String,
  type: String,
  description: String,
  location: String,
  date: Date,
  formattedDate: String,
  photos: Array
}, {
  collection: 'EventData'
});

const Event = Mongoose.model('Event', EventSchema);
module.exports = Event;
<commit_msg>feat (DB): Add custom validator function to schema<commit_after>'use strict';
const Mongoose = require('mongoose'),
      Schema = Mongoose.Schema;

const EventSchema = new Schema({
  name: {
    type: String,
    validate: {
      validator: (name) => name.length >= 3,
      message: 'Your event name must be at least 3 characters long.'
    },
    required: [true, 'This event requires a name.']
  },
  noteID: String,
  type: String,
  description: String,
  location: String,
  date: Date,
  formattedDate: String,
  photos: Array,
  photoCount: Number
}, {
  collection: 'EventData'
});

const Event = Mongoose.model('Event', EventSchema);
module.exports = Event;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
  View,
  ListView,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Platform,
} from 'react-native';
import colors from '../config/colors';
import Carpooler from '../components/Carpooler';
import { connectActionSheet } from '@exponent/react-native-action-sheet';
import { withNavigation } from '@exponent/ex-navigation';
import ElevatedView from 'react-native-elevated-view';
import { maybeOpenURL } from 'react-native-app-link';
import connectDropdownAlert from '../utils/connectDropdownAlert';
import { observer } from 'mobx-react/native';
import { Notifications } from 'exponent';

@withNavigation
@connectActionSheet
@connectDropdownAlert
@observer
export default class Ride extends Component { // eslint-disable-line require-jsdoc
  static propTypes = {
    event: PropTypes.object.isRequired,
    navigator: PropTypes.object,
    showActionSheetWithOptions: PropTypes.func,
    refresh: PropTypes.func,
    refreshing: PropTypes.bool,
    alertWithType: PropTypes.func.isRequired,
  }

  state = {
    passengers: [],
    pickedUpUsers: 0,
    selfIsDriver: this.props.event.yourRide.driver === global.firebaseApp.auth().currentUser.uid,
  }

  componentWillMount() {
    const passengers = [];
    let pickedUpUsers = 0;
    global.firebaseApp.database()
    .ref('users')
    .child(this.props.event.yourRide.driver)
    .once('value')
    .then(userSnap => {
      passengers.push({
        userUID: this.props.event.yourRide.driver,
        ...userSnap.val(),
        type: 'driver',
      });

      // now get other users and push to arr
      if (this.props.event.yourRide.passengers) {
        this.props.event.yourRide.passengers.slice().forEach(pass => {
          global.firebaseApp.database()
          .ref('users')
          .child(pass.userUID)
          .once('value')
          .then(passSnap => {
            passengers.push({
              ...pass,
              ...passSnap.val(),
              type: 'rider',
            });
            if (pass.isPickedUp) {
              pickedUpUsers++;
            }
            this.setState(() => {
              return {
                passengers,
                pickedUpUsers,
              };
            });
          });
        });
      }
      this.setState(() => {
        return {
          passengers,
        };
      });
    })
    .catch(err => {
      this.props.alertWithType('error', 'Error', err.toString());
    });
  }

  ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })

  _onOpenActionSheet = () => {
    // Same interface as https://facebook.github.io/react-native/docs/actionsheetios.html
    const options = ['Leave Ride', 'Navigate', 'Cancel'];
    const destructiveButtonIndex = 0;
    const navigateButtonIndex = 1;
    const cancelButtonIndex = 2;
    this.props.showActionSheetWithOptions({
      options,
      cancelButtonIndex,
      destructiveButtonIndex,
    },
    (buttonIndex) => {
      if (buttonIndex === destructiveButtonIndex) {
        if (this.state.selfIsDriver) {
          Alert.alert(
            Platform.OS === 'ios' ? 'Leave Ride' : 'Leave ride',
            'Are you sure? Leaving this ride will strand your passengers. 😢',
            [
              { text: 'Cancel', style: 'cancel' },
              {
                text: 'OK',
                onPress: () => {
                  global.firebaseApp.database()
                    .ref('schools')
                    .child(this.props.event.schoolUID)
                    .child('events')
                    .child(this.props.event.uid)
                    .child('rides')
                    .child(this.props.event.yourRide.uid)
                    .remove()
                    .then(() => {
                      Notifications.cancelScheduledNotificationAsync(this.props.event.yourRide.notiID);
                      this.props.alertWithType('error', '😢', `You left ${this.props.event.name}.`);
                      this.props.refresh(false);
                    })
                    .catch(err => {
                      this.props.alertWithType('error', 'Error', err.toString());
                    });
                },
              },
            ]
          );
        } else {
          Alert.alert(
            Platform.OS === 'ios' ? 'Leave Ride' : 'Leave ride',
            'Are you sure? Leaving this ride so not lit.',
            [
              { text: 'Cancel', style: 'cancel' },
              {
                text: 'OK',
                onPress: () => {
                  const passIndex = this.props.event.yourRide.passengers.slice().findIndex(
                    i => i.userUID === global.firebaseApp.auth().currentUser.uid
                  );
                  global.firebaseApp.database()
                    .ref('schools')
                    .child(this.props.event.schoolUID)
                    .child('events')
                    .child(this.props.event.uid)
                    .child('rides')
                    .child(this.props.event.yourRide.uid)
                    .child('passengers')
                    .child(this.props.event.yourRide.passengers[passIndex].passUID)
                    .remove()
                    .then(() => {
                      this.props.alertWithType('error', '😢', `You left ${this.props.event.name}.`);
                      this.props.refresh(false);
                    })
                    .catch(err => {
                      this.props.alertWithType('error', 'Error', err.toString());
                    });
                },
              },
            ]
          );
        }
      }
      if (buttonIndex === navigateButtonIndex) {
        const wazeUrl = `waze://?ll=${this.props.event.location.geometry.location.lat},` +
        `${this.props.event.location.geometry.location.lng}&z=10&navigate=yes`;
        maybeOpenURL(wazeUrl, { appName: 'Waze', appStoreId: 'id323229106', playStoreId: 'com.waze' })
        .catch(err => {
          this.props.alertWithType('error', 'Error', err.toString());
        });
      }
    });
  }

  render() {
    return (
      <View style={ styles.container }>
        <View style={ styles.headerRow }>
          <Text style={ styles.label }>
            {this.props.event.name.toUpperCase()}
          </Text>
          <TouchableOpacity
            style={ styles.moreContainer }
            onPress={ this._onOpenActionSheet }
            // onPress open an action sheet
            hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }}
          >
            <View style={ styles.moreItem } />
            <View style={ styles.moreItem } />
            <View style={ styles.moreItem } />
          </TouchableOpacity>
        </View>
        <ListView
          enableEmptySections
          dataSource={ this.ds.cloneWithRows(this.state.passengers) }
          renderRow={ u => <Carpooler
            event={ this.props.event }
            refresh={ this.props.refresh }
            passengers={ this.state.passengers }
            pickedUpUsers={ this.state.pickedUpUsers }
            refreshing={ this.props.refreshing }
            user={ u }
            selfIsDriver={ this.state.selfIsDriver }
          /> }
        />
        { /* if everyone is pickedUp render 'start driving' button */ }
        <Choose>
          <When
            condition={
              this.state.selfIsDriver &&
              !this.props.event.yourRide.rideStarted &&
              this.state.passengers.length > 1 &&
              this.state.pickedUpUsers === this.state.passengers.length - 1
            }
          >
            <TouchableOpacity
              onPress={
                () => Alert.alert(
                  Platform.OS === 'ios' ? 'Start Ride' : 'Start ride',
                  'Are you sure? Just making sure you didn\'t click this by mistake.',
                  [
                    { text: 'Cancel', style: 'cancel' },
                    {
                      text: 'OK',
                      onPress: () => {
                        global.firebaseApp.database()
                        .ref('schools')
                        .child(this.props.event.schoolUID)
                        .child('events')
                        .child(this.props.event.uid)
                        .child('rides')
                        .child(this.props.event.yourRide.uid)
                        .update({
                          rideStarted: true,
                        }, () => {
                          const wazeUrl = `waze://?ll=${this.props.event.location.geometry.location.lat},` +
                          `${this.props.event.location.geometry.location.lng}&z=10&navigate=yes`;
                          maybeOpenURL(wazeUrl, { appName: 'Waze', appStoreId: 'id323229106', playStoreId: 'com.waze' })
                          .catch(err => {
                            this.props.alertWithType('error', 'Error', err.toString());
                          });
                        })
                        .catch(err => {
                          this.props.alertWithType('error', 'Error', err.toString());
                        });
                      },
                    },
                  ]
                )
              }
            >
              <ElevatedView
                style={ styles.startDrivingButton }
                elevation={ 4 }
              >
                <Text style={ styles.buttonText }>
                  START DRIVING
                </Text>
              </ElevatedView>
            </TouchableOpacity>
          </When>
          <When
            condition={ this.state.selfIsDriver && this.props.event.yourRide.rideStarted && !this.props.event.yourRide.rideCompleted }
          >
            <TouchableOpacity
              onPress={
                () => Alert.alert(
                  Platform.OS === 'ios' ? 'End Ride' : 'End ride',
                  'Are you sure? Just making sure you didn\'t click this by mistake.',
                  [
                    { text: 'Cancel', style: 'cancel' },
                    {
                      text: 'OK',
                      onPress: () => {
                        global.firebaseApp.database()
                        .ref('schools')
                        .child(this.props.event.schoolUID)
                        .child('events')
                        .child(this.props.event.uid)
                        .child('rides')
                        .child(this.props.event.yourRide.uid)
                        .update({
                          rideCompleted: true,
                        }, () => {
                          this.props.alertWithType('success', 'YEET', 'Aye you made it!');
                        })
                        .catch(err => {
                          this.props.alertWithType('error', 'Error', err.toString());
                        });
                      },
                    },
                  ]
                )
              }
            >
              <ElevatedView
                style={ styles.rideCompleteButton }
                elevation={ 4 }
              >
                <Text style={ styles.buttonText }>
                  COMPLETE RIDE
                </Text>
              </ElevatedView>
            </TouchableOpacity>
          </When>
          <When condition={ this.state.selfIsDriver && this.state.passengers.length === 1 }>
            <Text
              style={{
                fontFamily: 'open-sans-semibold',
                fontSize: 18,
                alignSelf: 'center',
                paddingTop: 16,
              }}
            >
              NO PASSENGERS AVAILABLE
            </Text>
          </When>
          <When condition={ this.props.event.yourRide.rideCompleted }>
            <Text
              style={{
                fontFamily: 'open-sans-semibold',
                fontSize: 18,
                alignSelf: 'center',
                paddingTop: 16,
              }}
            >
              RIDE COMPLETED
            </Text>
          </When>
        </Choose>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingVertical: 8,
  },
  label: {
    fontFamily: 'open-sans-semibold',
    fontSize: 12,
    color: 'rgba(128, 128, 128, 0.7)',
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginHorizontal: 8,
    paddingBottom: 4,
  },
  moreContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: 24,
  },
  moreItem: {
    backgroundColor: '#546E7A',
    height: 5,
    width: 5,
    borderRadius: 5,
  },
  startDrivingButton: {
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
    marginHorizontal: 8,
    paddingVertical: 8,
    marginTop: 8,
    backgroundColor: colors.purp,
  },
  rideCompleteButton: {
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
    marginHorizontal: 8,
    paddingVertical: 8,
    marginTop: 8,
    backgroundColor: colors.neonGreen,
  },
  buttonText: {
    fontFamily: 'open-sans-bold',
    fontSize: 18,
    color: 'white',
  },
});
<commit_msg>show if ride is in progress<commit_after>import React, { Component, PropTypes } from 'react';
import {
  View,
  ListView,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Platform,
} from 'react-native';
import colors from '../config/colors';
import Carpooler from '../components/Carpooler';
import { connectActionSheet } from '@exponent/react-native-action-sheet';
import { withNavigation } from '@exponent/ex-navigation';
import ElevatedView from 'react-native-elevated-view';
import { maybeOpenURL } from 'react-native-app-link';
import connectDropdownAlert from '../utils/connectDropdownAlert';
import { observer } from 'mobx-react/native';
import { Notifications } from 'exponent';

@withNavigation
@connectActionSheet
@connectDropdownAlert
@observer
export default class Ride extends Component { // eslint-disable-line require-jsdoc
  static propTypes = {
    event: PropTypes.object.isRequired,
    navigator: PropTypes.object,
    showActionSheetWithOptions: PropTypes.func,
    refresh: PropTypes.func,
    refreshing: PropTypes.bool,
    alertWithType: PropTypes.func.isRequired,
  }

  state = {
    passengers: [],
    pickedUpUsers: 0,
    selfIsDriver: this.props.event.yourRide.driver === global.firebaseApp.auth().currentUser.uid,
  }

  componentWillMount() {
    const passengers = [];
    let pickedUpUsers = 0;
    global.firebaseApp.database()
    .ref('users')
    .child(this.props.event.yourRide.driver)
    .once('value')
    .then(userSnap => {
      passengers.push({
        userUID: this.props.event.yourRide.driver,
        ...userSnap.val(),
        type: 'driver',
      });

      // now get other users and push to arr
      if (this.props.event.yourRide.passengers) {
        this.props.event.yourRide.passengers.slice().forEach(pass => {
          global.firebaseApp.database()
          .ref('users')
          .child(pass.userUID)
          .once('value')
          .then(passSnap => {
            passengers.push({
              ...pass,
              ...passSnap.val(),
              type: 'rider',
            });
            if (pass.isPickedUp) {
              pickedUpUsers++;
            }
            this.setState(() => {
              return {
                passengers,
                pickedUpUsers,
              };
            });
          });
        });
      }
      this.setState(() => {
        return {
          passengers,
        };
      });
    })
    .catch(err => {
      this.props.alertWithType('error', 'Error', err.toString());
    });
  }

  ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })

  _onOpenActionSheet = () => {
    // Same interface as https://facebook.github.io/react-native/docs/actionsheetios.html
    const options = ['Leave Ride', 'Navigate', 'Cancel'];
    const destructiveButtonIndex = 0;
    const navigateButtonIndex = 1;
    const cancelButtonIndex = 2;
    this.props.showActionSheetWithOptions({
      options,
      cancelButtonIndex,
      destructiveButtonIndex,
    },
    (buttonIndex) => {
      if (buttonIndex === destructiveButtonIndex) {
        if (this.state.selfIsDriver) {
          Alert.alert(
            Platform.OS === 'ios' ? 'Leave Ride' : 'Leave ride',
            'Are you sure? Leaving this ride will strand your passengers. 😢',
            [
              { text: 'Cancel', style: 'cancel' },
              {
                text: 'OK',
                onPress: () => {
                  global.firebaseApp.database()
                    .ref('schools')
                    .child(this.props.event.schoolUID)
                    .child('events')
                    .child(this.props.event.uid)
                    .child('rides')
                    .child(this.props.event.yourRide.uid)
                    .remove()
                    .then(() => {
                      Notifications.cancelScheduledNotificationAsync(this.props.event.yourRide.notiID);
                      this.props.alertWithType('error', '😢', `You left ${this.props.event.name}.`);
                      this.props.refresh(false);
                    })
                    .catch(err => {
                      this.props.alertWithType('error', 'Error', err.toString());
                    });
                },
              },
            ]
          );
        } else {
          Alert.alert(
            Platform.OS === 'ios' ? 'Leave Ride' : 'Leave ride',
            'Are you sure? Leaving this ride so not lit.',
            [
              { text: 'Cancel', style: 'cancel' },
              {
                text: 'OK',
                onPress: () => {
                  const passIndex = this.props.event.yourRide.passengers.slice().findIndex(
                    i => i.userUID === global.firebaseApp.auth().currentUser.uid
                  );
                  global.firebaseApp.database()
                    .ref('schools')
                    .child(this.props.event.schoolUID)
                    .child('events')
                    .child(this.props.event.uid)
                    .child('rides')
                    .child(this.props.event.yourRide.uid)
                    .child('passengers')
                    .child(this.props.event.yourRide.passengers[passIndex].passUID)
                    .remove()
                    .then(() => {
                      this.props.alertWithType('error', '😢', `You left ${this.props.event.name}.`);
                      this.props.refresh(false);
                    })
                    .catch(err => {
                      this.props.alertWithType('error', 'Error', err.toString());
                    });
                },
              },
            ]
          );
        }
      }
      if (buttonIndex === navigateButtonIndex) {
        const wazeUrl = `waze://?ll=${this.props.event.location.geometry.location.lat},` +
        `${this.props.event.location.geometry.location.lng}&z=10&navigate=yes`;
        maybeOpenURL(wazeUrl, { appName: 'Waze', appStoreId: 'id323229106', playStoreId: 'com.waze' })
        .catch(err => {
          this.props.alertWithType('error', 'Error', err.toString());
        });
      }
    });
  }

  render() {
    return (
      <View style={ styles.container }>
        <View style={ styles.headerRow }>
          <Text style={ styles.label }>
            {this.props.event.name.toUpperCase()}
          </Text>
          <TouchableOpacity
            style={ styles.moreContainer }
            onPress={ this._onOpenActionSheet }
            // onPress open an action sheet
            hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }}
          >
            <View style={ styles.moreItem } />
            <View style={ styles.moreItem } />
            <View style={ styles.moreItem } />
          </TouchableOpacity>
        </View>
        <ListView
          enableEmptySections
          dataSource={ this.ds.cloneWithRows(this.state.passengers) }
          renderRow={ u => <Carpooler
            event={ this.props.event }
            refresh={ this.props.refresh }
            passengers={ this.state.passengers }
            pickedUpUsers={ this.state.pickedUpUsers }
            refreshing={ this.props.refreshing }
            user={ u }
            selfIsDriver={ this.state.selfIsDriver }
          /> }
        />
        { /* if everyone is pickedUp render 'start driving' button */ }
        <Choose>
          <When
            condition={
              this.state.selfIsDriver &&
              !this.props.event.yourRide.rideStarted &&
              this.state.passengers.length > 1 &&
              this.state.pickedUpUsers === this.state.passengers.length - 1
            }
          >
            <TouchableOpacity
              onPress={
                () => Alert.alert(
                  Platform.OS === 'ios' ? 'Start Ride' : 'Start ride',
                  'Are you sure? Just making sure you didn\'t click this by mistake.',
                  [
                    { text: 'Cancel', style: 'cancel' },
                    {
                      text: 'OK',
                      onPress: () => {
                        global.firebaseApp.database()
                        .ref('schools')
                        .child(this.props.event.schoolUID)
                        .child('events')
                        .child(this.props.event.uid)
                        .child('rides')
                        .child(this.props.event.yourRide.uid)
                        .update({
                          rideStarted: true,
                        }, () => {
                          const wazeUrl = `waze://?ll=${this.props.event.location.geometry.location.lat},` +
                          `${this.props.event.location.geometry.location.lng}&z=10&navigate=yes`;
                          maybeOpenURL(wazeUrl, { appName: 'Waze', appStoreId: 'id323229106', playStoreId: 'com.waze' })
                          .catch(err => {
                            this.props.alertWithType('error', 'Error', err.toString());
                          });
                        })
                        .catch(err => {
                          this.props.alertWithType('error', 'Error', err.toString());
                        });
                      },
                    },
                  ]
                )
              }
            >
              <ElevatedView
                style={ styles.startDrivingButton }
                elevation={ 4 }
              >
                <Text style={ styles.buttonText }>
                  START DRIVING
                </Text>
              </ElevatedView>
            </TouchableOpacity>
          </When>
          <When
            condition={ this.state.selfIsDriver && this.props.event.yourRide.rideStarted && !this.props.event.yourRide.rideCompleted }
          >
            <TouchableOpacity
              onPress={
                () => Alert.alert(
                  Platform.OS === 'ios' ? 'End Ride' : 'End ride',
                  'Are you sure? Just making sure you didn\'t click this by mistake.',
                  [
                    { text: 'Cancel', style: 'cancel' },
                    {
                      text: 'OK',
                      onPress: () => {
                        global.firebaseApp.database()
                        .ref('schools')
                        .child(this.props.event.schoolUID)
                        .child('events')
                        .child(this.props.event.uid)
                        .child('rides')
                        .child(this.props.event.yourRide.uid)
                        .update({
                          rideCompleted: true,
                        }, () => {
                          this.props.alertWithType('success', 'YEET', 'Aye you made it!');
                        })
                        .catch(err => {
                          this.props.alertWithType('error', 'Error', err.toString());
                        });
                      },
                    },
                  ]
                )
              }
            >
              <ElevatedView
                style={ styles.rideCompleteButton }
                elevation={ 4 }
              >
                <Text style={ styles.buttonText }>
                  COMPLETE RIDE
                </Text>
              </ElevatedView>
            </TouchableOpacity>
          </When>
          <When condition={ this.state.selfIsDriver && this.state.passengers.length === 1 }>
            <Text
              style={{
                fontFamily: 'open-sans-semibold',
                fontSize: 18,
                alignSelf: 'center',
                paddingTop: 16,
              }}
            >
              NO PASSENGERS AVAILABLE
            </Text>
          </When>
          <When condition={ this.props.event.yourRide.rideStarted && !this.props.event.yourRide.rideCompleted }>
            <Text
              style={{
                fontFamily: 'open-sans-semibold',
                fontSize: 18,
                alignSelf: 'center',
                paddingTop: 16,
              }}
            >
              RIDE IN PROGRESS
            </Text>
          </When>
          <When condition={ this.props.event.yourRide.rideCompleted }>
            <Text
              style={{
                fontFamily: 'open-sans-semibold',
                fontSize: 18,
                alignSelf: 'center',
                paddingTop: 16,
              }}
            >
              RIDE COMPLETED
            </Text>
          </When>
        </Choose>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingVertical: 8,
  },
  label: {
    fontFamily: 'open-sans-semibold',
    fontSize: 12,
    color: 'rgba(128, 128, 128, 0.7)',
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginHorizontal: 8,
    paddingBottom: 4,
  },
  moreContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: 24,
  },
  moreItem: {
    backgroundColor: '#546E7A',
    height: 5,
    width: 5,
    borderRadius: 5,
  },
  startDrivingButton: {
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
    marginHorizontal: 8,
    paddingVertical: 8,
    marginTop: 8,
    backgroundColor: colors.purp,
  },
  rideCompleteButton: {
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
    marginHorizontal: 8,
    paddingVertical: 8,
    marginTop: 8,
    backgroundColor: colors.neonGreen,
  },
  buttonText: {
    fontFamily: 'open-sans-bold',
    fontSize: 18,
    color: 'white',
  },
});
<|endoftext|>


<commit_before>"use strict";

var ADB = require('./adb.js')
  , mkdirp = require('mkdirp')
  , _ = require('underscore')
  , deviceCommon = require('../common.js')
  , androidController = require('./android-controller.js')
  , proxyTo = deviceCommon.proxyTo
  , getLog = deviceCommon.getLog
  , getLogTypes = deviceCommon.getLogTypes
  , logger = require('../../server/logger.js').get('appium')
  , status = require("../../server/status.js")
  , fs = require('fs')
  , async = require('async')
  , helpers = require('../../helpers.js')
  , getTempPath = helpers.getTempPath
  , androidCommon = require('./android-common.js')
  , path = require('path');

var Selendroid = function(opts) {
  this.opts = opts;
  this.opts.devicePort = 8080;
  this.opts.systemPort = opts.systemPort;
  this.avdName = opts.avdName || null;
  this.appWaitActivity = opts.appWaitActivity;
  this.serverApk = null;
  this.appPackage = opts.appPackage;
  this.apkPath = opts.apkPath;
  this.appActivity = opts.appActivity;
  this.desiredCaps = opts.desiredCaps;
  this.onStop = function() {};
  this.selendroidSessionId = null;
  this.adb = null;
  this.isProxy = true;
  this.mobileMethodsSupported = [
    'setLocation'
    , 'setCommandTimeout'
    , 'getCommandTimeout'
    , 'reset'
    , 'lock'
    , 'keyevent'
    , 'currentActivity'
    , 'installApp'
    , 'removeApp'
    , 'isAppInstalled'
  ];
  this.proxyHost = 'localhost';
  this.proxyPort = opts.systemPort;
  this.avoidProxy = [
    ['GET', new RegExp('^/wd/hub/session/[^/]+/log/types$')]
    , ['POST', new RegExp('^/wd/hub/session/[^/]+/log')]
  ];
};

Selendroid.prototype.start = function(cb) {
  logger.info("Starting selendroid server");
  this.adb = new ADB(this.opts);

  var modServerExists = false
    , modAppPkg = this.appPackage + '.selendroid';
  this.selendroidServerPath = path.resolve(getTempPath(),
      'selendroid.' + this.appPackage + '.apk');

  var checkModServerExists = function(cb) {
    fs.stat(this.selendroidServerPath, function(err) {
      modServerExists = !err;
      cb();
    });
  }.bind(this);

  var conditionalUninstallSelendroid = function(cb) {
    if (!modServerExists) {
      logger.info("Rebuilt selendroid apk does not exist, uninstalling " +
                  "any instances of it on device to make way for new one");
      this.adb.uninstallApk(modAppPkg, cb);
    } else {
      logger.info("Rebuilt selendroid apk exists, doing nothing");
      cb();
    }
  }.bind(this);

  var conditionalInsertManifest = function(cb) {
    if (!modServerExists) {
      logger.info("Rebuilt selendroid server does not exist, inserting " +
                  "modified manifest");
      this.insertSelendroidManifest(this.serverApk, cb);
    } else {
      logger.info("Rebuilt selendroid server already exists, no need to " +
                  "rebuild it with a new manifest");
      cb();
    }
  }.bind(this);

  var conditionalInstallSelendroid = function(cb) {
    this.adb.isAppInstalled(modAppPkg, function(e, installed) {
      if (!installed) {
        logger.info("Rebuilt selendroid is not installed, installing it");
        this.adb.install(this.selendroidServerPath, cb);
      } else {
        logger.info("Rebuilt selendroid is already installed");
        cb();
      }
    }.bind(this));
  }.bind(this);

  async.series([
    this.ensureServerExists.bind(this),
    this.prepareDevice.bind(this),
    checkModServerExists,
    conditionalUninstallSelendroid,
    conditionalInsertManifest,
    this.checkSelendroidCerts.bind(this),
    conditionalInstallSelendroid,
    this.installApp.bind(this),
    this.forwardPort.bind(this),
    this.pushUnlock.bind(this),
    this.unlockScreen.bind(this),
    this.pushSelendroid.bind(this),
    this.waitForServer.bind(this),
  ], function(err) {
    if (err) return cb(err);
    this.createSession(cb);
  }.bind(this));
};

Selendroid.prototype.pushSelendroid = function(cb) {
  var instrumentWith = this.appPackage + ".selendroid/" +
                       "io.selendroid.ServerInstrumentation";
  this.adb.instrument(this.appPackage, this.appActivity, instrumentWith, cb);
};

Selendroid.prototype.checkSelendroidCerts = function(cb) {
  var alreadyReturned = false
    , checks = 0;

  var onDoneSigning = function() {
    checks++;
    if (checks === 2 && !alreadyReturned) {
      cb();
    }
  };

  // these run in parallel
  var apks = [this.selendroidServerPath, this.apkPath];
  _.each(apks, function(apk) {
    logger.info("Checking signed status of " + apk);
    this.adb.checkApkCert(apk, this.appPackage, function(err, isSigned) {
      if (err) return cb(err);
      if (isSigned) return onDoneSigning();
      this.adb.sign([apk], function(err) {
        if (err && !alreadyReturned) {
          alreadyReturned = true;
          return cb(err);
        }
        onDoneSigning();
      });
    }.bind(this));
  }.bind(this));
};

Selendroid.prototype.stop = function(cb) {
  logger.info("Stopping selendroid server");
  this.deleteSession(function(err) {
    cb(err ? 1 : 0);
  });
};

Selendroid.prototype.keyevent = function(keycode, metastate, cb) {
  this.adb.keyevent(keycode, function() {
    cb(null, {
      status: status.codes.Success.code
      , value: null
    });
  });
};

Selendroid.prototype.ensureServerExists = function(cb) {
  logger.info("Checking whether selendroid is built yet");
  var selBin = path.resolve(__dirname, "..", "..", "..", "build", "selendroid",
      "selendroid.apk");
  fs.stat(selBin, function(err) {
    if (err) {
      logger.info("Selendroid needs to be built; please run ./reset.sh " +
                  "--selendroid");
      return cb(err);
    }
    logger.info("Selendroid server exists!");
    this.serverApk = selBin;
    cb(null);
  }.bind(this));
};

Selendroid.prototype.waitForServer = function(cb) {
  var waitMs = 20000
    , intMs = 800
    , start = Date.now();

  var pingServer = function() {
    this.proxyTo('/wd/hub/status', 'GET', null, function(err, res, body) {
      if (body === null || typeof body === "undefined" || !body.trim()) {
        if (Date.now() - start < waitMs) {
          setTimeout(pingServer, intMs);
        } else {
          cb(new Error("Waited " + (waitMs / 1000) + " secs for " +
                       "selendroid server and it never showed up"));
        }
      } else {
        logger.info("Selendroid server is alive!");
        cb(null);
      }
    });
  }.bind(this);

  pingServer();
};

Selendroid.prototype.createSession = function(cb) {
  logger.info("Creating Selendroid session");
  var data = {desiredCapabilities: this.desiredCaps};
  this.proxyTo('/wd/hub/session', 'POST', data, function(err, res, body) {
    if (err) return cb(err);

    if (res.statusCode === 301 && body.sessionId) {
      logger.info("Successfully started selendroid session");
      this.selendroidSessionId = body.sessionId;
      this.adb.waitForActivity(this.appPackage, this.appActivity, 1800,
          function(err) {
        if (err) {
          logger.info("Selendroid hasn't started app yet, let's do it " +
                      "manually with adb.startApp");
          return this.adb.startApp(this.appPackage, this.appActivity, function(err) {
            if (err) return cb(err);
            return cb(null, body.sessionId);
          }.bind(this));
        }
        return cb(null, body.sessionId);
      }.bind(this), 1800);
    } else {
      logger.error("Selendroid create session did not work. Status was " +
                   res.statusCode + " and body was " + body);
      cb(new Error("Did not get session redirect from selendroid"));
    }
  }.bind(this));
};

Selendroid.prototype.deleteSession = function(cb) {
  var url = '/wd/hub/session/' + this.selendroidSessionId;
  this.proxyTo(url, 'DELETE', null, function(err, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb(new Error("Status was not 200"));
    this.adb.forceStop(this.appPackage, function(err) {
      if (err) return cb(err);
      this.adb.stopLogcat(cb);
    }.bind(this));
  }.bind(this));
};

Selendroid.prototype.proxyTo = proxyTo;
Selendroid.prototype.getLog = getLog;
Selendroid.prototype.getLogTypes = getLogTypes;

Selendroid.prototype.insertSelendroidManifest = function(serverPath, cb) {
  logger.info("Inserting selendroid manifest");
  var newServerPath = this.selendroidServerPath
    , newPackage = this.appPackage + '.selendroid'
    , srcManifest = path.resolve(__dirname, '..', '..', '..', 'build',
        'selendroid', 'AndroidManifest.xml')
    , dstDir = path.resolve(getTempPath(), this.appPackage)
    , dstManifest = path.resolve(dstDir, 'AndroidManifest.xml');

  try {
    fs.mkdirSync(dstDir);
  } catch (e) {
    if (e.message.indexOf("EEXIST") === -1) {
      throw e;
    }
  }
  fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8");
  async.series([
    function(cb) { mkdirp(dstDir, cb); }.bind(this),
    function(cb) { this.adb.checkSdkBinaryPresent("aapt", cb); }.bind(this),
    function(cb) { this.adb.compileManifest(dstManifest, newPackage,
      this.appPackage, cb); }.bind(this),
    function(cb) { this.adb.insertManifest(dstManifest, serverPath,
      newServerPath, cb); }.bind(this)
  ], cb);
};

_.extend(Selendroid.prototype, androidCommon);
Selendroid.prototype.setLocation = androidController.setLocation;

module.exports = Selendroid;
<commit_msg>bring back closeApp for selendroid (fix #1686)<commit_after>"use strict";

var ADB = require('./adb.js')
  , mkdirp = require('mkdirp')
  , _ = require('underscore')
  , deviceCommon = require('../common.js')
  , androidController = require('./android-controller.js')
  , proxyTo = deviceCommon.proxyTo
  , getLog = deviceCommon.getLog
  , getLogTypes = deviceCommon.getLogTypes
  , logger = require('../../server/logger.js').get('appium')
  , status = require("../../server/status.js")
  , fs = require('fs')
  , async = require('async')
  , helpers = require('../../helpers.js')
  , getTempPath = helpers.getTempPath
  , androidCommon = require('./android-common.js')
  , path = require('path');

var Selendroid = function(opts) {
  this.opts = opts;
  this.opts.devicePort = 8080;
  this.opts.systemPort = opts.systemPort;
  this.avdName = opts.avdName || null;
  this.appWaitActivity = opts.appWaitActivity;
  this.serverApk = null;
  this.appPackage = opts.appPackage;
  this.apkPath = opts.apkPath;
  this.appActivity = opts.appActivity;
  this.desiredCaps = opts.desiredCaps;
  this.onStop = function() {};
  this.selendroidSessionId = null;
  this.adb = null;
  this.isProxy = true;
  this.mobileMethodsSupported = [
    'setLocation'
    , 'setCommandTimeout'
    , 'getCommandTimeout'
    , 'reset'
    , 'lock'
    , 'keyevent'
    , 'currentActivity'
    , 'installApp'
    , 'removeApp'
    , 'closeApp'
    , 'isAppInstalled'
  ];
  this.proxyHost = 'localhost';
  this.proxyPort = opts.systemPort;
  this.avoidProxy = [
    ['GET', new RegExp('^/wd/hub/session/[^/]+/log/types$')]
    , ['POST', new RegExp('^/wd/hub/session/[^/]+/log')]
  ];
};

Selendroid.prototype.start = function(cb) {
  logger.info("Starting selendroid server");
  this.adb = new ADB(this.opts);

  var modServerExists = false
    , modAppPkg = this.appPackage + '.selendroid';
  this.selendroidServerPath = path.resolve(getTempPath(),
      'selendroid.' + this.appPackage + '.apk');

  var checkModServerExists = function(cb) {
    fs.stat(this.selendroidServerPath, function(err) {
      modServerExists = !err;
      cb();
    });
  }.bind(this);

  var conditionalUninstallSelendroid = function(cb) {
    if (!modServerExists) {
      logger.info("Rebuilt selendroid apk does not exist, uninstalling " +
                  "any instances of it on device to make way for new one");
      this.adb.uninstallApk(modAppPkg, cb);
    } else {
      logger.info("Rebuilt selendroid apk exists, doing nothing");
      cb();
    }
  }.bind(this);

  var conditionalInsertManifest = function(cb) {
    if (!modServerExists) {
      logger.info("Rebuilt selendroid server does not exist, inserting " +
                  "modified manifest");
      this.insertSelendroidManifest(this.serverApk, cb);
    } else {
      logger.info("Rebuilt selendroid server already exists, no need to " +
                  "rebuild it with a new manifest");
      cb();
    }
  }.bind(this);

  var conditionalInstallSelendroid = function(cb) {
    this.adb.isAppInstalled(modAppPkg, function(e, installed) {
      if (!installed) {
        logger.info("Rebuilt selendroid is not installed, installing it");
        this.adb.install(this.selendroidServerPath, cb);
      } else {
        logger.info("Rebuilt selendroid is already installed");
        cb();
      }
    }.bind(this));
  }.bind(this);

  async.series([
    this.ensureServerExists.bind(this),
    this.prepareDevice.bind(this),
    checkModServerExists,
    conditionalUninstallSelendroid,
    conditionalInsertManifest,
    this.checkSelendroidCerts.bind(this),
    conditionalInstallSelendroid,
    this.installApp.bind(this),
    this.forwardPort.bind(this),
    this.pushUnlock.bind(this),
    this.unlockScreen.bind(this),
    this.pushSelendroid.bind(this),
    this.waitForServer.bind(this),
  ], function(err) {
    if (err) return cb(err);
    this.createSession(cb);
  }.bind(this));
};

Selendroid.prototype.pushSelendroid = function(cb) {
  var instrumentWith = this.appPackage + ".selendroid/" +
                       "io.selendroid.ServerInstrumentation";
  this.adb.instrument(this.appPackage, this.appActivity, instrumentWith, cb);
};

Selendroid.prototype.checkSelendroidCerts = function(cb) {
  var alreadyReturned = false
    , checks = 0;

  var onDoneSigning = function() {
    checks++;
    if (checks === 2 && !alreadyReturned) {
      cb();
    }
  };

  // these run in parallel
  var apks = [this.selendroidServerPath, this.apkPath];
  _.each(apks, function(apk) {
    logger.info("Checking signed status of " + apk);
    this.adb.checkApkCert(apk, this.appPackage, function(err, isSigned) {
      if (err) return cb(err);
      if (isSigned) return onDoneSigning();
      this.adb.sign([apk], function(err) {
        if (err && !alreadyReturned) {
          alreadyReturned = true;
          return cb(err);
        }
        onDoneSigning();
      });
    }.bind(this));
  }.bind(this));
};

Selendroid.prototype.stop = function(cb) {
  logger.info("Stopping selendroid server");
  this.deleteSession(function(err) {
    cb(err ? 1 : 0);
  });
};

Selendroid.prototype.keyevent = function(keycode, metastate, cb) {
  this.adb.keyevent(keycode, function() {
    cb(null, {
      status: status.codes.Success.code
      , value: null
    });
  });
};

Selendroid.prototype.ensureServerExists = function(cb) {
  logger.info("Checking whether selendroid is built yet");
  var selBin = path.resolve(__dirname, "..", "..", "..", "build", "selendroid",
      "selendroid.apk");
  fs.stat(selBin, function(err) {
    if (err) {
      logger.info("Selendroid needs to be built; please run ./reset.sh " +
                  "--selendroid");
      return cb(err);
    }
    logger.info("Selendroid server exists!");
    this.serverApk = selBin;
    cb(null);
  }.bind(this));
};

Selendroid.prototype.waitForServer = function(cb) {
  var waitMs = 20000
    , intMs = 800
    , start = Date.now();

  var pingServer = function() {
    this.proxyTo('/wd/hub/status', 'GET', null, function(err, res, body) {
      if (body === null || typeof body === "undefined" || !body.trim()) {
        if (Date.now() - start < waitMs) {
          setTimeout(pingServer, intMs);
        } else {
          cb(new Error("Waited " + (waitMs / 1000) + " secs for " +
                       "selendroid server and it never showed up"));
        }
      } else {
        logger.info("Selendroid server is alive!");
        cb(null);
      }
    });
  }.bind(this);

  pingServer();
};

Selendroid.prototype.createSession = function(cb) {
  logger.info("Creating Selendroid session");
  var data = {desiredCapabilities: this.desiredCaps};
  this.proxyTo('/wd/hub/session', 'POST', data, function(err, res, body) {
    if (err) return cb(err);

    if (res.statusCode === 301 && body.sessionId) {
      logger.info("Successfully started selendroid session");
      this.selendroidSessionId = body.sessionId;
      this.adb.waitForActivity(this.appPackage, this.appActivity, 1800,
          function(err) {
        if (err) {
          logger.info("Selendroid hasn't started app yet, let's do it " +
                      "manually with adb.startApp");
          return this.adb.startApp(this.appPackage, this.appActivity, function(err) {
            if (err) return cb(err);
            return cb(null, body.sessionId);
          }.bind(this));
        }
        return cb(null, body.sessionId);
      }.bind(this), 1800);
    } else {
      logger.error("Selendroid create session did not work. Status was " +
                   res.statusCode + " and body was " + body);
      cb(new Error("Did not get session redirect from selendroid"));
    }
  }.bind(this));
};

Selendroid.prototype.deleteSession = function(cb) {
  var url = '/wd/hub/session/' + this.selendroidSessionId;
  this.proxyTo(url, 'DELETE', null, function(err, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb(new Error("Status was not 200"));
    this.adb.forceStop(this.appPackage, function(err) {
      if (err) return cb(err);
      this.adb.stopLogcat(cb);
    }.bind(this));
  }.bind(this));
};

Selendroid.prototype.proxyTo = proxyTo;
Selendroid.prototype.getLog = getLog;
Selendroid.prototype.getLogTypes = getLogTypes;

Selendroid.prototype.insertSelendroidManifest = function(serverPath, cb) {
  logger.info("Inserting selendroid manifest");
  var newServerPath = this.selendroidServerPath
    , newPackage = this.appPackage + '.selendroid'
    , srcManifest = path.resolve(__dirname, '..', '..', '..', 'build',
        'selendroid', 'AndroidManifest.xml')
    , dstDir = path.resolve(getTempPath(), this.appPackage)
    , dstManifest = path.resolve(dstDir, 'AndroidManifest.xml');

  try {
    fs.mkdirSync(dstDir);
  } catch (e) {
    if (e.message.indexOf("EEXIST") === -1) {
      throw e;
    }
  }
  fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8");
  async.series([
    function(cb) { mkdirp(dstDir, cb); }.bind(this),
    function(cb) { this.adb.checkSdkBinaryPresent("aapt", cb); }.bind(this),
    function(cb) { this.adb.compileManifest(dstManifest, newPackage,
      this.appPackage, cb); }.bind(this),
    function(cb) { this.adb.insertManifest(dstManifest, serverPath,
      newServerPath, cb); }.bind(this)
  ], cb);
};

_.extend(Selendroid.prototype, androidCommon);
Selendroid.prototype.setLocation = androidController.setLocation;

module.exports = Selendroid;
<|endoftext|>


<commit_before>var _conf = require('param.json');
var _os = require('os');
var _tools = require('graphdat-plugin-tools');

var _source = _os.hostname();
var _interval =  _conf.pollInterval || 1000;

var _last;

function poll()
{
	var cpus = _os.cpus();

	for(var idx = 0; idx < cpus.length; idx++)
	{
		var e = cpus[idx];
		e.total = 0;
		for(var t in e.times)
			e.total += e.times[t];
	}

	if (_last)
	{
		for(var idx = 0; idx < cpus.length; idx++)
		{
			var e = cpus[idx];
			var l = _last[idx];
			var user = (e.times.user - l.times.user)  /
					   (e.total - l.total);

			if (!isNaN(user))
				console.log('CPU_CORE %d %s-C%d', user, _source, idx + 1);
		}
	}

	_last = cpus;

	setTimeout(poll, _interval);
}

poll();
<commit_msg>param<commit_after>var _conf = require('./param.json');
var _os = require('os');
var _tools = require('graphdat-plugin-tools');

var _source = _os.hostname();
var _interval =  _conf.pollInterval || 1000;

var _last;

function poll()
{
	var cpus = _os.cpus();

	for(var idx = 0; idx < cpus.length; idx++)
	{
		var e = cpus[idx];
		e.total = 0;
		for(var t in e.times)
			e.total += e.times[t];
	}

	if (_last)
	{
		for(var idx = 0; idx < cpus.length; idx++)
		{
			var e = cpus[idx];
			var l = _last[idx];
			var user = (e.times.user - l.times.user)  /
					   (e.total - l.total);

			if (!isNaN(user))
				console.log('CPU_CORE %d %s-C%d', user, _source, idx + 1);
		}
	}

	_last = cpus;

	setTimeout(poll, _interval);
}

poll();
<|endoftext|>


<commit_before>import React from 'react';
import { CreateTask } from './CreateTask';
import expect, { createSpy } from 'expect';
import { shallow } from 'enzyme';

describe('<CreateTask />', () => {

  it('simulates click events', () => {
    const onButtonClick = createSpy();
    const wrapper = shallow(
      <CreateTask addToDo={ onButtonClick } />
    );
    wrapper.find('form').simulate('submit');
    expect(onButtonClick).toHaveBeenCalled();
  });
});
<commit_msg>create-task spec passing<commit_after>import React from 'react';
import { CreateTask } from './CreateTask';
import expect, { createSpy, spyOn } from 'expect';
import { shallow } from 'enzyme';

describe('<CreateTask />', () => {

  it('simulates submit event', () => {
    const addToDo = createSpy();
    const preventDefault = createSpy();
    const e = { preventDefault, currentTarget: {
      id: 1,
      title: '',
      description: ''
    }};

    const wrapper = shallow(
      <CreateTask addToDo={ addToDo } />
    );
    const form = wrapper.find('form');
    form.simulate('submit', e);
    expect(addToDo).toHaveBeenCalled();
    expect(preventDefault).toHaveBeenCalled();
  });
});
<|endoftext|>


<commit_before>require(['bootstrap'],function(){
	'use strict';
	require(['Router'],function(Router){
		// private vars
		var $window = $(window);

		/**
		 * Init the app object and export it to the window
		 */
		window.app = {
			viewport: {
				width:0,
				height:0
			}
		};

		/**
		 * Create the initialize function
		 */
		app.init = function () {
			this.setupViewport();
			this.router = new Router();
			Backbone.history.start();
		};
		/**
		 * Function needed to cache the viewport size
		 */
		app.setupViewport = function () {
			app.viewport.width = $window.width();
			app.viewport.height = $window.height();
			$window.trigger('update');
		};

		/**
		 *
		 * Trigger a delayed resize window event being able to listen it from everywhere
		 *
		 */
		$window.on('resize orientationchange',_.debounce(app.setupViewport,200));

		// run the app
		app.init();

	});
});<commit_msg>update: backbone main<commit_after>require(['bootstrap'],function(){
	'use strict';
	require(['Router'],function(Router){
		// private vars
		var $window = $(window);

		/**
		 * Init the app object and export it to the window
		 */
		window.app = {
			viewport: {
				width:0,
				height:0
			}
		};

		/**
		 * Create the initialize function
		 */
		app.init = function () {
			this.router = new Router();
			Backbone.history.start();
			this.setupViewport();
		};
		/**
		 * Function needed to cache the viewport size
		 */
		app.setupViewport = function () {
			app.viewport.width = $window.width();
			app.viewport.height = $window.height();
			console.log('s');
			$window.trigger('update');
		};

		/**
		 *
		 * Trigger a delayed resize window event being able to listen it from everywhere
		 *
		 */
		$window.on('resize orientationchange',_.debounce(app.setupViewport,200));

		// run the app
		app.init();

	});
});<|endoftext|>


<commit_before>// BASIC PLAYER CLASS
// init: function is our function constructor
// init: function initializes player
// this._super means reaching to the constructor of the entity
// spriteheight and spritewidth are telling us what the size of the image is.
// new me.Rect is the rectangle the player can walk into
game.PlayerBaseEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			sprtiteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBase";

		//sets the towers to not be on fire from the start
		//also allows it to swtich to an on fire tower when attacked
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},
	update:function(delta){
		if (this.health<=0) {
			//sets the tower to an on fire position
			this.broken = true;
			this.renderable.addAnimation("broken");

		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	onCollision: function(){

	}
});

game.EnemyBaseEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			sprtiteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBase";

		//sets the towers to not be on fire from the start
		//also allows it to swtich to an on fire tower when attacked
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},
	update:function(delta){
		if (this.health<=0) {
			this.broken = true;
			//sets the tower to an on fire position
			this.renderable.addAnimation("broken");
		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	onCollision: function(){

	}
});

game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			sprtiteheight: "64",
			spritewidth: "64",
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		this.body.setVelocity(5, 20);
		//makes the screen follow the player on both axis x and y
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk",[117, 118, 119 ,120, 121, 122, 123 , 124 , 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		if (me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
		}
		//allows player to move left
		else if (me.input.isKeyPressed("left")){
				this.body.vel.x -= this.body.accel.x * me.timer.tick;
		//filp x allows the player to turn the oppisite side of the orc sprites.
				this.flipX(false);
			}else{
			this.body.vel.x = 0;
		}

		if(me.input.isKeyPressed("jump")){
			if(!this.body.jumping && !this.body.falling){
				this.body.jumping = true;
				this.body.vel.y -= this.body.accel.y * me.timer.tick;
			}
		}

		if (me.input.isKeyPressed("attack")){
			if (!this.renderable.isCurrentAnimation("attack")){
				//sets the current animation to attack and oce that
				//is over it goes back to the idle position.
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the next time we start this sequence we begin
				//from the first animation, not wherever we left off when we
				//switched to another animation.
				this.renderable.setAnimationFrame();
			}
		}

		else if(this.body.vel.x !== 0){
			if (!this.renderable.isCurrentAnimation("walk")){
				 this.renderable.setCurrentAnimation("walk");
}			//sets player to idle or zero when not moving
			}else{
				this.renderable.setCurrentAnimation("idle");
			}

		this.body.update(delta);
		//it is updating the code so the animations run smooth
		this._super(me.Entity, "update", [delta]);
		return true;
	}

});<commit_msg>video 14 comments<commit_after>// BASIC PLAYER CLASS
// init: function is our function constructor
// init: function initializes player
// this._super means reaching to the constructor of the entity
// spriteheight and spritewidth are telling us what the size of the image is.
// new me.Rect is the rectangle the player can walk into
game.PlayerBaseEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			sprtiteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBase";

		//sets the towers to not be on fire from the start
		//also allows it to swtich to an on fire tower when attacked
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},
	update:function(delta){
		if (this.health<=0) {
			//sets the tower to an on fire position
			this.broken = true;
			this.renderable.addAnimation("broken");

		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	onCollision: function(){

	}
});

game.EnemyBaseEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			sprtiteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBase";

		//sets the towers to not be on fire from the start
		//also allows it to swtich to an on fire tower when attacked
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},
	update:function(delta){
		if (this.health<=0) {
			this.broken = true;
			//sets the tower to an on fire position
			this.renderable.addAnimation("broken");
		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	onCollision: function(){

	}
});

game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			sprtiteheight: "64",
			spritewidth: "64",
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		this.body.setVelocity(5, 20);
		//makes the screen follow the player on both axis x and y
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk",[117, 118, 119 ,120, 121, 122, 123 , 124 , 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		if (me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
		}
		//allows player to move left
		else if (me.input.isKeyPressed("left")){
				this.body.vel.x -= this.body.accel.x * me.timer.tick;
		//filp x allows the player to turn the oppisite side of the orc sprites.
				this.flipX(false);
			}else{
			this.body.vel.x = 0;
		}
		//allows the player to jump
		if(me.input.isKeyPressed("jump")){
			if(!this.body.jumping && !this.body.falling){
				this.body.jumping = true;
				this.body.vel.y -= this.body.accel.y * me.timer.tick;
			}
		}

		if (me.input.isKeyPressed("attack")){
			if (!this.renderable.isCurrentAnimation("attack")){
				//sets the current animation to attack and oce that
				//is over it goes back to the idle position.
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the next time we start this sequence we begin
				//from the first animation, not wherever we left off when we
				//switched to another animation.
				this.renderable.setAnimationFrame();
			}
		}

		else if(this.body.vel.x !== 0){
			if (!this.renderable.isCurrentAnimation("walk")){
				 this.renderable.setCurrentAnimation("walk");
}			//sets player to idle or zero when not moving
			}else{
				this.renderable.setCurrentAnimation("idle");
			}

		this.body.update(delta);
		//it is updating the code so the animations run smooth
		this._super(me.Entity, "update", [delta]);
		return true;
	}

});<|endoftext|>


<commit_before>#!/usr/bin/nodejs
/*jslint indent: 2, node: true*/
"use strict";

var program = require("commander"),
  pdf = require("./pdf.js"),
  paginator = require("./paginator.js"),
  html = require("./html.js"),
  phantomWrapper = require("./phantom-wrapper.js"),
  util = require("util"),
  fs = require("fs"),
  namp = require("namp"),
  images = require("./images.js"),
  options = require("./options.js");

function cleanup(callback) {
  phantomWrapper.cleanup(callback);
}

function fail(msg) {
  cleanup(function () {
    throw new Error(msg);
  });
}

function success(msg) {
  cleanup(function () {
    util.puts(msg);
    process.exit();
  });
}

function compileBook(file) {
  var markup;

  function generatedPdf(err, pathToPdf) {
    if (err) {
      fail(err);
      return;
    }

    success("pdf generated at: " + pathToPdf);
  }

  function generatedPages(err, pages) {
    if (err) {
      fail(err);
      return;
    }

    pdf.generatePdfFromPages(pages, program.output, generatedPdf);
  }

  function resolvedImages(err, markup) {
    if (err) {
      fail(err);
      return;
    }

    paginator.paginate(markup, generatedPages);
  }

  function setOptions(err) {
    if (err) {
      fail(err);
      return;
    }

    images.resolveImagesInMarkup(markup, program.pathToImages, resolvedImages);
  }

  function readFile(err, markdown) {
    var nampResult;
    if (err) {
      fail(err);
      return;
    }

    nampResult = namp(markdown);
    markup = html.prepMarkup(nampResult.html);
    options.set(nampResult.metadata, setOptions);
  }

  fs.readFile(file, { encoding: "utf-8" }, readFile);
}

program
  .version("0.0.5")
  .usage("[command] <file>");

program
  .command("book <file>")
  .action(compileBook);

program
  .command("*")
  .action(compileBook);

program.parse(process.argv);
<commit_msg>getting options from options module rather than program input<commit_after>#!/usr/bin/nodejs
/*jslint indent: 2, node: true*/
"use strict";

var program = require("commander"),
  pdf = require("./pdf.js"),
  paginator = require("./paginator.js"),
  html = require("./html.js"),
  phantomWrapper = require("./phantom-wrapper.js"),
  util = require("util"),
  fs = require("fs"),
  namp = require("namp"),
  images = require("./images.js"),
  options = require("./options.js");

function cleanup(callback) {
  phantomWrapper.cleanup(callback);
}

function fail(msg) {
  cleanup(function () {
    throw new Error(msg);
  });
}

function success(msg) {
  cleanup(function () {
    util.puts(msg);
    process.exit();
  });
}

function compileBook(file) {
  var markup;

  function generatedPdf(err, pathToPdf) {
    if (err) {
      fail(err);
      return;
    }

    success("pdf generated at: " + pathToPdf);
  }

  function generatedPages(err, pages) {
    if (err) {
      fail(err);
      return;
    }

    pdf.generatePdfFromPages(pages, options.output, generatedPdf);
  }

  function resolvedImages(err, markup) {
    if (err) {
      fail(err);
      return;
    }

    paginator.paginate(markup, generatedPages);
  }

  function setOptions(err) {
    if (err) {
      fail(err);
      return;
    }

    images.resolveImagesInMarkup(markup, options.pathToImages, resolvedImages);
  }

  function readFile(err, markdown) {
    var nampResult;
    if (err) {
      fail(err);
      return;
    }

    nampResult = namp(markdown);
    markup = html.prepMarkup(nampResult.html);
    options.set(nampResult.metadata, setOptions);
  }

  fs.readFile(file, { encoding: "utf-8" }, readFile);
}

program
  .version("0.0.5")
  .usage("[command] <file>");

program
  .command("book <file>")
  .action(compileBook);

program
  .command("*")
  .action(compileBook);

program.parse(process.argv);
<|endoftext|>


<commit_before>$(function() {

  /* L20n */

  var parser = new L20nParser(L20nEventEmitter);
  var compiler = new L20nCompiler(L20nEventEmitter, L20nParser);

  parser.addEventListener('error', function(e) {
    $("#errors").append("
Syntax error at position " + e.pos + "

" + e.message + "
");
  });
  compiler.addEventListener('error', function(e) {
    $("#errors").append("
" + e.name + " in entity " + e.entry + "

" + e.message + "
");
  });

  function update() {
    $("#output").empty();
    $("#errors").empty();
    var code = source.getValue();
    var ast = parser.parse(code);
    var data;
    try {
      var data = JSON.parse(context.getValue());
    } catch (e) {}
    var entries = compiler.compile(ast);
    for (var id in entries) {
      if (entries[id].expression) {
        $("#output").append("

" + id + "()

macro

");
        continue;
      }
      var val;
      try {
        val = entries[id].toString(data);
      } catch (e) {
        if (e instanceof compiler.ValueError) {
          val = e.source;
        } else {
          continue;
        }
      }
      $("#output").append("

" + id + "

" + val + "

");
    }
  }

  /* ACE */

  var source = ace.edit("source");
  source.getSession().setMode("ace/mode/clojure");
  source.getSession().on('change', update);

  var context = ace.edit("context");
  context.getSession().setMode("ace/mode/json");
  context.getSession().on('change', update);

  /* Linkify */

  function utf8_to_b64(str) {
      return window.btoa(unescape(encodeURIComponent(str)));
  }

  function b64_to_utf8(str) {
      return decodeURIComponent(escape(window.atob(str)));
  }

  function linkify() {
    var code = source.getValue();
    return window.location.href.split("#")[0] + '#' + utf8_to_b64(code);
  }

  /* Main Code */

  var hash = window.location.hash.slice(1);
  var content = (
    "<name \"L20n tinker\">\n" +
    "<welcome \"Welcome to {{ name }}\">\n"
  );

  if (hash) {
    content = b64_to_utf8(hash);
  }
  source.setValue(content);

  $('#share').popover({
    placement: 'bottom',
    html: true,
    title: 'Share URL',
    content: '<input id="share-url" type="text">',
  }).click(function() {
    $('#share-url').val(linkify()).focus().select();
    $(this).popover('toggle');
  });
});
<commit_msg>Better defaults<commit_after>$(function() {

  /* L20n */

  var parser = new L20nParser(L20nEventEmitter);
  var compiler = new L20nCompiler(L20nEventEmitter, L20nParser);

  parser.addEventListener('error', function(e) {
    $("#errors").append("
Syntax error at position " + e.pos + "

" + e.message + "
");
  });
  compiler.addEventListener('error', function(e) {
    $("#errors").append("
" + e.name + " in entity " + e.entry + "

" + e.message + "
");
  });

  function update() {
    $("#output").empty();
    $("#errors").empty();
    var code = source.getValue();
    var ast = parser.parse(code);
    var data;
    try {
      var data = JSON.parse(context.getValue());
    } catch (e) {}
    var entries = compiler.compile(ast);
    for (var id in entries) {
      if (entries[id].expression) {
        $("#output").append("

" + id + "()

macro

");
        continue;
      }
      var val;
      try {
        val = entries[id].toString(data);
      } catch (e) {
        if (e instanceof compiler.ValueError) {
          val = e.source;
        } else {
          continue;
        }
      }
      $("#output").append("

" + id + "

" + val + "

");
    }
  }

  /* ACE */

  var source = ace.edit("source");
  source.getSession().setMode("ace/mode/clojure");
  source.getSession().on('change', update);

  var context = ace.edit("context");
  context.getSession().setMode("ace/mode/json");
  context.getSession().on('change', update);

  /* Linkify */

  function utf8_to_b64(str) {
      return window.btoa(unescape(encodeURIComponent(str)));
  }

  function b64_to_utf8(str) {
      return decodeURIComponent(escape(window.atob(str)));
  }

  function linkify() {
    var code = source.getValue();
    return window.location.href.split("#")[0] + '#' + utf8_to_b64(code);
  }

  /* Main Code */

  var hash = window.location.hash.slice(1);
  var content = (
    "<name \"L20n tinker\">\n" +
    "<welcome \"Welcome to {{ name }}\">\n" +
    "\n" +
    "<plural($n) { $n == 1 ? \"one\" : \"many\" }>\n" +
    "<turnout[plural($people)] {\n" +
    "  one: \"There's one person in the room.\",\n" +
    "  many: \"There are {{ $people }} people in the room.\"\n" +
    "}>"
  );
  var ctxdata = (
    "{\n" +
    "  \"people\": 7\n" +
    "}"
  );

  if (hash) {
    content = b64_to_utf8(hash);
  }
  source.setValue(content);
  context.setValue(ctxdata);

  $('#share').popover({
    placement: 'bottom',
    html: true,
    title: 'Share URL',
    content: '<input id="share-url" type="text">',
  }).click(function() {
    $('#share-url').val(linkify()).focus().select();
    $(this).popover('toggle');
  });
});
<|endoftext|>


<commit_before>/**
 * @file Slice Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */

import { Vector3 } from "../../lib/three.es6.js";

import { ColorMakerRegistry } from "../globals.js";
import { defaults } from "../utils.js";
import Representation from "./representation.js";
import ImageBuffer from "../buffer/image-buffer.js";

function SliceRepresentation( volume, viewer, params ){

    Representation.call( this, volume, viewer, params );

    this.volume = volume;

    this.build();

}

SliceRepresentation.prototype = Object.assign( Object.create(

    Representation.prototype ), {

    constructor: SliceRepresentation,

    type: "slice",

    parameters: Object.assign( {

        filter: {
            type: "select", buffer: true, options: {
                "nearest": "nearest",
                "linear": "linear",
                "cubic-bspline": "cubic-bspline",
                "cubic-catmulrom": "cubic-catmulrom",
                "cubic-mitchell": "cubic-mitchell"
            }
        },
        position: {
            type: "range", step: 0.1, max: 100, min: 1,
            rebuild: true
        },
        dimension: {
            type: "select", rebuild: true, options: {
                "x": "x", "y": "y", "z": "z"
            }
        },
        thresholdType: {
            type: "select", rebuild: true, options: {
                "value": "value", "sigma": "sigma"
            }
        },
        thresholdMin: {
            type: "number", precision: 3, max: Infinity, min: -Infinity, rebuild: true
        },
        thresholdMax: {
            type: "number", precision: 3, max: Infinity, min: -Infinity, rebuild: true
        },

    }, Representation.prototype.parameters, {

        flatShaded: null,
        side: null,
        wireframe: null,
        linewidth: null,
        colorScheme: null,

        roughness: null,
        metalness: null,
        diffuse: null,

    } ),

    init: function( params ){

        var p = params || {};
        p.colorScheme = defaults( p.colorScheme, "value" );
        p.colorScale = defaults( p.colorScale, "Spectral" );

        Representation.prototype.init.call( this, p );

        this.colorScheme = "value";
        this.dimension = "x";
        this.filter = defaults( p.filter, "cubic-bspline" );
        this.position = defaults( p.position, 30 );
        this.thresholdType = defaults( p.thresholdType, "sigma" );
        this.thresholdMin = defaults( p.thresholdMin, -Infinity );
        this.thresholdMax = defaults( p.thresholdMax, Infinity );

    },

    attach: function( callback ){

        this.bufferList.forEach( function( buffer ){

            this.viewer.add( buffer );

        }, this );

        this.setVisibility( this.visible );

        callback();

    },

    create: function(){

        var p = this.position;
        var v = this.volume;
        v.filterData( -Infinity, Infinity, false );
        var d = v.data;
        var m = v.matrix;

        function pos( dimLen ){
            return Math.round( ( dimLen  / 100 ) * ( p - 1 ) )
        }

        function index( x, y, z, i ){
            return ( z * v.ny * v.nx + y * v.nx + x ) * 3 + i;
        }

        var position = new Float32Array( 4 * 3 );
        var width, height;
        var x0, y0, z0, nx, ny, nz;

        var x0 = 0, y0 = 0, z0 = 0;
        var nx = v.nx, ny = v.ny, nz = v.nz;
        var vec = new Vector3();

        if( this.dimension === "x" ){

            var x = pos( v.nx );
            var y = v.ny-1;
            var z = v.nz-1;

            width = v.nz;
            height = v.ny;

            x0 = x;
            nx = x0 + 1;

            vec.set( x, 0, 0 ).applyMatrix4( m ).toArray( position, 0 );
            vec.set( x, y, 0 ).applyMatrix4( m ).toArray( position, 3 );
            vec.set( x, 0, z ).applyMatrix4( m ).toArray( position, 6 );
            vec.set( x, y, z ).applyMatrix4( m ).toArray( position, 9 );

        }else if( this.dimension === "y" ){

            var x = v.nx-1;
            var y = pos( v.ny );
            var z = v.nz-1;

            width = v.nz;
            height = v.nx;

            y0 = y;
            ny = y0 + 1;

            vec.set( 0, y, 0 ).applyMatrix4( m ).toArray( position, 0 );
            vec.set( x, y, 0 ).applyMatrix4( m ).toArray( position, 3 );
            vec.set( 0, y, z ).applyMatrix4( m ).toArray( position, 6 );
            vec.set( x, y, z ).applyMatrix4( m ).toArray( position, 9 );

        }else if( this.dimension === "z" ){

            var x = v.nx-1;
            var y = v.ny-1;
            var z = pos( v.nz );

            width = v.nx;
            height = v.ny;

            z0 = z;
            nz = z0 + 1;

            vec.set( 0, 0, z ).applyMatrix4( m ).toArray( position, 0 );
            vec.set( 0, y, z ).applyMatrix4( m ).toArray( position, 3 );
            vec.set( x, 0, z ).applyMatrix4( m ).toArray( position, 6 );
            vec.set( x, y, z ).applyMatrix4( m ).toArray( position, 9 );

        }

        var i = 0;
        var data = new Uint8Array( width * height * 4 );

        var min, max;
        if( this.thresholdType === "sigma" ){
            min = v.getValueForSigma( this.thresholdMin );
            max = v.getValueForSigma( this.thresholdMax );
        }else{
            min = this.thresholdMin;
            max = this.thresholdMax;
        }

        var cp = this.getColorParams( { volume: v } );
        cp.domain = [ v.getDataMin(), v.getDataMax() ];
        var colorMaker = ColorMakerRegistry.getScheme( cp );
        var tmp = new Float32Array( 3 );

        for ( var iy = y0; iy < ny; ++iy ) {
            for ( var ix = x0; ix < nx; ++ix ) {
                for ( var iz = z0; iz < nz; ++iz ) {

                    var idx = index( ix, iy, iz, 0 ) / 3;
                    var val = d[ idx ];
                    colorMaker.volumeColorToArray( idx, tmp );
                    data[ i     ] = Math.round( tmp[ 0 ] * 255 );
                    data[ i + 1 ] = Math.round( tmp[ 1 ] * 255 );
                    data[ i + 2 ] = Math.round( tmp[ 2 ] * 255 );
                    data[ i + 3 ] = ( val > min && val < max ) ? 255 : 0;
                    i += 4;

                }
            }
        }

        var sliceBuffer = new ImageBuffer(
            position, data, width, height, { filter: this.filter }
        );

        this.bufferList.push( sliceBuffer );

    }

} );

export default SliceRepresentation;
<commit_msg>cleanup<commit_after>/**
 * @file Slice Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */

import { Vector3 } from "../../lib/three.es6.js";

import { ColorMakerRegistry } from "../globals.js";
import { defaults } from "../utils.js";
import Representation from "./representation.js";
import ImageBuffer from "../buffer/image-buffer.js";

function SliceRepresentation( volume, viewer, params ){

    Representation.call( this, volume, viewer, params );

    this.volume = volume;

    this.build();

}

SliceRepresentation.prototype = Object.assign( Object.create(

    Representation.prototype ), {

    constructor: SliceRepresentation,

    type: "slice",

    parameters: Object.assign( {

        filter: {
            type: "select", buffer: true, options: {
                "nearest": "nearest",
                "linear": "linear",
                "cubic-bspline": "cubic-bspline",
                "cubic-catmulrom": "cubic-catmulrom",
                "cubic-mitchell": "cubic-mitchell"
            }
        },
        position: {
            type: "range", step: 0.1, max: 100, min: 1,
            rebuild: true
        },
        dimension: {
            type: "select", rebuild: true, options: {
                "x": "x", "y": "y", "z": "z"
            }
        },
        thresholdType: {
            type: "select", rebuild: true, options: {
                "value": "value", "sigma": "sigma"
            }
        },
        thresholdMin: {
            type: "number", precision: 3, max: Infinity, min: -Infinity, rebuild: true
        },
        thresholdMax: {
            type: "number", precision: 3, max: Infinity, min: -Infinity, rebuild: true
        },

    }, Representation.prototype.parameters, {

        flatShaded: null,
        side: null,
        wireframe: null,
        linewidth: null,
        colorScheme: null,

        roughness: null,
        metalness: null,
        diffuse: null,

    } ),

    init: function( params ){

        var p = params || {};
        p.colorScheme = defaults( p.colorScheme, "value" );
        p.colorScale = defaults( p.colorScale, "Spectral" );

        Representation.prototype.init.call( this, p );

        this.colorScheme = "value";
        this.dimension = "x";
        this.filter = defaults( p.filter, "cubic-bspline" );
        this.position = defaults( p.position, 30 );
        this.thresholdType = defaults( p.thresholdType, "sigma" );
        this.thresholdMin = defaults( p.thresholdMin, -Infinity );
        this.thresholdMax = defaults( p.thresholdMax, Infinity );

    },

    attach: function( callback ){

        this.bufferList.forEach( function( buffer ){

            this.viewer.add( buffer );

        }, this );

        this.setVisibility( this.visible );

        callback();

    },

    create: function(){

        var p = this.position;
        var v = this.volume;
        v.filterData( -Infinity, Infinity, false );
        var d = v.data;
        var m = v.matrix;

        function pos( dimLen ){
            return Math.round( ( dimLen  / 100 ) * ( p - 1 ) )
        }

        function index( x, y, z, i ){
            return ( z * v.ny * v.nx + y * v.nx + x ) * 3 + i;
        }

        var position = new Float32Array( 4 * 3 );
        var width, height;
        var x, y, z;

        var x0 = 0, y0 = 0, z0 = 0;
        var nx = v.nx, ny = v.ny, nz = v.nz;
        var vec = new Vector3();

        if( this.dimension === "x" ){

            x = pos( v.nx );
            y = v.ny-1;
            z = v.nz-1;

            width = v.nz;
            height = v.ny;

            x0 = x;
            nx = x0 + 1;

            vec.set( x, 0, 0 ).applyMatrix4( m ).toArray( position, 0 );
            vec.set( x, y, 0 ).applyMatrix4( m ).toArray( position, 3 );
            vec.set( x, 0, z ).applyMatrix4( m ).toArray( position, 6 );
            vec.set( x, y, z ).applyMatrix4( m ).toArray( position, 9 );

        }else if( this.dimension === "y" ){

            x = v.nx-1;
            y = pos( v.ny );
            z = v.nz-1;

            width = v.nz;
            height = v.nx;

            y0 = y;
            ny = y0 + 1;

            vec.set( 0, y, 0 ).applyMatrix4( m ).toArray( position, 0 );
            vec.set( x, y, 0 ).applyMatrix4( m ).toArray( position, 3 );
            vec.set( 0, y, z ).applyMatrix4( m ).toArray( position, 6 );
            vec.set( x, y, z ).applyMatrix4( m ).toArray( position, 9 );

        }else if( this.dimension === "z" ){

            x = v.nx-1;
            y = v.ny-1;
            z = pos( v.nz );

            width = v.nx;
            height = v.ny;

            z0 = z;
            nz = z0 + 1;

            vec.set( 0, 0, z ).applyMatrix4( m ).toArray( position, 0 );
            vec.set( 0, y, z ).applyMatrix4( m ).toArray( position, 3 );
            vec.set( x, 0, z ).applyMatrix4( m ).toArray( position, 6 );
            vec.set( x, y, z ).applyMatrix4( m ).toArray( position, 9 );

        }

        var i = 0;
        var data = new Uint8Array( width * height * 4 );

        var min, max;
        if( this.thresholdType === "sigma" ){
            min = v.getValueForSigma( this.thresholdMin );
            max = v.getValueForSigma( this.thresholdMax );
        }else{
            min = this.thresholdMin;
            max = this.thresholdMax;
        }

        var cp = this.getColorParams( { volume: v } );
        cp.domain = [ v.getDataMin(), v.getDataMax() ];
        var colorMaker = ColorMakerRegistry.getScheme( cp );
        var tmp = new Float32Array( 3 );

        for ( var iy = y0; iy < ny; ++iy ) {
            for ( var ix = x0; ix < nx; ++ix ) {
                for ( var iz = z0; iz < nz; ++iz ) {

                    var idx = index( ix, iy, iz, 0 ) / 3;
                    var val = d[ idx ];
                    colorMaker.volumeColorToArray( idx, tmp );
                    data[ i     ] = Math.round( tmp[ 0 ] * 255 );
                    data[ i + 1 ] = Math.round( tmp[ 1 ] * 255 );
                    data[ i + 2 ] = Math.round( tmp[ 2 ] * 255 );
                    data[ i + 3 ] = ( val > min && val < max ) ? 255 : 0;
                    i += 4;

                }
            }
        }

        var sliceBuffer = new ImageBuffer(
            position, data, width, height, { filter: this.filter }
        );

        this.bufferList.push( sliceBuffer );

    }

} );

export default SliceRepresentation;
<|endoftext|>


<commit_before>//Functions

function point(centreX, centreY, label) {
  // Allows creating a point with a centre and a label.
  // reduces var A = {cx:80, cy:160, label:"A"}; to A = new point( 80, 160, "A");
  // Some debate about this method: The ideal method would not 'draw' a circle
  // Also, it's more convenient to write A.cx instead of A.attr("cx")

  myPoint = drawing.append("circle")
  .classed('point', true)
  .style("stroke", "none")
  .style("fill", "none")
  .attr("r", 0)
  .attr("cx", parseInt(centreX))
  .attr("cy", parseInt(centreY))
  .attr("label", label)

  return myPoint
}

function lineFromTwoPoints( A, B, strokeWidth, colour ) {
  if (typeof colour == 'undefined'){
    colour = "rgba(0,0,50,1)";
  }
  if (typeof strokeWidth == 'undefined'){
    strokeWidth = 1;
  }

  var myLine = drawing.append("svg:line")
  //x to the left
  .attr("x1", A.attr("cx"))
  .attr("y1", A.attr("cy"))
  .attr("x2", B.attr("cx"))
  .attr("y2", B.attr("cy"))
  .attr("stroke-width", strokeWidth)
  .style("stroke", colour);

  return myLine;
}

function circle(point, radius){
  // Simply draws a circle. Does not create variables such as "circle1 = new circle(A, 50)"
  drawing.append("circle")
  .style("stroke", "black")
  .style("fill", "none")
  .attr("r", radius)
  .attr("cx", point.cx)
  .attr("cy", point.cy);
}

function pointsOnACircle (whichpoint, numberOfPoints, cx, cy, radius) {
  //Returns a point along the outside of a circle, starting at (whichpoint=1) = 0 degress
  //Could be simpler, but ran in to problems when debugging: Adding all points to an array filled the array with a single point

  //Normally used with:
  //       for (var i = 1; i < (numberOfPoints+1); i++) {
  //           pointsOnACircleArray[pointsOnACircleArray.length] = new pointsOnACircle (i, numberOfPoints, cx, cy, radius);
  //       }

  eachpoint = whichpoint * 2 * Math.PI/numberOfPoints;
  this.cx = cx+radius*Math.sin(eachpoint);
  this.cy = cy-radius*Math.cos(eachpoint);
}<commit_msg>Added two circle functions. They receive a point and a radius, then output an unfilled or filled circle<commit_after>//Functions

function point(centreX, centreY, label) {
  // Allows creating a point with a centre and a label.
  // reduces var A = {cx:80, cy:160, label:"A"}; to A = new point( 80, 160, "A");
  // Some debate about this method: The ideal method would not 'draw' a circle
  // Also, it's more convenient to write A.cx instead of A.attr("cx")

  myPoint = drawing.append("circle")
  .classed('point', true)
  .style("stroke", "none")
  .style("fill", "none")
  .attr("r", 0)
  .attr("cx", parseInt(centreX))
  .attr("cy", parseInt(centreY))
  .attr("label", label)

  return myPoint
}

function lineFromTwoPoints( A, B, strokeWidth, colour ) {
  if (typeof colour == 'undefined'){
    colour = "rgba(0,0,50,1)";
  }
  if (typeof strokeWidth == 'undefined'){
    strokeWidth = 1;
  }

  var myLine = drawing.append("svg:line")
  //x to the left
  .attr("x1", A.attr("cx"))
  .attr("y1", A.attr("cy"))
  .attr("x2", B.attr("cx"))
  .attr("y2", B.attr("cy"))
  .attr("stroke-width", strokeWidth)
  .style("stroke", colour);

  return myLine;
}

function circle(point, radius, colour){
  // Simply draws a circle. Returns an object such as "circle1 = new circle(A, 50)"
  if (typeof colour == 'undefined'){
    colour = "black";
  }
  myCircle = drawing.append("circle")
  .style("stroke", colour)
  .style("fill", "none")
  .attr("r", radius)
  .attr("cx", point.attr("cx"))
  .attr("cy", point.attr("cy"))
  .attr("label", point.attr("label"))

  return myCircle;
}

function circleFilled (point, radius, colour){
  // Simply draws a circle. Does not create variables such as "circle1 = new circle(A, 50)"

  if (typeof colour == 'undefined'){
    colour = "black";
  }
  myFilledCircle = drawing.append("circle")
  .style("stroke", "none")
  .style("fill", colour)
  .attr("r", radius)
  .attr("cx", point.attr("cx"))
  .attr("cy", point.attr("cy"))
  .attr("label", point.attr("label"));

  return myFilledCircle;
}

function pointsOnACircle (whichpoint, numberOfPoints, cx, cy, radius) {
  //Returns a point along the outside of a circle, starting at (whichpoint=1) = 0 degress
  //Could be simpler, but ran in to problems when debugging: Adding all points to an array filled the array with a single point

  //Normally used with:
  //       for (var i = 1; i < (numberOfPoints+1); i++) {
  //           pointsOnACircleArray[pointsOnACircleArray.length] = new pointsOnACircle (i, numberOfPoints, cx, cy, radius);
  //       }

  eachpoint = whichpoint * 2 * Math.PI/numberOfPoints;
  this.cx = cx+radius*Math.sin(eachpoint);
  this.cy = cy-radius*Math.cos(eachpoint);
}<|endoftext|>


<commit_before>function fun1() {
    var rtl = document.getElementById('rtl').value;
    var rtr = document.getElementById('rtr').value;
    var rbl = document.getElementById('rbl').value;
    var rbr = document.getElementById('rbr').value;
    var ttl = document.getElementById('ttl');
    var ttr = document.getElementById('ttr');
    var tbr = document.getElementById('tbr');
    var tbl = document.getElementById('tbl');

    var block = document.getElementById('block');

    ttl.value = rtl;
    ttr.value = rtr;
    tbr.value = rbr;
    tbl.value = rbl;
    block.style.borderRadius = rtl + 'px ' + rtr + 'px ' + rbr + 'px ' + rbl + 'px ';
}

function move() {
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);

    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("label").innerHTML = width * 1 + '%';
        }
    }
}

function myMove() {
    var elem = document.getElementById("myAnimation");
    var pos = 0;
    var id = setInterval(frame, 10);

    function frame() {
        if (pos == 150) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }
}

function moneyConverter(valNum) {
    document.getElementById("outputrub").innerHTML = valNum * 60;
}

function plus() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 + num2;
    document.getElementById('out').innerHTML = resalt;
}

function minus() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 - num2;
    document.getElementById('out').innerHTML = resalt;
}

function um() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 * num2;
    document.getElementById('out').innerHTML = resalt;
}

function del() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 / num2;
    document.getElementById('out').innerHTML = resalt;
}

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive"
    } else {
        x.className = "topnav";

    }
}

document.getElementById('nav').onmouseover = function(event) {
    var target = event.target;
    if (target.className == 'menu-item') {
        var s = target.getElementsByClassName('submenu');
        closeMenu();
        s[0].style.display = 'block';
    }
}
document.onmouseover = function(event) {
    var target = event.target;
    console.log(event.target);
    if (target.className != 'menu-item' && target.className != 'submenu') {
        closeMenu();
    }
}

function closeMenu() {
    var menu = document.getElementById('nav');
    var subm = document.getElementsByClassName('submenu');
    for (var i = 0; i < subm.length; i++) {
        subm[i].style.display = "none";
    }
}

function myFunction() {
    var x = document.getElementById('myDiv');
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}
var close = document.getElementsByClassName("closebtn");
var i;
for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
        var div = this.parentElement;
        div.style.opacity = "0";
        setTimeout(function() {
            div.style.display = "none";
        }, 600);
    }
}<commit_msg>откроем переменные<commit_after>function fun1() {
    var rtl = document.getElementById('rtl').value;
    var rtr = document.getElementById('rtr').value;
    var rbl = document.getElementById('rbl').value;
    var rbr = document.getElementById('rbr').value;
    var ttl = document.getElementById('ttl');
    var ttr = document.getElementById('ttr');
    var tbr = document.getElementById('tbr');
    var tbl = document.getElementById('tbl');

    var block = document.getElementById('block');

    ttl.value = rtl;
    ttr.value = rtr;
    tbr.value = rbr;
    tbl.value = rbl;
    block.style.borderRadius = rtl + 'px ' + rtr + 'px ' + rbr + 'px ' + rbl + 'px ';
}

function move() {
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);

    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("label").innerHTML = width * 1 + '%';
        }
    }
}

function myMove() {
    var elem = document.getElementById("myAnimation");
    var pos = 0;
    var id = setInterval(frame, 10);

    function frame() {
        if (pos == 150) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }
}

function moneyConverter(valNum) {
    document.getElementById("outputrub").innerHTML = valNum * 60;
}

function plus() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 + num2;
    document.getElementById('out').innerHTML = resalt;
}

function minus() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 - num2;
    document.getElementById('out').innerHTML = resalt;
}

function um() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 * num2;
    document.getElementById('out').innerHTML = resalt;
}

function del() {
    var num1, num2, resalt;
    num1 = document.getElementById('n1').value;
    num1 = parseInt(num1);
    num2 = document.getElementById('n2').value;
    num2 = parseInt(num2);
    resalt = num1 / num2;
    document.getElementById('out').innerHTML = resalt;
}

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive"
    } else {
        x.className = "topnav";

    }
}

document.getElementById('nav').onmouseover = function(event) {
    var target = event.target;
    if (target.className == 'menu-item') {
        var s = target.getElementsByClassName('submenu');
        closeMenu();
        s[0].style.display = 'block';
    }
}
document.onmouseover = function(event) {
    var target = event.target;
    console.log(event.target);
    if (target.className != 'menu-item' && target.className != 'submenu') {
        closeMenu();
    }
}

function closeMenu() {
    var menu = document.getElementById('nav');
    var subm = document.getElementsByClassName('submenu');
    for (var i = 0; i < subm.length; i++) {
        subm[i].style.display = "none";
    }
}

function myFunction() {
    var x = document.getElementById('myDiv');
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}
var close = document.getElementsByClassName("closebtn");
var i;
for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
        var div = this.parentElement;
        div.style.opacity = "0";
        setTimeout(function() {
            div.style.display = "none";
        }, 600);
    }
}

var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
<|endoftext|>


<commit_before>Prism.languages.rip = {
	'comment': /#[^\r\n]*(\r?\n|$)/g,

	'keyword': /(?:=>|->)|\b(?:class|if|else|switch|case|return|exit|try|catch|finally|raise)\b/g,

	'builtin': /\b(@|System)\b/g,

	'boolean': /\b(true|false)\b/g,

	'date': /\b\d{4}-\d{2}-\d{2}\b/g,
	'time': /\b\d{2}:\d{2}:\d{2}\b/g,
	'datetime': /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\b/g,

	'number': /[+-]?(?:(?:\d+\.\d+)|(?:\d+))/g,

	'character': /\B`[^\s\`\'",.:;#\/\\()<>\[\]{}]\b/g,

	'regex': {
		pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/(?=\s*($|[\r\n,.;})]))/g,
		lookbehind: true
	},

	'symbol': /:[^\d\s\`\'",.:;#\/\\()<>\[\]{}][^\s\`\'",.:;#\/\\()<>\[\]{}]*/g,
	'string': /("|')(\\?.)*?\1/g
};
<commit_msg>Recognize punctuation and reference<commit_after>Prism.languages.rip = {
	'comment': /#[^\r\n]*(\r?\n|$)/g,

	'keyword': /(?:=>|->)|\b(?:class|if|else|switch|case|return|exit|try|catch|finally|raise)\b/g,

	'builtin': /\b(@|System)\b/g,

	'boolean': /\b(true|false)\b/g,

	'date': /\b\d{4}-\d{2}-\d{2}\b/g,
	'time': /\b\d{2}:\d{2}:\d{2}\b/g,
	'datetime': /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\b/g,

	'number': /[+-]?(?:(?:\d+\.\d+)|(?:\d+))/g,

	'character': /\B`[^\s\`\'",.:;#\/\\()<>\[\]{}]\b/g,

	'regex': {
		pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/(?=\s*($|[\r\n,.;})]))/g,
		lookbehind: true
	},

	'symbol': /:[^\d\s\`\'",.:;#\/\\()<>\[\]{}][^\s\`\'",.:;#\/\\()<>\[\]{}]*/g,
	'string': /("|')(\\?.)*?\1/g,

	'punctuation': /(?:\.{2,3})|[\`,.:;=\/\\()<>\[\]{}]/,

	'reference': /[^\d\s\`\'",.:;#\/\\()<>\[\]{}][^\s\`\'",.:;#\/\\()<>\[\]{}]*/g
};
<|endoftext|>


<commit_before>chorus.views.DashboardProjectList = chorus.views.Base.extend({
    constructorName: "DashboardProjectListView",
    templateName: "dashboard/project_list",

    setup: function (params) {
        this.projectCards = [];
        if(params.state === 'most_active') {
            this.mostActive = true;
            this.noFilter = true;
        }
        else {
            params.mostActive = false;
            if(this.state === 'all') {
                this.noFilter = true;
            }
            else {
                this.noFilter = false;
            }
        }
    },

    preRender: function () {
        _.invoke(this.projectCards, 'teardown');
        this.projectCards = this.collection.filter(this.filter, this).map(function (workspace) {
            var card = new chorus.views.ProjectCard({model: workspace});
            this.registerSubView(card);
            return card;
        }, this);
    },

    postRender: function () {
        _.each(this.projectCards, function(view) {
            this.$el.append(view.render().el);
        }, this);
    },

    triggerRender: function (bool) {
        this.noFilter = bool;
        this.render();
    },

    filter: function (project) {
        return this.noFilter || project.get('isMember');
    }
});<commit_msg>[Fixes #80595750] clicking on "All Workspaces" the first time should now bring up all worksapces<commit_after>chorus.views.DashboardProjectList = chorus.views.Base.extend({
    constructorName: "DashboardProjectListView",
    templateName: "dashboard/project_list",

    setup: function (params) {
        this.projectCards = [];
        if(params.state === 'most_active') {
            this.mostActive = true;
            this.noFilter = true;
        }
        else {
            this.mostActive = false;
            if(params.state === 'all') {
                this.noFilter = true;
            }
            else {
                this.noFilter = false;
            }
        }
    },

    preRender: function () {
        _.invoke(this.projectCards, 'teardown');
        this.projectCards = this.collection.filter(this.filter, this).map(function (workspace) {
            var card = new chorus.views.ProjectCard({model: workspace});
            this.registerSubView(card);
            return card;
        }, this);
    },

    postRender: function () {
        _.each(this.projectCards, function(view) {
            this.$el.append(view.render().el);
        }, this);
    },

    triggerRender: function (bool) {
        this.noFilter = bool;
        this.render();
    },

    filter: function (project) {
        return this.noFilter || project.get('isMember');
    }
});<|endoftext|>