<commit_before>var pk = pk || {};

/**
Create a new switch control

HTML:

	<input type='switch' id='switch' />

Javascript:

	pk.switch({
		element: document.getElementById('switch')
	});

@class pk.switch
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to control
@param [options.value] {Boolean} Initial value
@param [options.name=pk-switch-RandInt] {String} Name of underlying input control, defaults to the attribute value set on the passed element, or `pk-switch-RandInt`
@param [options.tabindex=0] {Number} Tabindex of control, defaults to the attribute value set on the passed element, or `0`
@param [options.disabled=false] {Boolean} Disabled state of control, defaults to the attribute value set on the passed element, or `false`
@param [options.listeners] {Object} Object array of event listeners to bind to underlying input(s)
@return Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function(pk) {
    pk.switch = function(opt) {
        var el = opt.element,
            //    listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputValue = opt.value || el.getAttribute('value') || 0,
            inputLabel = opt.label || el.getAttribute('label') || el.innerHTML,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputName = opt.name || el.getAttribute('name') || 'pk-switch-' + pk.getRand(1, 999),
            listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        /*jshint multistr:true */
        var str = "\
			<input type = 'checkbox'  id = '" + inputName + "'  name = '" + inputName + "'  value = '" + inputValue + "'  tabindex = '" + inputTabIndex + "' / >\
             " + inputLabel + " \
			 " + inputLabel + " \
		";

        el.innerHTML = '';
        el = pk.replaceEl(el, str);
        /**
        Gets or sets control value
        @method val
        @param [value] {String} Value to set
        @return {String} Returns current value
        */

        /**
        Gets or sets control disabled state
        @method disabled
        @param [boolean] {Boolean} Disabled state
        @return {Boolean} Returns disabled state
        */
        var obj = {
            0: el,
            val: function(val) {
                if (val === undefined) {
                    return inputValue;
                }
                pk.attribute(el.children[0], 'checked', Boolean(val));
            },
            disabled: function(val) {
                if (val !== undefined) {
                    pk.toggleClass(el, 'pk-disabled', Boolean(val));
                    pk.attribute(el.children[0], 'disabled', Boolean(val));
                }
                return pk.attribute(el.children[0], 'disabled');
            }
        };
        obj.val(inputValue);
        if (inputDisabled) {
            obj.disabled(true);
        }
        pk.bindListeners(listeners, el.children[0]);
        return obj;
    };
    return pk;
})(pk);
<commit_msg>Update switch.js<commit_after>var pk = pk || {};

/**
Create a new switch control

HTML:

	<input type='switch' id='switch' />

Javascript:

	pk.switch({
		element: document.getElementById('switch')
	});

@class pk.switch
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to control
@param [options.value] {Boolean} Initial value
@param [options.name=pk-switch-RandInt] {String} Name of underlying input control, defaults to the attribute value set on the passed element, or `pk-switch-RandInt`
@param [options.tabindex=0] {Number} Tabindex of control, defaults to the attribute value set on the passed element, or `0`
@param [options.disabled=false] {Boolean} Disabled state of control, defaults to the attribute value set on the passed element, or `false`
@param [options.listeners] {Object} Object array of event listeners to bind to underlying input(s)
@return Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function(pk) {
    pk.switch = function(opt) {
        var el = opt.element,
            //    listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputValue = opt.value || el.getAttribute('value') || true,
            inputLabel = opt.label || el.getAttribute('label') || el.innerHTML,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputName = opt.name || el.getAttribute('name') || 'pk-switch-' + pk.getRand(1, 999),
            listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        /*jshint multistr:true */
        var str = "\
			<input type = 'checkbox'  id = '" + inputName + "'  name = '" + inputName + "' tabindex = '" + inputTabIndex + "' / >\
             " + inputLabel + " \
			 " + inputLabel + " \
		";

        el.innerHTML = '';
        el = pk.replaceEl(el, str);

		pk.bindEvent("mousewheel", el, function(e) {
		 	pk.preventBubble(e);
			if (e.wheelDelta > 0 || e.detail < 0) {
                obj.val(false);
            }else{
				obj.val(true);
			}
        });
        /**
        Gets or sets control value
        @method val
        @param [value] {String} Value to set
        @return {String} Returns current value
        */

        /**
        Gets or sets control disabled state
        @method disabled
        @param [boolean] {Boolean} Disabled state
        @return {Boolean} Returns disabled state
        */
        var obj = {
            0: el,
            val: function(val) {
                if (val === undefined) {
                    return pk.attribute(el.children[0], 'checked');
                }
                pk.attribute(el.children[0], 'checked', Boolean(val));
            },
            disabled: function(val) {
                if (val !== undefined) {
                    pk.toggleClass(el, 'pk-disabled', Boolean(val));
                    pk.attribute(el.children[0], 'disabled', Boolean(val));
                }
                return pk.attribute(el.children[0], 'disabled');
            }
        };
        obj.val(inputValue);
        if (inputDisabled) {
            obj.disabled(true);
        }
        pk.bindListeners(listeners, el.children[0]);
        return obj;
    };
    return pk;
})(pk);
<|endoftext|>


<commit_before>/**
 * ingestion.js
 * expects:
 * 1. path of directory
 * 2. parentpid
 * 3. namespace
 * 4. model
 *   (note: basic image,large image,audio,video, collection, pdf, binary -- all require
 * the "ibsp" in the command string, book requires the "ibbp" part in the drush command.)
 * output:
 *  log of drush run
 * errors:
 *  if parameters missing
 *  if first command did not run
 *  if first command did run but did not prep ingest
 *  if first command ran with a good ingest but second command did not run
 *  if second ran but did not ingest
 *
 * @param target directory path
 * @param parentpid
 * @param namespace
 * @param model
 * @return $message
 *
 */
// for testing
//
var param = process.argv;
console.log('hi');
target = String(param[2]);
parentpid = String(param[3]);
namespace = String(param[4]);
model = String(param[5]);

function ingestion(target,parentpid,namespace,model) {
  // build command pieces
  // serveruri is the location of the drupal_home on the drupal server
  let drupalhome = '/vhosts/dlwork/web/collections';
  let serveruri = 'http://dlwork.lib.utk.edu/dev/';
  let parentpid = '';
  console.log('parentpid = '.parentpid.'\n');
  // namespace
  let namespace = '';
  console.log('namespace = '.namespace.'\n');
  // target is the local directory holding the ingest files
  let target = '';
  console.log('target = '.target.'\n');
  // make mongo connection
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost/ibu');
  var conn = mongoose.connection;
  //
  var $message = 'ingest did not happen';
  var contentmodel = '';
  if ((model)&& (model==='basic')) {
    contentmodel = 'islandora:sp_basic_image';
  }
  if ((model)&&(model==='large')) {
    contentmodel = 'islandora:sp_Large_image';
  }
  console.log('model = '.model.'\n');
  // execute first drush command
  var exec = require('child_process').exec;
  var cmd = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' ibsp --content_models='.contentmodel.' --type=directory --parent='.parentpid.' --namespace='.namespace.' --target='target;
  if ((target!='')&&(contentmodel!='')&&(parentpid!='')&&(namespace!='')) {
    exec(cmd, function(error, stdout, stderr) {
     // command output is in stdout
     //console.log(stdout);
     $message = 'ingest prep drush command success';
     status.push("$message");
    });
  }// end if
  else {
      console.log('parameters for first command missing\n');
      $message = 'parameters for first command missing';
      return $message;
  }
  // exec second drush command
  //var exec2 = require('child_process').exec;
  var cmd2 = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' islandora_batch_ingest';
  if ($message = 'ingest prep drush command success') {
    exec(cmd2, function(error, stdout, stderr) {
     // command output is in stdout
     console.log(stdout);
     $message = 'ingest drush command success';
     status.push("$message");
    });
  }// end if
  return $message;
}// end function
//export default ingestion;
ingestion();
<commit_msg>remove parentid init, not needed.<commit_after>/**
 * ingestion.js
 * expects:
 * 1. path of directory
 * 2. parentpid
 * 3. namespace
 * 4. model
 *   (note: basic image,large image,audio,video, collection, pdf, binary -- all require
 * the "ibsp" in the command string, book requires the "ibbp" part in the drush command.)
 * output:
 *  log of drush run
 * errors:
 *  if parameters missing
 *  if first command did not run
 *  if first command did run but did not prep ingest
 *  if first command ran with a good ingest but second command did not run
 *  if second ran but did not ingest
 *
 * @param target directory path
 * @param parentpid
 * @param namespace
 * @param model
 * @return $message
 *
 */
// for testing
//
var param = process.argv;
console.log('hi');
target = String(param[2]);
parentpid = String(param[3]);
namespace = String(param[4]);
model = String(param[5]);

function ingestion(target,parentpid,namespace,model) {
  // build command pieces
  // serveruri is the location of the drupal_home on the drupal server
  let drupalhome = '/vhosts/dlwork/web/collections';
  let serveruri = 'http://dlwork.lib.utk.edu/dev/';
  console.log('parentpid = '.parentpid.'\n');
  // namespace
  let namespace = '';
  console.log('namespace = '.namespace.'\n');
  // target is the local directory holding the ingest files
  let target = '';
  console.log('target = '.target.'\n');
  // make mongo connection
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost/ibu');
  var conn = mongoose.connection;
  //
  var $message = 'ingest did not happen';
  var contentmodel = '';
  if ((model)&& (model==='basic')) {
    contentmodel = 'islandora:sp_basic_image';
  }
  if ((model)&&(model==='large')) {
    contentmodel = 'islandora:sp_Large_image';
  }
  console.log('model = '.model.'\n');
  // execute first drush command
  var exec = require('child_process').exec;
  var cmd = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' ibsp --content_models='.contentmodel.' --type=directory --parent='.parentpid.' --namespace='.namespace.' --target='target;
  if ((target!='')&&(contentmodel!='')&&(parentpid!='')&&(namespace!='')) {
    exec(cmd, function(error, stdout, stderr) {
     // command output is in stdout
     //console.log(stdout);
     $message = 'ingest prep drush command success';
     status.push("$message");
    });
  }// end if
  else {
      console.log('parameters for first command missing\n');
      $message = 'parameters for first command missing';
      return $message;
  }
  // exec second drush command
  //var exec2 = require('child_process').exec;
  var cmd2 = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' islandora_batch_ingest';
  if ($message = 'ingest prep drush command success') {
    exec(cmd2, function(error, stdout, stderr) {
     // command output is in stdout
     console.log(stdout);
     $message = 'ingest drush command success';
     status.push("$message");
    });
  }// end if
  return $message;
}// end function
//export default ingestion;
ingestion();
<|endoftext|>


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

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

var HelloApp = React.createClass({
  render: function() {
    return (

      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>

      </View>

    );
  }
});

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

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

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

var HelloApp = React.createClass({
  render: function() {
    return (

      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>

    );
  }
});

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

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


<commit_before>/**
 * OneDo iOS App
 * https://github.com/virae
 */
'use strict';

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

var App = require('./application/components/App');

class SomeDay extends React.Component {

    render() {
        return (
            <App />
        );
    }
}

AppRegistry.registerComponent('SomeDay', () => SomeDay);
<commit_msg>Removing StyleSheet from index.ios.js<commit_after>/**
 * OneDo iOS App
 * https://github.com/virae
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry
} = React;

var App = require('./application/components/App');

class SomeDay extends React.Component {

    render() {
        return (
            <App />
        );
    }
}

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


<commit_before>'use strict';

var React = require('react-native');
var MapboxGLMap = require('react-native-mapbox-gl');

 var {
   AppRegistry,
   StyleSheet,
   View,
   Text,
   TextInput,
   StatusBarIOS,
   TouchableHighlight,
   NativeModules
 } = React;

 var map = React.createClass({
    watchID: (null: ?number),
    getInitialState() {
     return {
       mapLocation: {
         latitude: 0,
         longitude: 0,
         zoom: 12
        },
        center: {
          latitude: 40.72345355209305,
          longitude: -73.99343490600586
        },
        direction: 30
      }
   },
   onRegionChange(e) {
     this.setState({ mapLocation: e});
   },
   onCenterChange(e) {
     this.setState({ center: e});
   },
   componentDidMount() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      var lo = position.coords.longitude, la = position.coords.latitude;
      if (Math.abs(this.state.center.longitude-lo)>0.001||Math.abs(this.state.center.latitude-la)>0.001){
        this.onCenterChange({longitude: lo, latitude: la});
      }
    });
   },
  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  },
   render: function() {
     StatusBarIOS.setHidden(true)
     return (
       <View style={styles.container}>
         <TextInput
          autoCapitalize='none'
          placeholder='Search a place'
          autoCorrect={false}
          style={styles.default}/>
        <MapboxGLMap
          accessToken={'sk.eyJ1IjoiY29kZTRoayIsImEiOiJmN2JhYzhhOGMxMmM1ZTI1ZDJlOWRkNGZiYzliZTk4OSJ9.RdPsLMXx2XA0j1yJt2cPOw'}
          style={styles.map}
          styleURL={'asset://styles/mapbox-streets-v7.json'}
          centerCoordinate={this.state.center}
          // direction={this.state.direction}
          zoomLevel={this.state.mapLocation.zoom}
          onRegionChange={this.onRegionChange}
          onRegionWillChange={this.onRegionChange}
          rotateEnabled={false}
          showsUserLocation={true}/>
          <Text>direction: {this.state.direction}</Text>
          <Text>Latitude: {this.state.mapLocation.latitude}</Text>
          <Text>Longitude: {this.state.mapLocation.longitude}</Text>
          <Text>zoom level: {this.state.mapLocation.zoom}</Text>
        </View>
     );
   }
 });

 var styles = StyleSheet.create({
   container: {
     flexDirection: 'column',
     flex: 1
   },
   default: {
    flex: 0.5,
    paddingLeft: 10,
    fontSize: 13,
  },
   map: {
     flex:5,
   },
   text: {
     padding: 20
   }
 });

AppRegistry.registerComponent('hike4hk', () => map);
<commit_msg>add stats and start stop button<commit_after>'use strict';

var React = require('react-native');
var MapboxGLMap = require('react-native-mapbox-gl');
var Button = require('react-native-button');

 var {
   AppRegistry,
   StyleSheet,
   View,
   Text,
   TextInput,
   TouchableHighlight,
   NativeModules
 } = React;
 var map = React.createClass({
    watchID: (null: ?number),
    getInitialState() {
     return {
       mapLocation: {
         latitude: 40.72345355209305,
         longitude: -73.99343490600586,
         zoom: 14
        },
        center: {
          latitude: 40.72345355209305,
          longitude: -73.99343490600586
        },
        currentLocation: {
          latitude: 0,
          longitude: 0
        },
        startTime: 0,
        currentTime: 0,
        button_text: "Start",
        distance: 0,
        elevation: 0,
        pastAltitude: 0,
        showsUserLocation: true
      }
   },
   _handlePress(e) {
    if(this.state.button_text==="Start"){
      this.onStart();
      this.setState({showsUserLocation: true, distance:0, button_text: "Stop", startTime: 0, currentTime: 0, elevation: 0});
    }else{
      this.onStop();
      this.setState({showsUserLocation: false});
      this.setState({button_text: "Start"});
    }
   },
   onRegionChange(e) {
     this.setState({mapLocation: e});
   },
   onCenterChange(e) {
     this.setState({center: e});
   },
   timestampChanged(e) {
    if (this.state.startTime===0){
     this.setState({ currentTime: e, startTime: e});
    }else{
      this.setState({currentTime: e})
    }
   },
   onMove(longitude, latitude, altitude){
    if (this.state.currentLocation.latitude!=0 || this.state.currentLocation.longitude!=0){
      this.setState({distance: this.state.distance+dist(latitude, longitude,
        this.state.currentLocation.latitude, this.state.currentLocation.longitude)});
    }
    console.log("altitude: "+ altitude);
    if (this.state.pastAltitude!==0 && altitude > this.state.pastAltitude){
      this.setState({elevation: this.state.elevation + altitude - this.state.pastAltitude})
    }
    this.setState({currentLocation:{longitude: longitude, latitude: latitude}, pastAltitude: altitude});
   },
   saveToDB(lo, la, al, time){
    fetch("http://elasticsearch-cfublog.rhcloud.com/hiking/location/", {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        activityId: 2,
        user: "vincent",
        location: lo+", "+la,
        altitude: al,
        time: time
      })
    });
   },
   onStart() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      this.timestampChanged(position.timestamp)
      var lo = position.coords.longitude, la = position.coords.latitude, al = position.coords.altitude;
      console.log("pos: "+ JSON.stringify(position.coords));
      this.onMove(lo, la, al);
      this.saveToDB(lo, la, al, position.timestamp);
      if (Math.abs(this.state.center.longitude-lo)>0.003||Math.abs(this.state.center.latitude-la)>0.003){
        this.onCenterChange({longitude: lo, latitude: la});
      }
    });
   },
  onStop() {
    navigator.geolocation.clearWatch(this.watchID);
  },
   render: function() {
     return (
       <View style={styles.container}>
         <View style={styles.statSection}>
          <View style={styles.statCell}>
           <Text style={styles.statDigit}>{this.state.distance.toFixed(2)}</Text>
           <Text style={styles.statDesc}>Distance</Text>
          </View>
          <View style={styles.statCell}>
           <Text style={styles.statDigit}>{toHHMMSS(this.state.currentTime-this.state.startTime)}</Text>
           <Text style={styles.statDesc}>Duration</Text>
          </View>
          <View style={styles.statCell}>
           <Text style={styles.statDigit}>{this.state.elevation.toFixed(0)}</Text>
           <Text style={styles.statDesc}>Elevation</Text>
          </View>
          <View style={styles.statCell}>
           <Text style={styles.statDigit}>{cal(this.state.distance, this.state.elevation).toFixed(0)}</Text>
           <Text style={styles.statDesc}>Calories</Text>
          </View>
         </View>
        <MapboxGLMap
          accessToken={'sk.eyJ1IjoiY29kZTRoayIsImEiOiJmN2JhYzhhOGMxMmM1ZTI1ZDJlOWRkNGZiYzliZTk4OSJ9.RdPsLMXx2XA0j1yJt2cPOw'}
          style={styles.map}
          styleURL={'asset://styles/mapbox-streets-v7.json'}
          centerCoordinate={this.state.center}
          zoomLevel={this.state.mapLocation.zoom}
          onRegionChange={this.onRegionChange}
          onRegionWillChange={this.onRegionChange}
          rotateEnabled={false}
          showsUserLocation={this.state.showsUserLocation}/>
          <Button onPress={this._handlePress} style={styles.text}>{this.state.button_text}</Button>
        </View>
     );
   }
 });
 var styles = StyleSheet.create({
   container: {
     flexDirection: 'column',
     flex: 1
   },
   statSection: {
    flexDirection: 'row',
    paddingTop: 30,
    padding: 20,
    flex: 1,
    justifyContent: 'center'
   },
   statCell: {
    padding: 10
   },
   statDigit: {
    fontSize: 30,
    textAlign: 'center'
   },
   statDesc: {
    textAlign: 'center'
   },
   default: {
    flex: 0.5,
    paddingLeft: 10,
    fontSize: 13,
  },
   map: {
     flex: 5,
   },
   text: {
     padding: 20
   }
 });
var dist=function(lat1, lon1, lat2, lon2) {
      var R = 6371; // km
      var dLat = toRad(lat2-lat1);
      var dLon = toRad(lon2-lon1);
      lat1 = toRad(lat1);
      lat2 = toRad(lat2);

      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      return R * c; //to miles
  }

// Converts numeric degrees to radians
var toRad = function(Value) {
    return Value * Math.PI / 180;
}

var toHHMMSS = function (millisec) {
    var sec_num = Math.floor(millisec / 1000);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time;
    if (hours === "00"){
      time = minutes+':'+seconds;
    }else{
      time = hours+':'+minutes+':'+seconds;
    }
    return time;
}

var cal = function(distance, elevation){
  return 6 * 70 * (distance / 5 + elevation/600);
}

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


<commit_before>(function (module, exports, fn) {
    if (typeof module === 'undefined') {
        module = {
            exports: {}
        };

        window.gitIndexedDB = module;
    }

    if (typeof exports === 'undefined') {
        exports = module.exports;
    }

    fn(
        module,
        exports,
        window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
    );
})(module, exports,
function (module, exports, indexedDB) {
    var version = 1;
    var hashStoreName = 'hashs';
    var hashIndexKey = 'hash';
    var pathStoreName = 'paths';
    var pathIndexKey = 'path';
    var isHash = /^[a-z0-9]{40}$/;

    var deflate, inflate;
    module.exports = function (platform) {
        deflate = platform.deflate || fake;
        inflate = platform.inflate || fake;
        return db;
    };

    var fake = function fake(input, callback) {
        setImmediate(function () {
            callback(null, input);
        });
    };

    var db = function db(prefix) {
        var context = {};
        'use strict';

        return {
            init: init.bind(context, prefix),
            get: get.bind(context),
            keys: keys.bind(context)
        };
    };

    var init = function init(prefix, callback) {
        var request = indexedDB.open(prefix, version);
        var context = this;

        request.addEventListener('upgradeneeded', function (e) {
            var db = e.target.result;

            var hashStore = db.createObjectStore(hashStoreName);
            hashStore.createIndex(hashIndexKey, hashIndexKey, {
                unique: true
            });

            var pathStore = db.createObjectStore(pathStoreName);
            pathStore.createIndex(pathIndexKey, pathIndexKey, {
                unique: true
            });
        });
        request.addEventListener('success', function (e) {
            context.db = e.target.result;
            callback();
        });
        request.addEventListener('error', function (e) {
            //Some better error handling would be nice...
            throw e;
        });
    };

    var get = function get(key, callback) {
        var context = this;
        if (!callback) {
            return get.bind(this, key);
        }
        if (isHash.test(key)) {
            var transaction = context.db.transaction(hashStoreName);
            var store = transaction.objectStore(hashStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                //pretty sure if it goes in as Uint8Array it comes out as such
                callback(null, e.target.result);
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        } else {
            var transaction = context.db.transaction(pathStoreName);
            var store = transaction.objectStore(pathStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                callback(null, e.target.result);
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        }
    };

    var keys = function keys(prefix, callback) {
        var context = this;

        var transaction = context.db.transaction(pathStoreName);
        var store = transaction.objectStore(pathStoreName);

        if (prefix) {
            var request = store.get(prefix);

            request.addEventListener('success', function (e) {
                if (e.target.result) {
                    callback(null, e.target.result.keys);
                } else {
                    callback(null, []);
                }
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        } else {
            var request = store.openCursor();
            var keys = [];
            request.addEventListener('success', function (e) {
                var cursor = e.target.result;

                if (cursor) {
                    keys.push(cursor.value);
                    cursor['continue']();
                }
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
            transaction.addEventListener('success', function (e) {
                callback(null, keys.reduce(function (arr, key) {
                    return arr.concat(key.keys);
                }, []));
            });
        }
    };
});<commit_msg>starting work in storing items<commit_after>(function (module, exports, fn) {
    if (typeof module === 'undefined') {
        module = {
            exports: {}
        };

        window.gitIndexedDB = module;
    }

    if (typeof exports === 'undefined') {
        exports = module.exports;
    }

    fn(
        module,
        exports,
        window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
    );
})(module, exports,
function (module, exports, indexedDB) {
    var version = 1;
    var hashStoreName = 'hashs';
    var hashIndexKey = 'hash';
    var pathStoreName = 'paths';
    var pathIndexKey = 'path';
    var isHash = /^[a-z0-9]{40}$/;

    var deflate, inflate;
    module.exports = function (platform) {
        deflate = platform.deflate || fake;
        inflate = platform.inflate || fake;
        return db;
    };

    var fake = function fake(input, callback) {
        setImmediate(function () {
            callback(null, input);
        });
    };

    var db = function db(prefix) {
        var context = {};
        'use strict';

        return {
            init: init.bind(context, prefix),
            get: get.bind(context),
            keys: keys.bind(context),
            set: set.bind(context)
        };
    };

    var init = function init(prefix, callback) {
        var request = indexedDB.open(prefix, version);
        var context = this;

        request.addEventListener('upgradeneeded', function (e) {
            var db = e.target.result;

            var hashStore = db.createObjectStore(hashStoreName);
            hashStore.createIndex(hashIndexKey, hashIndexKey, {
                unique: true
            });

            var pathStore = db.createObjectStore(pathStoreName);
            pathStore.createIndex(pathIndexKey, pathIndexKey, {
                unique: true
            });
        });
        request.addEventListener('success', function (e) {
            context.db = e.target.result;
            callback();
        });
        request.addEventListener('error', function (e) {
            //Some better error handling would be nice...
            throw e;
        });
    };

    var get = function get(key, callback) {
        var context = this;
        if (!callback) {
            return get.bind(this, key);
        }
        if (isHash.test(key)) {
            var transaction = context.db.transaction(hashStoreName);
            var store = transaction.objectStore(hashStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                //pretty sure if it goes in as Uint8Array it comes out as such
                callback(null, e.target.result);
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        } else {
            var transaction = context.db.transaction(pathStoreName);
            var store = transaction.objectStore(pathStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                callback(null, e.target.result);
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        }
    };

    var keys = function keys(prefix, callback) {
        var context = this;

        var transaction = context.db.transaction(pathStoreName);
        var store = transaction.objectStore(pathStoreName);

        if (prefix) {
            var request = store.get(prefix);

            request.addEventListener('success', function (e) {
                if (e.target.result) {
                    callback(null, e.target.result.keys);
                } else {
                    callback(null, []);
                }
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        } else {
            var request = store.openCursor();
            var keys = [];
            request.addEventListener('success', function (e) {
                var cursor = e.target.result;

                if (cursor) {
                    keys.push(cursor.value);
                    cursor['continue']();
                }
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
            transaction.addEventListener('success', function (e) {
                callback(null, keys.reduce(function (arr, key) {
                    return arr.concat(key.keys);
                }, []));
            });
        }
    };

    var set = function set(key, value, callback) {
        var context = this;
        if (!callback) {
            return set.bind(context, key, value);
        }

        if (isHash.test(key)) {
            return deflate(value, function (err, deflated) {
                var raw = "";
                for (var i = 0, l = deflated.length; i < l; ++i) {
                  raw += String.fromCharCode(deflated[i]);
                }

                var transaction = context.db.transaction(hashStoreName, 'readwrite');
                var store = transaction.objectStore(hashStoreName);

                var record = {
                    value: value,
                    raw: raw
                };

                record[hashIndexKey] = key;

                var request = store.put(record);

                request.addEventListener('success', function (e) {
                    callback();
                });
                request.addEventListener('error', function (e) {
                    throw e;
                });
            });
        } else {
            var transaction = context.db.transaction(pathStoreName, 'readwrite');
            var store = transaction.objectStore(pathStoreName);
            var record = {
                keys: [value]
            };
            record[pathIndexKey] = key;

            var request = store.put(record);

            request.addEventListener('success', function (e) {
                callback();
            });
            request.addEventListener('error', function (e) {
                throw e;
            });
        }
    };
});<|endoftext|>


<commit_before>/**
 * Integration test for the frost-table-cell component
 */

import {expect} from 'chai'
import {$hook} from 'ember-hook'
import wait from 'ember-test-helpers/wait'
import hbs from 'htmlbars-inline-precompile'
import {afterEach, beforeEach, describe, it} from 'mocha'
import sinon from 'sinon'

import {integration} from 'dummy/tests/helpers/ember-test-utils/setup-component-test'

const test = integration('frost-table-cell')
describe(test.label, function () {
  test.setup()

  let sandbox

  beforeEach(function () {
    sandbox = sinon.sandbox.create()
  })

  afterEach(function () {
    sandbox.restore()
  })

  it('should have real tests', function () {
    expect(true).to.equal(false)
  })

  describe('after render', function () {
    beforeEach(function () {
      this.setProperties({
        myHook: 'myThing'
      })

      this.render(hbs`
        {{frost-table-cell
          hook=myHook
        }}
      `)

      return wait()
    })

    it('should have an element', function () {
      expect(this.$()).to.have.length(1)
    })

    it('should be accessible via the hook', function () {
      expect($hook('myThing')).to.have.length(1)
    })
  })
})
<commit_msg>Skip intentionally failing test till next pr<commit_after>/**
 * Integration test for the frost-table-cell component
 */

import {expect} from 'chai'
import {$hook} from 'ember-hook'
import wait from 'ember-test-helpers/wait'
import hbs from 'htmlbars-inline-precompile'
import {afterEach, beforeEach, describe, it} from 'mocha'
import sinon from 'sinon'

import {integration} from 'dummy/tests/helpers/ember-test-utils/setup-component-test'

const test = integration('frost-table-cell')
describe(test.label, function () {
  test.setup()

  let sandbox

  beforeEach(function () {
    sandbox = sinon.sandbox.create()
  })

  afterEach(function () {
    sandbox.restore()
  })

  // FIXME: actually add real tests in next PR when frost-table-cell supports custom renderer components
  it.skip('should have real tests', function () {
    expect(true).to.equal(false)
  })

  describe('after render', function () {
    beforeEach(function () {
      this.setProperties({
        myHook: 'myThing'
      })

      this.render(hbs`
        {{frost-table-cell
          hook=myHook
        }}
      `)

      return wait()
    })

    it('should have an element', function () {
      expect(this.$()).to.have.length(1)
    })

    it('should be accessible via the hook', function () {
      expect($hook('myThing')).to.have.length(1)
    })
  })
})
<|endoftext|>


<commit_before>/**
 * Text progress.
 * @copyright 2015 Aliaksandr Astashenkau.
 * @licence MIT.
 */

// UMD definition. See https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {

	'use strict';

	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = factory();
	} else {
		// Browser globals (root is window)
		root.TextProgress = factory();
	}
}(this, function () {

	'use strict';

	// Helper utility functions
	var utils = {

		mixin: function mix() {
			var arg, prop, result = {};
			for (arg = 0; arg < arguments.length; arg++) {
				for (prop in arguments[arg]) {
					if (arguments[arg].hasOwnProperty(prop)) {
						result[prop] = arguments[arg][prop];
					}
				}
			}
			return result;
		},

		template: function(str, data) {
			return str.replace(/\${(.*?)}/g, function(a, b) {
				return typeof data[b] !== 'undefined' ? data[b] : '';
			});
		}
	};

	function TextProgress(options) {
		this.options = utils.mixin({
			max: 100
		}, options);
		this.element = this.options.element;
		this.element.classList.add('progress');
		this.progressType = this.getRenderer(options.type);
	}

	TextProgress.prototype = {

		constructor: TextProgress,

		display: function() {
			this.element.innerHTML = this.progressType.render(this.getPercent(), this.value, this.options.max);
		},

		set: function(value) {
			this.value = value;
			this.display();
		},

		increment: function(value) {
			this.set(this.value + value);
		},

		getRenderer: function(type) {
			var options = typeof type === 'object' ? type : {name: type};
			var renderer = new TextProgress.TYPES[options.name](options);
			return renderer;
		},

		getPercent: function() {
			return Math.ceil(this.value * 100 / this.options.max);
		}
	};

	TextProgress.TYPES = {

		simple: function() {
			return {
				render: function(percent) {
					return percent + '%';
				}
			};
		},

		terminal: function(options) {

			var defaults = {
				width: 20,
				charCompleted: '=',
				charRemaining: '-',
				template: '[${completed}${remaining}] ${percent}%'
			};

			return {
				options: utils.mixin(defaults, options),
				render: function(percent) {

					var completed = Math.floor(this.options.width * percent / 100),
						remaining = this.options.width - completed,
						completedStr = new Array(completed + 1).join(this.options.charCompleted),
						remainingStr = new Array(remaining + 1).join(this.options.charRemaining);

					return utils.template(this.options.template, {
						completed: completedStr,
						remaining: remainingStr,
						percent: percent
					});
				}
			};
		}
	};

	return TextProgress;
}));
<commit_msg>"changes" progress type added.<commit_after>/**
 * Text progress.
 * @copyright 2015 Aliaksandr Astashenkau.
 * @licence MIT.
 */

// UMD definition. See https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {

	'use strict';

	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = factory();
	} else {
		// Browser globals (root is window)
		root.TextProgress = factory();
	}
}(this, function () {

	'use strict';

	// Helper utility functions
	var utils = {

		mixin: function mix() {
			var arg, prop, result = {};
			for (arg = 0; arg < arguments.length; arg++) {
				for (prop in arguments[arg]) {
					if (arguments[arg].hasOwnProperty(prop)) {
						result[prop] = arguments[arg][prop];
					}
				}
			}
			return result;
		},

		template: function(str, data) {
			return str.replace(/\${(.*?)}/g, function(a, b) {
				return typeof data[b] !== 'undefined' ? data[b] : '';
			});
		}
	};

	function TextProgress(options) {
		this.options = utils.mixin({
			max: 100
		}, options);
		this.element = this.options.element;
		this.element.classList.add('progress');
		this.progressType = this.getRenderer(options.type);
	}

	TextProgress.prototype = {

		constructor: TextProgress,

		display: function() {
			this.element.innerHTML = this.progressType.render(this.getPercent(), this.value, this.options.max);
		},

		set: function(value) {
			this.value = value;
			this.display();
		},

		increment: function(value) {
			this.set(this.value + value);
		},

		getRenderer: function(type) {
			var options = typeof type === 'object' ? type : {name: type};
			var renderer = new TextProgress.TYPES[options.name](options);
			return renderer;
		},

		getPercent: function() {
			return Math.ceil(this.value * 100 / this.options.max);
		}
	};

	TextProgress.TYPES = {

		simple: function() {
			return {
				render: function(percent) {
					return percent + '%';
				}
			};
		},

		terminal: function(options) {

			var defaults = {
				width: 20,
				charCompleted: '=',
				charRemaining: '−',
				template: '[${completed}${remaining}] ${percent}%'
			};

			return {
				options: utils.mixin(defaults, options),
				render: function(percent) {

					var completed = Math.floor(this.options.width * percent / 100),
						remaining = this.options.width - completed,
						completedStr = new Array(completed + 1).join(this.options.charCompleted),
						remainingStr = new Array(remaining + 1).join(this.options.charRemaining);

					return utils.template(this.options.template, {
						completed: completedStr,
						remaining: remainingStr,
						percent: percent
					});
				}
			};
		},

		changes: function(options) {

            var defaults = {
                charInserted: '+',
                charDeleted: '−',
                template: '${total} ${inserted}${deleted}'
            };

            return {
                options: utils.mixin(defaults, options),
                render: function(percent, value, max) {

                    var insertedStr = Array(value + 1).join(this.options.charInserted),
                        deletedStr = Array(this.options.total - value + 1).join(this.options.charDeleted);

                    return utils.template(this.options.template, {
                        inserted: insertedStr,
                        deleted: deletedStr,
                        total: this.options.total
                    });
                }
            };
        }
	};

	return TextProgress;
}));
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
(function () { /* Begin of privacy scope */
    "use strict";
/*#endif*/

    gpf.interfaces = {

        /**
         * Verify that the object implements the current interface
         *
         * @param {Object} objectInstance object to inspect
         * @param {gpf.interfaces.Interface} interfaceDefinition reference
         * interface
         * @return {Boolean}
         */
        isImplementedBy: function (objectInstance, interfaceDefinition) {
            var member;
            /*
             * IMPORTANT note: we test the object itself (i.e. own members and
             * the prototype). That's why the hasOwnProperty is skipped
             */
            /*jslint forin:false*/
            for (member in interfaceDefinition.prototype) {
                if ("constructor" === member                           // Object
                    || "extend" === member) {                       // gpf.Class
                    continue;
                }
                if (typeof interfaceDefinition.prototype[member]
                    !== typeof objectInstance[member]) {
                    return false;
                }
                // TODO: check function arity
            }
            /*jslint forin:true*/
            return true;
        },

/*#ifdef(DEBUG)*/

        /**
         * Used to remove warnings about unused parameters
         */
        ignoreParameter: function (value) {
            // TODO remove at build time
            return value;
        },

/*#endif*/

        /**
         * Retrieve an object implementing the expected interface from an
         * object.
         * This is done in two passes:
         * - Either the object implements the interface, it is returned
         * - Or the object implements IUnknown, then queryInterface is used
         *
         * @param {Object} objectInstance object to inspect
         * @param {gpf.interfaces.Interface} interfaceDefinition reference
         * interface
         * @return {Object|null}
         */
        query: function (objectInstance, interfaceDefinition) {
            if (gpf.interfaces.isImplementedBy(objectInstance,
                interfaceDefinition)) {
                return objectInstance;
            } else if (gpf.interfaces.isImplementedBy(objectInstance,
                gpf.interfaces.IUnknown)) {
                return objectInstance.queryInterface(interfaceDefinition);
            } else {
                return null;
            }
        }

    };

/*#ifndef(DEBUG)*/

    if (!gpf.interfaces.ignoreParameter) {

        gpf.interfaces.ignoreParameter = function /*gpf:inline*/ () {};

    }

/*#endif*/

    /**
     * Defines an interface (relies on gpf.define)
     *
     * @param {String} name Interface name. If it contains a dot, it is
     * treated as absolute contextual. Otherwise, it is relative to
     * "gpf.interfaces"
     * @param {Function|string} [base=undefined] base Base interface
     * (or contextual name)
     * @param {Object} [definition=undefined] definition Interface definition
     * @return {Function}
     * @private
     */
    gpf._defIntrf = gpf._genDefHandler("gpf.interfaces", "Interface");

    gpf._defIntrf("Interface");

    //region IUnknown

    /**
     * Provide a way for any object to implement an interface using an
     * intermediate object (this avoids overloading the object with temporary
     * / useless members)
     */
    gpf._defIntrf("IUnknown", {

        /**
         * Retrieves an object supporting the provided interface
         * (maybe the object itself)
         *
         * @param {gpf.interfaces.Interface} interfaceDefinition The expected
         * interface
         * @return {Object|null} The object supporting the interface (or null)
         */
        queryInterface: function (interfaceDefinition) {
            gpf.interfaces.ignoreParameter(interfaceDefinition);
            return null;
        }

    });

    //endregion

    //region InterfaceImplement attribute

    /**
     * Retrieves an object supporting the provided interface
     * (maybe the object itself). This function (added to any object declaring
     * the attribute InterfaceImplementAttribute with a builder) uses the
     * InterfaceImplementAttribute attribute list to see if the one
     * corresponding to the interface provides a builder and calls it
     *
     * @param {gpf.interfaces.Interface} interfaceDefinition The expected
     * interface
     * @return {Object|null} The object supporting the interface (or null)
     */
    function _queryInterface (interfaceDefinition) {
        /*jslint -W040*/
        var
            array = (new gpf.attributes.Map(this))
                .member("Class")
                .filter(gpf.attributes.InterfaceImplementAttribute),
            idx,
            attribute;
        for (idx = 0; idx < array.length(); ++idx) {
            attribute = array.get(idx);
            if (attribute._interfaceDefinition === interfaceDefinition) {
                if (attribute._builder) {
                    return attribute._builder(this);
                }
                break;
            }
        }
        // Otherwise
        return null;
        /*jslint +W040*/
    }

    /**
     * Creates a wrapper calling _queryInterface and, if no result is built, the
     * original one defined in the object prototype.
     *
     * @param {Function} orgQueryInterface
     * @private
     * @closure
     */
    function _wrapQueryInterface (orgQueryInterface) {
        return function () {
            var result = _queryInterface.apply(this, arguments);
            if (null === result) {
                result = orgQueryInterface.apply(this, arguments);
            }
            return result;
        };
    }

    /**
     * Extend the class to provide an array-like interface
     *
     * @param {Function} interfaceDefinition Implemented interface definition
     * @param {Function} [queryInterfaceBuilder=undefined] queryInterfaceBuilder
     * Function applied if the implemented interface is requested
     *
     * @class gpf.attributes.ClassArrayInterfaceAttribute
     * @extends gpf.attributes.ClassAttribute
     * @alias gpf.$ClassIArray
     */
    gpf._defAttr("$InterfaceImplement", {

//        "[Class]": [gpf.$Alias("InterfaceImplement")],

        "[_interfaceDefinition]": [gpf.$ClassProperty(false, "which")],
        _interfaceDefinition: 0,

        "[_builder]": [gpf.$ClassProperty(false, "how")],
        _builder: null,

        constructor: function (interfaceDefinition, queryInterfaceBuilder) {
            this._interfaceDefinition = interfaceDefinition;
            if (queryInterfaceBuilder) {
                this._builder = queryInterfaceBuilder;
            }
        },

        alterPrototype: function (objPrototype) {
            if (!this._builder) {
                // Nothing to do
                return;
            }
            if (undefined !== objPrototype.queryInterface) {
                /*
                 * Two situations here:
                 * - Either the class (or one of its parent) already owns
                 *   the $InterfaceImplement attribute
                 * - Or the class (or one of its parent) implements its
                 *   own queryInterface
                 * In that last case, wrap it to use the attribute version first
                 *
                 * In both case, we take the assumption that the class already
                 * owns gpf.$InterfaceImplement(gpf.interfaces.IUnknown)
                 */
                if (_queryInterface !== objPrototype.queryInterface) {
                    objPrototype.queryInterface =
                        _wrapQueryInterface(objPrototype.queryInterface);
                }
            } else {
                objPrototype.queryInterface = _queryInterface;
                gpf.attributes.add(objPrototype.constructor, "Class",
                    [gpf.$InterfaceImplement(gpf.interfaces.IUnknown)]);
            }
        }

    });

    //endregion

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/<commit_msg>IEventTarget<commit_after>/*#ifndef(UMD)*/
(function () { /* Begin of privacy scope */
    "use strict";
/*#endif*/

    gpf.interfaces = {

        /**
         * Verify that the object implements the current interface
         *
         * @param {Object} objectInstance object to inspect
         * @param {gpf.interfaces.Interface} interfaceDefinition reference
         * interface
         * @return {Boolean}
         */
        isImplementedBy: function (objectInstance, interfaceDefinition) {
            var member;
            /*
             * IMPORTANT note: we test the object itself (i.e. own members and
             * the prototype). That's why the hasOwnProperty is skipped
             */
            /*jslint forin:false*/
            for (member in interfaceDefinition.prototype) {
                if ("constructor" === member                           // Object
                    || "extend" === member) {                       // gpf.Class
                    continue;
                }
                if (typeof interfaceDefinition.prototype[member]
                    !== typeof objectInstance[member]) {
                    return false;
                }
                // TODO: check function arity
            }
            /*jslint forin:true*/
            return true;
        },

/*#ifdef(DEBUG)*/

        /**
         * Used to remove warnings about unused parameters
         */
        ignoreParameter: function (value) {
            // TODO remove at build time
            return value;
        },

/*#endif*/

        /**
         * Retrieve an object implementing the expected interface from an
         * object.
         * This is done in two passes:
         * - Either the object implements the interface, it is returned
         * - Or the object implements IUnknown, then queryInterface is used
         *
         * @param {Object} objectInstance object to inspect
         * @param {gpf.interfaces.Interface} interfaceDefinition reference
         * interface
         * @return {Object|null}
         */
        query: function (objectInstance, interfaceDefinition) {
            if (gpf.interfaces.isImplementedBy(objectInstance,
                interfaceDefinition)) {
                return objectInstance;
            } else if (gpf.interfaces.isImplementedBy(objectInstance,
                gpf.interfaces.IUnknown)) {
                return objectInstance.queryInterface(interfaceDefinition);
            } else {
                return null;
            }
        }

    };

/*#ifndef(DEBUG)*/

    if (!gpf.interfaces.ignoreParameter) {

        gpf.interfaces.ignoreParameter = function /*gpf:inline*/ () {};

    }

/*#endif*/

    /**
     * Defines an interface (relies on gpf.define)
     *
     * @param {String} name Interface name. If it contains a dot, it is
     * treated as absolute contextual. Otherwise, it is relative to
     * "gpf.interfaces"
     * @param {Function|string} [base=undefined] base Base interface
     * (or contextual name)
     * @param {Object} [definition=undefined] definition Interface definition
     * @return {Function}
     * @private
     */
    gpf._defIntrf = gpf._genDefHandler("gpf.interfaces", "Interface");

    gpf._defIntrf("Interface");

    //region IEventTarget

    gpf._defIntrf("IEventTarget", {

        /**
         * Add an event listener to the target
         *
         * @param {String} event name
         * @param {Function|gpf.Callback} callback
         * @param {Object|Boolean} scope scope of callback or useCapture
         * parameter. NOTE: if a gpf.Callback object is used and a scope
         * specified, a new gpf.Callback object is created.
         * @param {Boolean} [useCapture=false] useCapture push it on top of the
         * triggering queue
         * @return {gpf.interfaces.IEventTarget}
         * @chainable
         */
        addEventListener: function (event, callback, scope, useCapture) {
            gpf.interfaces.ignoreParameter(event);
            gpf.interfaces.ignoreParameter(callback);
            gpf.interfaces.ignoreParameter(scope);
            gpf.interfaces.ignoreParameter(useCapture);
        },

        /**
         * Remove an event listener to the target
         *
         * @param {String} event name
         * @param {Function|gpf.Callback} callback
         * @param {Object} [scope=undefined] scope scope of callback
         * @return {gpf.interfaces.IEventTarget}
         * @chainable
         */
        removeEventListener: function (event, callback, scope) {
            gpf.interfaces.ignoreParameter(event);
            gpf.interfaces.ignoreParameter(callback);
            gpf.interfaces.ignoreParameter(scope);
        }

    });

    //endregion

    //region IUnknown

    /**
     * Provide a way for any object to implement an interface using an
     * intermediate object (this avoids overloading the object with temporary
     * / useless members)
     */
    gpf._defIntrf("IUnknown", {

        /**
         * Retrieves an object supporting the provided interface
         * (maybe the object itself)
         *
         * @param {gpf.interfaces.Interface} interfaceDefinition The expected
         * interface
         * @return {Object|null} The object supporting the interface (or null)
         */
        queryInterface: function (interfaceDefinition) {
            gpf.interfaces.ignoreParameter(interfaceDefinition);
            return null;
        }

    });

    //endregion

    //region InterfaceImplement attribute

    /**
     * Retrieves an object supporting the provided interface
     * (maybe the object itself). This function (added to any object declaring
     * the attribute InterfaceImplementAttribute with a builder) uses the
     * InterfaceImplementAttribute attribute list to see if the one
     * corresponding to the interface provides a builder and calls it
     *
     * @param {gpf.interfaces.Interface} interfaceDefinition The expected
     * interface
     * @return {Object|null} The object supporting the interface (or null)
     */
    function _queryInterface (interfaceDefinition) {
        /*jslint -W040*/
        var
            array = (new gpf.attributes.Map(this))
                .member("Class")
                .filter(gpf.attributes.InterfaceImplementAttribute),
            idx,
            attribute;
        for (idx = 0; idx < array.length(); ++idx) {
            attribute = array.get(idx);
            if (attribute._interfaceDefinition === interfaceDefinition) {
                if (attribute._builder) {
                    return attribute._builder(this);
                }
                break;
            }
        }
        // Otherwise
        return null;
        /*jslint +W040*/
    }

    /**
     * Creates a wrapper calling _queryInterface and, if no result is built, the
     * original one defined in the object prototype.
     *
     * @param {Function} orgQueryInterface
     * @private
     * @closure
     */
    function _wrapQueryInterface (orgQueryInterface) {
        return function () {
            var result = _queryInterface.apply(this, arguments);
            if (null === result) {
                result = orgQueryInterface.apply(this, arguments);
            }
            return result;
        };
    }

    /**
     * Extend the class to provide an array-like interface
     *
     * @param {Function} interfaceDefinition Implemented interface definition
     * @param {Function} [queryInterfaceBuilder=undefined] queryInterfaceBuilder
     * Function applied if the implemented interface is requested
     *
     * @class gpf.attributes.ClassArrayInterfaceAttribute
     * @extends gpf.attributes.ClassAttribute
     * @alias gpf.$ClassIArray
     */
    gpf._defAttr("$InterfaceImplement", {

//        "[Class]": [gpf.$Alias("InterfaceImplement")],

        "[_interfaceDefinition]": [gpf.$ClassProperty(false, "which")],
        _interfaceDefinition: 0,

        "[_builder]": [gpf.$ClassProperty(false, "how")],
        _builder: null,

        constructor: function (interfaceDefinition, queryInterfaceBuilder) {
            this._interfaceDefinition = interfaceDefinition;
            if (queryInterfaceBuilder) {
                this._builder = queryInterfaceBuilder;
            }
        },

        alterPrototype: function (objPrototype) {
            if (!this._builder) {
                // Nothing to do
                return;
            }
            if (undefined !== objPrototype.queryInterface) {
                /*
                 * Two situations here:
                 * - Either the class (or one of its parent) already owns
                 *   the $InterfaceImplement attribute
                 * - Or the class (or one of its parent) implements its
                 *   own queryInterface
                 * In that last case, wrap it to use the attribute version first
                 *
                 * In both case, we take the assumption that the class already
                 * owns gpf.$InterfaceImplement(gpf.interfaces.IUnknown)
                 */
                if (_queryInterface !== objPrototype.queryInterface) {
                    objPrototype.queryInterface =
                        _wrapQueryInterface(objPrototype.queryInterface);
                }
            } else {
                objPrototype.queryInterface = _queryInterface;
                gpf.attributes.add(objPrototype.constructor, "Class",
                    [gpf.$InterfaceImplement(gpf.interfaces.IUnknown)]);
            }
        }

    });

    //endregion

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/<|endoftext|>


<commit_before>require('./translate');
var tokens = require("./tokens.js");

var fs = require("fs");
var webdriverio = require("webdriverio");
var selenium = require('selenium-standalone');
var client = ""; // WebdriverIO client

var IS_VERBOSE = false;
var varStack = [];
const ERROR_NUM_ARGS = "Error: Number of arguments was invalid.";
const ERROR_FILEIO = "Error: Could not open the file specified. Does it exist, and do we have read access to it?";
const ERROR_SYNTAX = "Error: Syntax error on line ";
const INFO_USAGE = "Usage: node interpret.js [-v | --verbose] <path-to-task>";
/*
 * Interprets a CSL task and translates to WebdriverIO.
 */
function main() {
    var data = readArgs(process.argv);
    if (!data)
        return; // Abandon ship!
    parse(data);
}

function readArgs(args) {
    // Usage: interpret.js [-v] <task>

    // Check number of args
    if (!args || args.length < 3 || args.length > 4) {
        console.error(ERROR_NUM_ARGS);
        console.error(INFO_USAGE);
        return;
    }

    // Check for verbose flag
    var flag = args.indexOf(tokens.VERBOSE_ARG_LONG);
    if (flag == -1)
        flag = args.indexOf(tokens.VERBOSE_ARG);
    if (flag != -1) {
        args.splice(flag, 1);
        if (args.length < 3) {
            console.error(ERROR_NUM_ARGS);
            console.error(INFO_USAGE);
            return;
        }

        IS_VERBOSE = true;
    }

    // Check if we can open file specified
    var data = "";
    try {
            data = fs.readFileSync(args[2], {encoding: "utf8"});
    } catch (err) {
        console.error(ERROR_FILEIO);
        return;
    }

    // If all goes well...
    return data;
}

/*
 * Parses file data as CSL and interprets as WebdriverIO code.
 */
function parse(data) {
    var lines = data.split('\n');
    var timeout = 30000; // ms
    var output = [];

    for (var i = 0; i < lines.length; i++) {
        // Process line-by-line
        var line = lines[i].trim().split(' ');
        var cmd = line[0];
        var args = line.slice(1);
        if (cmd === "!timeout") {
                timeout = timescale(args);
                if (IS_VERBOSE) console.log(`[VERBOSE: LINE ${i}] Set timeout to ${args.join(' ')}.`);
                continue;
        } else if (cmd === "#") {
                continue;
        } else if (line.length <= 1) {
                continue;
        }

        try {
            processLine(cmd, args);
            sleep(5); // TODO: terrible
        } catch (err) {
            console.error(`[ERROR: LINE ${i}] Syntax error on: ${lines[i]}`);
            return;
        }
    }
}

// Converts all timescales to milliseconds
function timescale(args) {
    return parseInt(args[0]) * tokens.TIMESCALES[args[1]];
}

// Translates a single line, given a command and an argument array.
function processLine(cmd, args) {
    switch (cmd) {
        case "goto":
            if (IS_VERBOSE) console.log(`[VERBOSE] Navigating to ${args[0]}.`);
            return `.url(${args[0]})`;
        case "set":
            if (IS_VERBOSE) console.log(`[VERBOSE] Setting value.`);
            var value = 0;

            // Check how we should interpret value
            if (tokens.JQUERY_TAG.test(args[2])) {
                if (IS_VERBOSE) console.log(`[VERBOSE] Getting value as jQuery.`);
                value = jqueryEvalOrValue(args[2]);
            }
            else {
                if (IS_VERBOSE) console.log(`[VERBOSE] Getting value as string.`);
                value = args.slice(2).join(" ");
            }
            // Check what we should set
            if (JQUERY_TAG.test(args[0])) {
                if (IS_VERBOSE) console.log(`[VERBOSE] Setting variable as jQuery.`);
                return `.setValue(
                        processJquery(${args[0]}),
                        ${value}
                )`;
            }
            else {
                if (IS_VERBOSE) console.log(`[VERBOSE] Setting local variable.`);
                var obj = {}; obj[args[0]] = value;
                varStack.push(obj);
            }
            break;
        case "click":
            if (IS_VERBOSE) console.log(`[VERBOSE] Clicking on ${args[0]}.`);
            return `.click(${processJquery(args[0])})`;
            break;
        case "wait":
            if (args[0] === "for") {
                if (IS_VERBOSE) console.log(`[VERBOSE] Waiting for ${args[1]}.`);
                return `.waitForExist(
                        ${processJquery(args[1])},
                        ${timeout}
                )`;
            } else {
                // Process as timestamp
                if (IS_VERBOSE) console.log(`[VERBOSE] Waiting for timeslice.`);
                return `.pause(${timescale(args)})`;
            }
            break;
        case "return":
            return varStack[args[0]];
            break;
        default:
            throw new Error();
    }
}

// Processes a jQuery argument.
function processJquery(arg) {
    return `'${tokens.JQUERY_TAG.exec(arg)[0]
        .replace(/"/g, '\\"')}'`;
}

// Determines whether to evaluate the argument as jQuery
// or to just return the value of the jQuery selector.
function jqueryEvalOrValue(arg) {
    var retval = 0;
    if (tokens.JQUERY_TAG_EOT.test(arg)) {
        client = client
            .getValue(processJquery(arg))
            .then((result, retval) => { retval = result; });
    } else {
        arg = arg.replace("jquery[", "$('").replace("]", ")")
        client = client
            .execute((arg) => { return eval(arg); })
            .then((result, retval) => { retval = result; });
    }

    return retval;
}

function seleniumPrep() {
        selenium.install(() => {
                selenium.start(() => {
                        client = webdriverio.remote();
                        client.init().then(() => main());
                });
        });
}

// Terrible debug
function sleep(seconds)
{
    var e = new Date().getTime() + (seconds * 1000);
    while (new Date().getTime() <= e) {}
}

if (require.main === module) {
    seleniumPrep();
}
<commit_msg>Set val rework<commit_after>require('./translate');
var tokens = require("./tokens.js");

var fs = require("fs");
var webdriverio = require("webdriverio");
var selenium = require('selenium-standalone');
var client = ""; // WebdriverIO client

var IS_VERBOSE = false;
var varStack = [];
const ERROR_NUM_ARGS = "Error: Number of arguments was invalid.";
const ERROR_FILEIO = "Error: Could not open the file specified. Does it exist, and do we have read access to it?";
const ERROR_SYNTAX = "Error: Syntax error on line ";
const INFO_USAGE = "Usage: node interpret.js [-v | --verbose] <path-to-task>";
/*
 * Interprets a CSL task and translates to WebdriverIO.
 */
function main() {
    var data = readArgs(process.argv);
    if (!data)
        return; // Abandon ship!
    parse(data);
}

function readArgs(args) {
    // Usage: interpret.js [-v] <task>

    // Check number of args
    if (!args || args.length < 3 || args.length > 4) {
        console.error(ERROR_NUM_ARGS);
        console.error(INFO_USAGE);
        return;
    }

    // Check for verbose flag
    var flag = args.indexOf(tokens.VERBOSE_ARG_LONG);
    if (flag == -1)
        flag = args.indexOf(tokens.VERBOSE_ARG);
    if (flag != -1) {
        args.splice(flag, 1);
        if (args.length < 3) {
            console.error(ERROR_NUM_ARGS);
            console.error(INFO_USAGE);
            return;
        }

        IS_VERBOSE = true;
    }

    // Check if we can open file specified
    var data = "";
    try {
            data = fs.readFileSync(args[2], {encoding: "utf8"});
    } catch (err) {
        console.error(ERROR_FILEIO);
        return;
    }

    // If all goes well...
    return data;
}

/*
 * Parses file data as CSL and interprets as WebdriverIO code.
 */
function parse(data) {
    var lines = data.split('\n');
    var timeout = 30000; // ms
    var output = [];

    for (var i = 0; i < lines.length; i++) {
        // Process line-by-line
        var line = lines[i].trim().split(' ');
        var cmd = line[0];
        var args = line.slice(1);
        if (cmd === "!timeout") {
                timeout = timescale(args);
                if (IS_VERBOSE) console.log(`[VERBOSE: LINE ${i}] Set timeout to ${args.join(' ')}.`);
                continue;
        } else if (cmd === "#") {
                continue;
        } else if (line.length <= 1) {
                continue;
        }

        try {
            processLine(cmd, args);
            sleep(5); // TODO: terrible
        } catch (err) {
            console.error(`[ERROR: LINE ${i}] Syntax error on: ${lines[i]}`);
            return;
        }
    }
}

// Converts all timescales to milliseconds
function timescale(args) {
    return parseInt(args[0]) * tokens.TIMESCALES[args[1]];
}

// Translates a single line, given a command and an argument array.
function processLine(cmd, args) {
    switch (cmd) {
        case "goto":
            if (IS_VERBOSE) console.log(`[VERBOSE] Navigating to ${args[0]}.`);
            return `.url(${args[0]})`;
        case "set":
            if (IS_VERBOSE) console.log(`[VERBOSE] Setting value.`);
            var value = "";

            // Check how we should interpret value
            if (tokens.JQUERY_TAG.test(args[2])) {
                if (IS_VERBOSE) console.log(`[VERBOSE] Getting value as jQuery.`);
                value = jqueryEvalOrValue(args[2]);
            }
            else {
                if (IS_VERBOSE) console.log(`[VERBOSE] Getting value as string.`);
                value = args.slice(2).join(" ");
            }
            // Check what we should set
            if (JQUERY_TAG.test(args[0])) {
                if (IS_VERBOSE) console.log(`[VERBOSE] Setting variable as jQuery.`);
                return `.setValue(
                        processJquery(${args[0]}),
                        ${value}
                )`;
            }
            else {
                if (IS_VERBOSE) console.log(`[VERBOSE] Setting local variable.`);
                var obj = {}; obj[args[0]] = value;
                varStack.push(obj);
            }
            break;
        case "click":
            if (IS_VERBOSE) console.log(`[VERBOSE] Clicking on ${args[0]}.`);
            return `.click(${processJquery(args[0])})`;
            break;
        case "wait":
            if (args[0] === "for") {
                if (IS_VERBOSE) console.log(`[VERBOSE] Waiting for ${args[1]}.`);
                return `.waitForExist(
                        ${processJquery(args[1])},
                        ${timeout}
                )`;
            } else {
                // Process as timestamp
                if (IS_VERBOSE) console.log(`[VERBOSE] Waiting for timeslice.`);
                return `.pause(${timescale(args)})`;
            }
            break;
        case "return":
            return varStack[args[0]];
            break;
        default:
            throw new Error();
    }
}

// Processes a jQuery argument.
function processJquery(arg) {
    return `'${tokens.JQUERY_TAG.exec(arg)[0]
        .replace(/"/g, '\\"')}'`;
}

// Determines whether to evaluate the argument as jQuery
// or to just return the value of the jQuery selector.
function jqueryEvalOrValue(arg) {
    var retval = 0;
    if (tokens.JQUERY_TAG_EOT.test(arg)) {
        return `.getValue(${processJquery(arg})
                .then((retval) => window.retval = retval;)`;
    }

    arg = arg.replace("jquery[", "$('").replace("]", ")")
    return `.execute((arg) => {
        var script = document.createElement('script');script.src = "
        https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
        document.getElementsByTagName('head')[0].appendChild(script);

        window.retval = ${arg};
    })`;
}

function seleniumPrep() {
        selenium.install(() => {
                selenium.start(() => {
                        client = webdriverio.remote();
                        client.init().then(() => main());
                });
        });
}

// Terrible debug
function sleep(seconds)
{
    var e = new Date().getTime() + (seconds * 1000);
    while (new Date().getTime() <= e) {}
}

if (require.main === module) {
    seleniumPrep();
}
<|endoftext|>


<commit_before>define(function(){

	'use strict';

	var listeners = {
		'prevent_default': function(event){
			event.preventDefault();
		},
		'get_url': function(element){
			var url = element.getAttribute('href')''
			return url;
		},
		''
	};

});<commit_msg>Repo updated on: Sun Dec 20 2015 18:02:53<commit_after>define(function(){

	'use strict';

	var listeners = {
		'prevent_default': function(event){
			event.preventDefault();
		},
		'get_url': function(element){
			var url = element.getAttribute('href');
			return url;
		},
		''
	};
});<|endoftext|>


<commit_before>angular.module('ionic.services.core', [])

/**
 * A core Ionic account identity provider.
 *
 * Usage:
 * angular.module('myApp', ['ionic', 'ionic.services.common'])
 * .config(['$ionicAppProvider', function($ionicAccountProvider) {
 *   $ionicAppProvider.identify({
 *     app_id: 'x34dfxjydi23dx'
 *   });
 * }]);
 */
.provider('$ionicApp', function() {
  var app = {};

  var settings = {
    'api_server': 'http://ionic.io'
  };

  this.identify = function(opts) {
    app = opts;
  };

  /**
   * Set a config property.
   */
  this.set = function(k, v) {
    settings[k] = v;
  };

  this.$get = [function() {
    return {
      getValue: function(k) {
        return settings[k];
      },
      getApiUrl: function() {
        return this.getValue('api_server');
      },

      getApiEndpoint: function(service) {
        var app = this.getApp();
        if(!app) return null;

        return this.getApiUrl() + '/api/v1/' + app.app_id + '/' + service;
      },

      /**
       * Get the registered app for all commands.
       */
      getApp: function() {
        return app;
      }
    }
  }];
});

// Backwards compat
angular.module('ionic.services.common', ['ionic.services.core']);
<commit_msg>Set API Server explicitly<commit_after>angular.module('ionic.services.core', [])

/**
 * A core Ionic account identity provider.
 *
 * Usage:
 * angular.module('myApp', ['ionic', 'ionic.services.common'])
 * .config(['$ionicAppProvider', function($ionicAccountProvider) {
 *   $ionicAppProvider.identify({
 *     app_id: 'x34dfxjydi23dx'
 *   });
 * }]);
 */
.provider('$ionicApp', function() {
  var app = {};

  var settings = {
    'api_server': 'http://ionic.io'
  };

  this.identify = function(opts) {
    app = opts;
  };

  /**
   * Set a config property.
   */
  this.set = function(k, v) {
    settings[k] = v;
  };

  this.setApiServer = function(server) {
    settings.api_server = server;
  };

  this.$get = [function() {
    return {
      getValue: function(k) {
        return settings[k];
      },
      getApiUrl: function() {
        return this.getValue('api_server');
      },

      getApiEndpoint: function(service) {
        var app = this.getApp();
        if(!app) return null;

        return this.getApiUrl() + '/api/v1/' + app.app_id + '/' + service;
      },

      /**
       * Get the registered app for all commands.
       */
      getApp: function() {
        return app;
      }
    }
  }];
});

// Backwards compat
angular.module('ionic.services.common', ['ionic.services.core']);
<|endoftext|>


<commit_before><commit_msg>Tweens docs<commit_after>Glow.provide(function(glow) {
	/**
	@name glow.tweens
	@namespace
	@description Functions for modifying animations
	@see What are tweens?

	*/

	/**
	@name glow.tweens.linear
	@function
	@description Returns linear tween.

	Will transition values from start to finish with no
	acceleration or deceleration.

	@returns {Function}
	*/
	tweens.linear = function() {};

	/**
	@name glow.tweens.easeIn
	@function
	@description Creates a tween which starts off slowly and accelerates.

	@param {Number} [strength=2] How strong the easing is.

	A higher number means the animation starts off slowly and
	ends more quickly.

	@returns {Function}
	*/
	tweens.easeIn = function() {};

	/**
	@name glow.tweens.easeOut
	@function
	@description Creates a tween which starts off fast and decelerates.

	@param {Number} [strength=2] How strong the easing is.

	A higher number means the animation starts quickly and
	ends more slowly.

	@returns {Function}
	*/
	tweens.easeOut = function() {};

	/**
	@name glow.tweens.easeBoth
	@function
	@description Creates a tween which starts off slowly, accelerates then decelerates after the half way point.

	This produces a smooth and natural looking transition.

	@param {Number} [strength=2] How strong the easing is.

	A higher number produces a greater difference between
	start / end speed and the mid speed.

	@returns {Function}
	*/
	tweens.easeBoth = function() {};

	/**
	@name glow.tweens.overshootIn
	@function
	@description Returns the reverse of {@link glow.tweens.overshootOut overshootOut}

	@param {Number} [amount=1.70158] How much to overshoot.

	The default is 1.70158 which results in a 10% overshoot.

	@returns {Function}
	*/
	tweens.overshootIn = function() {};

	/**
	@name glow.tweens.overshootOut
	@function
	@description Creates a tween which overshoots its end point then returns to its end point.

	@param {Number} [amount=1.70158] How much to overshoot.

	The default is 1.70158 which results in a 10% overshoot.

	@returns {Function}
	*/
	tweens.overshootOut = function() {};

	/**
	@name glow.tweens.overshootBoth
	@function
	@description Returns a combination of {@link glow.tweens.overshootIn overshootIn} and {@link glow.tweens.overshootOut overshootOut}

	@param {Number} [amount=1.70158] How much to overshoot.

	The default is 1.70158 which results in a 10% overshoot.

	@returns {Function}
	*/
	tweens.overshootBoth = function() {};

	/**
	@name glow.tweens.bounceIn
	@function
	@description Returns the reverse of {@link glow.tweens.bounceOut bounceOut}

	@returns {Function}
	*/
	tweens.bounceIn = function() {};

	/**
	@name glow.tweens.bounceOut
	@function
	@description Returns a tween which bounces against the final value 3 times before stopping

	@returns {Function}
	*/
	tweens.bounceOut = function() {};

	/**
	@name glow.tweens.bounceBoth
	@function
	@description Returns a combination of {@link glow.tweens.bounceIn bounceIn} and {@link glow.tweens.bounceOut bounceOut}

	@returns {Function}
	*/
	tweens.bounceBoth = function() {};

	/**
	@name glow.tweens.elasticIn
	@function
	@description Returns the reverse of {@link glow.tweens.elasticOut elasticOut}

	@param {Number} [amplitude=1] How strong the elasticity is.

	@param {Number} [period=0.3] The frequency period.

	@returns {Function}
	*/
	tweens.elasticIn = function() {};

	/**
	@name glow.tweens.elasticOut
	@function
	@description Creates a tween which has an elastic movement.

	You can tweak the tween using the parameters but you'll
	probably find the defaults sufficient.

	@param {Number} [amplitude=1] How strong the elasticity is.

	@param {Number} [period=0.3] The frequency period.

	@returns {Function}
	*/
	tweens.elasticOut = function() {};

	/**
	@name glow.tweens.elasticBoth
	@function
	@description Returns a combination of {@link glow.tweens.elasticIn elasticIn} and {@link glow.tweens.elasticOut elasticOut}

	@param {Number} [amplitude=1] How strong the elasticity is.

	@param {Number} [period=0.3] The frequency period.

	@returns {Function}
	*/
	tweens.elasticBoth = function() {};

	/**
	@name glow.tweens.combine
	@function
	@description Create a tween from two tweens.

	This can be useful to make custom tweens which, for example,
	start with an easeIn and end with an overshootOut. To keep
	the motion natural, you should configure your tweens so the
	first ends and the same velocity that the second starts.

	@param {Function} tweenIn Tween to use for the first half

	@param {Function} tweenOut Tween to use for the second half

	@example
	// 4.5 has been chosen for the easeIn strength so it
	// ends at the same velocity as overshootOut starts.
	var myTween = glow.tweens.combine(
	glow.tweens.easeIn(4.5),
	glow.tweens.overshootOut()
	);

	@returns {Function}
	*/
	tweens.combine = function() {};

});

<|endoftext|>


<commit_before>/* global Y */
'use strict'

function extend (Y) {
  class twicConnector extends Y.AbstractConnector {
    constructor (y, options) {
      if (options === undefined) {
        throw new Error('Options must not be undefined!')
      }
      if (options.room == null) {
        throw new Error('You must define a room name!')
      }
      if( options.socket == null ){
          throw new Error('You have to set a websocket object')
      }
      if( options.user_id == null ){
          throw new Error('You have to define user id')
      }

      options.role = 'slave'
      super(y, options)

      var socket = this._twicSocket;
      var self = this

      self.setUserId(options.user_id);

      socket.emit( 'yjs_joinroom', {room:options.room, id:options.user_id} );

      socket.on('yjs_'+options.room+'_newpeer',function( peer ){
          self.userJoined(peer.id, 'master')
      });

      socket.on('yjs_'+options.room+'_message', function( message ){
          self.receiveMessage( message.peer, message.payload );
      });

      socket.on('yjs_'+options.room+'_oldpeer',function( peer ){
          self.userLeft(peer.id)
      });

      /*swr.once('connectionReady', function (userId) {
        // SimpleWebRTC (swr) is initialized
        swr.joinRoom(self.webrtcOptions.room)

        swr.once('joinedRoom', function () {
          self.setUserId(userId)

          swr.on('channelMessage', function (peer, room_, message) {
            // The client received a message
            // Check if the connector is already initialized,
            // only then forward the message to the connector class
            if (message.type != null) {
              self.receiveMessage(peer.id, message.payload)
            }
          })
        })

        swr.on('createdPeer', function (peer) {
          // a new peer/client joined the session.
          // Notify the connector class, if the connector
          // is already initialized
          self.userJoined(peer.id, 'master')
        })

        swr.on('peerStreamRemoved', function (peer) {
          // a client left the session.
          // Notify the connector class, if the connector
          // is already initialized
          self.userLeft(peer.id)
        })
    })*/
    }
    disconnect () {
      //this.swr.leaveRoom()
      this.options.socket.emit('yjs_leaveroom', this.options.room);
      super.disconnect()
    }
    reconnect () {
      //this.swr.joinRoom(this.webrtcOptions.room)
      this.options.socket.emit( 'yjs_joinroom', {room:this.options.room, id:this.options.user_id} );
      super.reconnect()
    }
    send (uid, message) {
      this.options.socket.emit('yjs_message',{room:this.options.room,peer: uid, message: message});
      /*
      // we have to make sure that the message is sent under all circumstances
      var send = function () {
        // check if the clients still exists
        var peer = self.swr.webrtc.getPeers(uid)[0]
        var success
        if (peer) {
          // success is true, if the message is successfully sent
          success = peer.sendDirectly('simplewebrtc', 'yjs', message)
        }
        if (!success) {
          // resend the message if it didn't work
          setTimeout(send, 500)
        }
      }
      // try to send the message
      send()*/
    }
    broadcast (message) {
        this.options.socket.emit('yjs_message',{room:this.options.room, message: message});
      //this.swr.sendDirectlyToAll('simplewebrtc', 'yjs', message)
    }
    isDisconnected () {
      return false
    }
  }
  Y.extend('twic', twicConnector)
}

module.exports = extend
if (typeof Y !== 'undefined') {
  extend(Y)
}
<commit_msg>joinRoom params<commit_after>/* global Y */
'use strict'

function extend (Y) {
  class twicConnector extends Y.AbstractConnector {
    constructor (y, options) {
      if (options === undefined) {
        throw new Error('Options must not be undefined!')
      }
      if (options.room == null) {
        throw new Error('You must define a room name!')
      }
      if( options.socket == null ){
          throw new Error('You have to set a websocket object')
      }
      if( options.user_id == null ){
          throw new Error('You have to define user id')
      }

      options.role = 'slave'
      super(y, options)

      var socket = this._twicSocket;
      var self = this

      self.setUserId(options.user_id);

      socket.emit( 'yjs_joinroom', {room:options.room, id:options.user_id} );

      socket.on('yjs_'+options.room+'_newpeer',function( peer ){
          self.userJoined(peer.id, 'master')
      });

      socket.on('yjs_'+options.room+'_message', function( message ){
          self.receiveMessage( message.peer, message.payload );
      });

      socket.on('yjs_'+options.room+'_oldpeer',function( peer ){
          self.userLeft(peer.id)
      });

      /*swr.once('connectionReady', function (userId) {
        // SimpleWebRTC (swr) is initialized
        swr.joinRoom(self.webrtcOptions.room)

        swr.once('joinedRoom', function () {
          self.setUserId(userId)

          swr.on('channelMessage', function (peer, room_, message) {
            // The client received a message
            // Check if the connector is already initialized,
            // only then forward the message to the connector class
            if (message.type != null) {
              self.receiveMessage(peer.id, message.payload)
            }
          })
        })

        swr.on('createdPeer', function (peer) {
          // a new peer/client joined the session.
          // Notify the connector class, if the connector
          // is already initialized
          self.userJoined(peer.id, 'master')
        })

        swr.on('peerStreamRemoved', function (peer) {
          // a client left the session.
          // Notify the connector class, if the connector
          // is already initialized
          self.userLeft(peer.id)
        })
    })*/
    }
    disconnect () {
      //this.swr.leaveRoom()
      this.options.socket.emit('yjs_leaveroom',{room:this.options.room, id:this.options.user_id});
      super.disconnect()
    }
    reconnect () {
      //this.swr.joinRoom(this.webrtcOptions.room)
      this.options.socket.emit( 'yjs_joinroom', {room:this.options.room, id:this.options.user_id} );
      super.reconnect()
    }
    send (uid, message) {
      this.options.socket.emit('yjs_message',{room:this.options.room,peer: uid, message: message});
      /*
      // we have to make sure that the message is sent under all circumstances
      var send = function () {
        // check if the clients still exists
        var peer = self.swr.webrtc.getPeers(uid)[0]
        var success
        if (peer) {
          // success is true, if the message is successfully sent
          success = peer.sendDirectly('simplewebrtc', 'yjs', message)
        }
        if (!success) {
          // resend the message if it didn't work
          setTimeout(send, 500)
        }
      }
      // try to send the message
      send()*/
    }
    broadcast (message) {
        this.options.socket.emit('yjs_message',{room:this.options.room, message: message});
      //this.swr.sendDirectlyToAll('simplewebrtc', 'yjs', message)
    }
    isDisconnected () {
      return false
    }
  }
  Y.extend('twic', twicConnector)
}

module.exports = extend
if (typeof Y !== 'undefined') {
  extend(Y)
}
<|endoftext|>


<commit_before>import { escapeStringForRegex, makeRegexOrPattern } from '../utils';

export default function keyword(symbol, name) {
  let pattern;
  if (symbol instanceof RegExp) pattern = symbol;

  if (typeof symbol === 'string') {
    pattern = new RegExp(`(^|\\s)(${escapeStringForRegex(symbol)})(\\s|$)`, 'gi');
  }

  if (symbol instanceof Array) {
    pattern = new RegExp(`(^|\\s)(${makeRegexOrPattern(symbol)})(\\s|$)`, 'gi');
  }

  if (!pattern) {
    console.error('Cannot create a keyword token without a string or regex. Cannot use:', typeof symbol);
    return false;
  }
  return {
    pattern,
    onMatch: function onMatch(match) {
      let start = match.index;
      return {
        name,
        type: 'KEYWORD',
        chars: match[2],
        index: start,
        handle: 'at',
      };
    }
  };
}
<commit_msg>fixed bug in token string index<commit_after>import { escapeStringForRegex, makeRegexOrPattern } from '../utils';

export default function keyword(symbol, name) {
  let pattern;
  if (symbol instanceof RegExp) pattern = symbol;

  if (typeof symbol === 'string') {
    pattern = new RegExp(`(^|\\s)(${escapeStringForRegex(symbol)})(\\s|$)`, 'gi');
  }

  if (symbol instanceof Array) {
    pattern = new RegExp(`(^|\\s)(${makeRegexOrPattern(symbol)})(\\s|$)`, 'gi');
  }

  if (!pattern) {
    console.error('Cannot create a keyword token without a string or regex. Cannot use:', typeof symbol);
    return false;
  }
  return {
    pattern,
    onMatch: function onMatch(match) {
      let start = match.index + match[1].length;
      return {
        name,
        type: 'KEYWORD',
        chars: match[2],
        index: start,
        handle: 'at',
      };
    }
  };
}
<|endoftext|>


<commit_before>/**
 * Created by huangxinghui on 2015/6/29.
 */

var $ = require('jquery');
var _ = require('underscore');
var log = require('./log');
var $document = require('../document');
var Bean = require('../core');

var lastCookies = {};
var lastCookieString = '';
var $base = $document.find('base');

var defaults = this.defaults = {};

function calcOptions(options) {
  return options ? _.extend({}, defaults, options) : defaults;
}

function baseHref() {
  var href = $base.attr('href');
  return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
}

function cookieReader() {
  var document = $document[0],
      currentCookieString = document.cookie,
      cookieArray, cookie, i, index, name;

  if (currentCookieString !== lastCookieString) {
    lastCookieString = currentCookieString;
    cookieArray = lastCookieString.split('; ');
    lastCookies = {};

    for (i = 0; i < cookieArray.length; i++) {
      cookie = cookieArray[i];
      index = cookie.indexOf('=');
      if (index > 0) { //ignore nameless cookies
        name = decodeURIComponent(cookie.substring(0, index));
        // the first value that is seen for a cookie is the most
        // specific one.  values for the same cookie name that
        // follow are for less specific paths.
        if (lastCookies[name] === undefined) {
          lastCookies[name] = decodeURIComponent(cookie.substring(index + 1));
        }
      }
    }
  }
  return lastCookies;
}

function cookieWriter() {
  var cookiePath = baseHref(),
      rawDocument = $document[0];

  function buildCookieString(name, value, options) {
    var path, expires;
    options = options || {};
    expires = options.expires;

    path = _.isUndefined(options.path) ? cookiePath : options.path;
    if (value === undefined) {
      expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
      value = '';
    }
    if (_.isString(expires)) {
      expires = new Date(expires);
    }

    var str = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    str += path ? ';path=' + path : '';
    str += options.domain ? ';domain=' + options.domain : '';
    str += expires ? ';expires=' + expires.toUTCString() : '';
    str += options.secure ? ';secure' : '';

    // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
    // - 300 cookies
    // - 20 cookies per unique domain
    // - 4096 bytes per cookie
    var cookieLength = str.length + 1;
    if (cookieLength > 4096) {
      log.warn("Cookie '" + name +
          "' possibly not set or overflowed because it was too large (" +
          cookieLength + " > 4096 bytes)!");
    }

    return str;
  }

  return function(name, value, options) {
    rawDocument.cookie = buildCookieString(name, value, options);
  };
}

module.exports = Bean.Cookie = {
  get: function(key) {
    return cookieReader()[key];
  },

  getObject: function(key) {
    var value = this.get(key);
    return value ? JSON.parse(value) : value;
  },

  put: function(key, value, options) {
    cookieWriter()(key, value, calcOptions(options));
  },

  putObject: function(key, value, options) {
    this.put(key, JSON.stringify(value), options);
  },

  remove: function(key, options) {
    this.put(key, undefined, options);
  }
};<commit_msg>change cookie logger import<commit_after>/**
 * Created by huangxinghui on 2015/6/29.
 */

var $ = require('jquery');
var _ = require('underscore');
var logger = require('./logger');
var $document = require('../document');
var Bean = require('../core');

var lastCookies = {};
var lastCookieString = '';
var $base = $document.find('base');
var defaults = this.defaults = {};

function calcOptions(options) {
  return options ? _.extend({}, defaults, options) : defaults;
}

function baseHref() {
  var href = $base.attr('href');
  return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
}

function cookieReader() {
  var document = $document[0],
      currentCookieString = document.cookie,
      cookieArray, cookie, i, index, name;

  if (currentCookieString !== lastCookieString) {
    lastCookieString = currentCookieString;
    cookieArray = lastCookieString.split('; ');
    lastCookies = {};

    for (i = 0; i < cookieArray.length; i++) {
      cookie = cookieArray[i];
      index = cookie.indexOf('=');
      if (index > 0) { //ignore nameless cookies
        name = decodeURIComponent(cookie.substring(0, index));
        // the first value that is seen for a cookie is the most
        // specific one.  values for the same cookie name that
        // follow are for less specific paths.
        if (lastCookies[name] === undefined) {
          lastCookies[name] = decodeURIComponent(cookie.substring(index + 1));
        }
      }
    }
  }
  return lastCookies;
}

function cookieWriter() {
  var cookiePath = baseHref(),
      rawDocument = $document[0];

  function buildCookieString(name, value, options) {
    var path, expires;
    options = options || {};
    expires = options.expires;

    path = _.isUndefined(options.path) ? cookiePath : options.path;
    if (value === undefined) {
      expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
      value = '';
    }
    if (_.isString(expires)) {
      expires = new Date(expires);
    }

    var str = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    str += path ? ';path=' + path : '';
    str += options.domain ? ';domain=' + options.domain : '';
    str += expires ? ';expires=' + expires.toUTCString() : '';
    str += options.secure ? ';secure' : '';

    // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
    // - 300 cookies
    // - 20 cookies per unique domain
    // - 4096 bytes per cookie
    var cookieLength = str.length + 1;
    if (cookieLength > 4096) {
      logger.warn("Cookie '" + name +
          "' possibly not set or overflowed because it was too large (" +
          cookieLength + " > 4096 bytes)!");
    }

    return str;
  }

  return function(name, value, options) {
    rawDocument.cookie = buildCookieString(name, value, options);
  };
}

module.exports = Bean.Cookie = {
  get: function(key) {
    return cookieReader()[key];
  },

  getObject: function(key) {
    var value = this.get(key);
    return value ? JSON.parse(value) : value;
  },

  put: function(key, value, options) {
    cookieWriter()(key, value, calcOptions(options));
  },

  putObject: function(key, value, options) {
    this.put(key, JSON.stringify(value), options);
  },

  remove: function(key, options) {
    this.put(key, undefined, options);
  }
};<|endoftext|>