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

var React = require('react-native');
var module = require('RCTRealtimeCloudStorageAndroid');
var RCTRealtimeCloudStorage = new module();

RCTRealtimeCloudStorage.storageRef('2Ze1dz', 'token');
var tabref = RCTRealtimeCloudStorage.table("todoTable");
var messages = [];

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

var RCTRealtimeStorageAndroid = React.createClass({

  getInitialState: function() {
    return {
      listName: "storage-demo",
      isLoading: false,
      active: 0,
      completed: 0,
      all: 1,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  },

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

  receiveData: function(receivedData){
    if (receivedData) {
      RCTRealtimeCloudStorage.RTLog("REALTIME", "on receivedData"+ (typeof (receivedData.timestamp)));
        messages[receivedData.timestamp] = receivedData;
      }else{
        RCTRealtimeCloudStorage.RTLog("REALTIME", "end receivedData");
        this.setState({
          dataSource: this.getDataSource(messages),
          isLoading: false
        });
      }
  },

  updateView: function(receivedData){
    messages[receivedData.timestamp] = receivedData;

    this.setState({
      dataSource: this.getDataSource([])
    });

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

  removeData: function(removeData){
    delete messages[removeData.timestamp];

    this.setState({
      dataSource: this.getDataSource([])
    });

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

  componentDidMount: function(){

    tabref.on("StorageEvent_UPDATE", this.updateView);

    tabref.on("StorageEvent_DELETE", this.removeData);

    tabref.equalsString("listName", this.state.listName);

    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );
  },

  onSearchChange: function(val){
    messages = [];
    this.setState({
      listName: val.nativeEvent.text,
    });

    tabref.equalsString("listName", val.nativeEvent.text);

    tabref.getItems(
      this.receiveData,
        function(data){
          console.log('error:' + JSON.stringify(data))
        }
      );
  },

  _renderRow: function(rowData: Object, sectionID: number, rowID: number) {
    JSON.stringify(rowData);
    return (
      <TodoItem
        update={() => this.updateSate(rowData)}
        item={rowData}
        remove={() => this.deleteItem(rowData)}
      />
    );
  },

 newTodo: function(val){
    var timestamp = Math.floor(new Date()/1000);

    tabref.push({"listName": this.state.listName, "timestamp": timestamp, "task": val.nativeEvent.text, "state": 0}, function(success){

    }, function(error){
      console.log('not updated');
    });
  },

  updateSate: function(todo:Object){
    todo.state = (todo.state == 1) ? 0 : 1;
    tabref.push(todo, function(success){

    }, function(error){
      console.log('not updated');
    });
  },

  deleteItem: function(todo:Object){
    var itemR = tabref.itemCustom(todo.listName, todo.timestamp);
    itemR.del(function(){

    },
    function(){
      console.log("itemref error");
    });
  },

  resetTableRef: function(){
    tabref.off("StorageEvent_UPDATE");
    tabref.off("StorageEvent_DELETE");
    tabref = RCTRealtimeCloudStorage.table("todoTable");
    tabref.on("StorageEvent_UPDATE", this.updateView);
    tabref.on("StorageEvent_DELETE", this.removeData);

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

  filterAll: function(){
    this.setState(
      {
        isLoading: true,
        active: 0,
        completed: 0,
        all: 1
      });

    this.resetTableRef();
    tabref.equalsString("listName", this.state.listName);
    RCTRealtimeCloudStorage.RTLog("REALTIME","GET ALL");
    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );
  },

  filterActive: function(){
    this.setState(
      {
        isLoading: true,
        active: 1,
        completed: 0,
        all: 0
      });

    this.resetTableRef();
    tabref.equalsString("listName", this.state.listName);
    tabref.equalsNumber("state", 0);
    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );

  },

  filterCompleted: function(){
    this.setState(
      {
        isLoading: true,
        active: 0,
        completed: 1,
        all: 0
      });

    this.resetTableRef();
    tabref.equalsString("listName", this.state.listName);
    tabref.equalsNumber("state", 1);
    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );

  },

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

        <View style={styles.shadow}>
          <View style={styles.topBar}>
          </View>

          <View style={styles.sBar}>
            <SearchBar
              onSearchChange={this.onSearchChange}
              placeholder="storage-demo"
              isLoading={this.state.isLoading}
              onFocus={() => this.refs.listview.getScrollResponder().scrollTo(0, 0)}
            />

            <SearchBar
              onEndEditing={this.newTodo}
              placeholder="What needs to be done?"
              isLoading={this.state.isLoading}
              onFocus={() => this.refs.listview.getScrollResponder().scrollTo(0, 0)}
            />
          </View>

          <ListView
            ref="listview"
            style={styles.list}
            dataSource={this.state.dataSource}
            renderRow={this._renderRow}
          />
          <View style={styles.line1}>
          </View>
          <View style={styles.line2}>
          </View>

          </View>
          <View style={[styles.middle, styles.shadow]}>
          </View>
          <View style={[styles.bottomView, styles.shadow]}>
            <CButton action={this.filterAll} text='All' selected={this.state.all} />
            <CButton action={this.filterActive} text='Active' selected={this.state.active}  />
            <CButton action={this.filterCompleted} text='Completed' selected={this.state.completed} />
          </View>
      </View>
    );
  }
});

var CButton = React.createClass({
  render: function() {
    if (this.props.selected){
    return (
      <View style={styles.searchBar}>
        <TouchableHighlight style={styles.bottomBt} onPress={this.props.action}>
          <Text style={styles.bottomBtSelected}>
            {this.props.text}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }else{
    return (
      <View style={styles.searchBar}>
        <TouchableHighlight style={styles.bottomBt} onPress={this.props.action}>
          <Text style={styles.bottomBtNot}>
            {this.props.text}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
  }
});

var SearchBar = React.createClass({
  render: function() {
    return (
      <View style={styles.searchBar}>
        <TextInput
          autoCapitalize="none"
          autoCorrect={false}
          onEndEditing={this.props.onEndEditing}
          onChange={this.props.onSearchChange}
          placeholder={this.props.placeholder}
          onFocus={this.props.onFocus}
          style={styles.searchBarInput}
        />
      </View>
    );
  }
});

var TodoItem = React.createClass({
  render: function() {
    var icon = (this.props.item.state == 1) ? require('image!check') : require('image!notcheck');
    return (
      <View>
          <View style={styles.row}>
            <TouchableHighlight onPress={this.props.update}>
                <Image source={icon} style={styles.icon}/>
            </TouchableHighlight>

            <View style={styles.textContainer}>
              <Text style={styles.movieTitle} numberOfLines={4}>
                {this.props.item.task}
              </Text>
            </View>

            <TouchableHighlight onPress={this.props.remove}>
                <Image source={require('image!x')} style={styles.icon} />
            </TouchableHighlight>
          </View>
        <View style={styles.cellBorder} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:20,
    backgroundColor: '#F2F2F2',
    padding: 10,

  },
  line1:{
    position:'absolute',
    left: 33,
    top: 0,
    bottom: 0,
    backgroundColor: 'red',
    width: 1,
    opacity: 0.2,
  },
  line2:{
    position:'absolute',
    left: 36,
    top: 0,
    bottom: 0,
    backgroundColor: 'red',
    width: 1,
    opacity: 0.2,
  },
  topBar:{
    backgroundColor: '#B89470',
    height: 10,
  },
  sBar:{
    marginLeft: 40,
  },
  list:{
    flex: 1,
    backgroundColor: 'white',
  },
  middle:{
    marginLeft:5,
    marginRight: 5,
    borderTopWidth: 0,
    height: 5,
    borderColor:'black',
  },
  bottomView:{
    flexDirection: 'row',
    justifyContent:'center',
    marginLeft:15,
    marginRight: 15,
    borderTopWidth: 0,
  },
  bottomBt:{
    padding: 5,
    marginLeft:10,
    marginRight: 10,
  },
  bottomBtSelected:{
    color: '#33CCFF',
  },
  bottomBtNot:{
    color: '#83756f',
  },
  shadow:{
    shadowColor: 'black',
    shadowOffset: {height:5, width:3},
    shadowOpacity: 1,
  },
  centerText: {
    alignItems: 'center',
  },
  noMoviesText: {
    marginTop: 80,
    color: '#888888',
  },
  searchBar: {
    marginTop: 0,
    padding: 3,
    paddingLeft: 8,
    flexDirection: 'row',
    alignItems: 'center',
  },
  remove:{
    color: '#a88a8a',
  },
  icon: {
    width: 20,
    height: 20,
  },
  searchBarInput: {
    fontSize: 15,
    flex: 1,
    height: 30,
  },
  separator: {
    height: 1,
    backgroundColor: '#eeeeee',
  },
  spinner: {
    width: 30,
  },
  scrollSpinner: {
    marginVertical: 20,
  },
  textContainer: {
    marginLeft:10,
    flex: 1,
  },
  movieTitle: {
    flex: 1,
    fontSize: 14,
    fontWeight: '300',
    marginBottom: 2,
  },
  movieYear: {
    color: '#999999',
    fontSize: 12,
  },
  row: {
    alignItems: 'center',
    backgroundColor: 'white',
    flexDirection: 'row',
    padding: 10,
  },
  resizeMode: {
    justifyContent: 'flex-start',
    flexDirection: 'column',
    width: 85,
    height: 80,
    marginRight: 5,
    borderColor: 'rgba(0, 0, 0, 0.1)',
    borderWidth: 1,
  },
  cellBorder: {
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    // Trick to get the thinest line the device can display
    height: 1,
  },
});

AppRegistry.registerComponent('RCTRealtimeStorageAndroid', () => RCTRealtimeStorageAndroid);
<commit_msg>Fix on Android images path<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var module = require('RCTRealtimeCloudStorageAndroid');
var RCTRealtimeCloudStorage = new module();

RCTRealtimeCloudStorage.storageRef('2Ze1dz', 'token');
var tabref = RCTRealtimeCloudStorage.table("todoTable");
var messages = [];

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

var RCTRealtimeStorageAndroid = React.createClass({

  getInitialState: function() {
    return {
      listName: "storage-demo",
      isLoading: false,
      active: 0,
      completed: 0,
      all: 1,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  },

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

  receiveData: function(receivedData){
    if (receivedData) {
      RCTRealtimeCloudStorage.RTLog("REALTIME", "on receivedData"+ (typeof (receivedData.timestamp)));
        messages[receivedData.timestamp] = receivedData;
      }else{
        RCTRealtimeCloudStorage.RTLog("REALTIME", "end receivedData");
        this.setState({
          dataSource: this.getDataSource(messages),
          isLoading: false
        });
      }
  },

  updateView: function(receivedData){
    messages[receivedData.timestamp] = receivedData;

    this.setState({
      dataSource: this.getDataSource([])
    });

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

  removeData: function(removeData){
    delete messages[removeData.timestamp];

    this.setState({
      dataSource: this.getDataSource([])
    });

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

  componentDidMount: function(){

    tabref.on("StorageEvent_UPDATE", this.updateView);

    tabref.on("StorageEvent_DELETE", this.removeData);

    tabref.equalsString("listName", this.state.listName);

    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );
  },

  onSearchChange: function(val){
    messages = [];
    this.setState({
      listName: val.nativeEvent.text,
    });

    tabref.equalsString("listName", val.nativeEvent.text);

    tabref.getItems(
      this.receiveData,
        function(data){
          console.log('error:' + JSON.stringify(data))
        }
      );
  },

  _renderRow: function(rowData: Object, sectionID: number, rowID: number) {
    JSON.stringify(rowData);
    return (
      <TodoItem
        update={() => this.updateSate(rowData)}
        item={rowData}
        remove={() => this.deleteItem(rowData)}
      />
    );
  },

 newTodo: function(val){
    var timestamp = Math.floor(new Date()/1000);

    tabref.push({"listName": this.state.listName, "timestamp": timestamp, "task": val.nativeEvent.text, "state": 0}, function(success){

    }, function(error){
      console.log('not updated');
    });
  },

  updateSate: function(todo:Object){
    todo.state = (todo.state == 1) ? 0 : 1;
    tabref.push(todo, function(success){

    }, function(error){
      console.log('not updated');
    });
  },

  deleteItem: function(todo:Object){
    var itemR = tabref.itemCustom(todo.listName, todo.timestamp);
    itemR.del(function(){

    },
    function(){
      console.log("itemref error");
    });
  },

  resetTableRef: function(){
    tabref.off("StorageEvent_UPDATE");
    tabref.off("StorageEvent_DELETE");
    tabref = RCTRealtimeCloudStorage.table("todoTable");
    tabref.on("StorageEvent_UPDATE", this.updateView);
    tabref.on("StorageEvent_DELETE", this.removeData);

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

  filterAll: function(){
    this.setState(
      {
        isLoading: true,
        active: 0,
        completed: 0,
        all: 1
      });

    this.resetTableRef();
    tabref.equalsString("listName", this.state.listName);
    RCTRealtimeCloudStorage.RTLog("REALTIME","GET ALL");
    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );
  },

  filterActive: function(){
    this.setState(
      {
        isLoading: true,
        active: 1,
        completed: 0,
        all: 0
      });

    this.resetTableRef();
    tabref.equalsString("listName", this.state.listName);
    tabref.equalsNumber("state", 0);
    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );

  },

  filterCompleted: function(){
    this.setState(
      {
        isLoading: true,
        active: 0,
        completed: 1,
        all: 0
      });

    this.resetTableRef();
    tabref.equalsString("listName", this.state.listName);
    tabref.equalsNumber("state", 1);
    tabref.getItems(this.receiveData,
                   function(data){
                   console.log('error:' + JSON.stringify(data))
                   }
    );

  },

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

        <View style={styles.shadow}>
          <View style={styles.topBar}>
          </View>

          <View style={styles.sBar}>
            <SearchBar
              onSearchChange={this.onSearchChange}
              placeholder="storage-demo"
              isLoading={this.state.isLoading}
              onFocus={() => this.refs.listview.getScrollResponder().scrollTo(0, 0)}
            />

            <SearchBar
              onEndEditing={this.newTodo}
              placeholder="What needs to be done?"
              isLoading={this.state.isLoading}
              onFocus={() => this.refs.listview.getScrollResponder().scrollTo(0, 0)}
            />
          </View>

          <ListView
            ref="listview"
            style={styles.list}
            dataSource={this.state.dataSource}
            renderRow={this._renderRow}
          />
          <View style={styles.line1}>
          </View>
          <View style={styles.line2}>
          </View>

          </View>
          <View style={[styles.middle, styles.shadow]}>
          </View>
          <View style={[styles.bottomView, styles.shadow]}>
            <CButton action={this.filterAll} text='All' selected={this.state.all} />
            <CButton action={this.filterActive} text='Active' selected={this.state.active}  />
            <CButton action={this.filterCompleted} text='Completed' selected={this.state.completed} />
          </View>
      </View>
    );
  }
});

var CButton = React.createClass({
  render: function() {
    if (this.props.selected){
    return (
      <View style={styles.searchBar}>
        <TouchableHighlight style={styles.bottomBt} onPress={this.props.action}>
          <Text style={styles.bottomBtSelected}>
            {this.props.text}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }else{
    return (
      <View style={styles.searchBar}>
        <TouchableHighlight style={styles.bottomBt} onPress={this.props.action}>
          <Text style={styles.bottomBtNot}>
            {this.props.text}
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
  }
});

var SearchBar = React.createClass({
  render: function() {
    return (
      <View style={styles.searchBar}>
        <TextInput
          autoCapitalize="none"
          autoCorrect={false}
          onEndEditing={this.props.onEndEditing}
          onChange={this.props.onSearchChange}
          placeholder={this.props.placeholder}
          onFocus={this.props.onFocus}
          style={styles.searchBarInput}
        />
      </View>
    );
  }
});

var TodoItem = React.createClass({
  render: function() {
    var icon = (this.props.item.state == 1) ? { uri: 'check' } : { uri: 'notcheck' };
    return (
      <View>
          <View style={styles.row}>
            <TouchableHighlight onPress={this.props.update}>
                <Image source={icon} style={styles.icon}/>
            </TouchableHighlight>

            <View style={styles.textContainer}>
              <Text style={styles.movieTitle} numberOfLines={4}>
                {this.props.item.task}
              </Text>
            </View>

            <TouchableHighlight onPress={this.props.remove}>
                <Image source={{ uri: 'x' }} style={styles.icon} />
            </TouchableHighlight>
          </View>
        <View style={styles.cellBorder} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:20,
    backgroundColor: '#F2F2F2',
    padding: 10,

  },
  line1:{
    position:'absolute',
    left: 33,
    top: 0,
    bottom: 0,
    backgroundColor: 'red',
    width: 1,
    opacity: 0.2,
  },
  line2:{
    position:'absolute',
    left: 36,
    top: 0,
    bottom: 0,
    backgroundColor: 'red',
    width: 1,
    opacity: 0.2,
  },
  topBar:{
    backgroundColor: '#B89470',
    height: 10,
  },
  sBar:{
    marginLeft: 40,
  },
  list:{
    flex: 1,
    backgroundColor: 'white',
  },
  middle:{
    marginLeft:5,
    marginRight: 5,
    borderTopWidth: 0,
    height: 5,
    borderColor:'black',
  },
  bottomView:{
    flexDirection: 'row',
    justifyContent:'center',
    marginLeft:15,
    marginRight: 15,
    borderTopWidth: 0,
  },
  bottomBt:{
    padding: 5,
    marginLeft:10,
    marginRight: 10,
  },
  bottomBtSelected:{
    color: '#33CCFF',
  },
  bottomBtNot:{
    color: '#83756f',
  },
  shadow:{
    shadowColor: 'black',
    shadowOffset: {height:5, width:3},
    shadowOpacity: 1,
  },
  centerText: {
    alignItems: 'center',
  },
  noMoviesText: {
    marginTop: 80,
    color: '#888888',
  },
  searchBar: {
    marginTop: 0,
    padding: 3,
    paddingLeft: 8,
    flexDirection: 'row',
    alignItems: 'center',
  },
  remove:{
    color: '#a88a8a',
  },
  icon: {
    width: 20,
    height: 20,
  },
  searchBarInput: {
    fontSize: 15,
    flex: 1,
    height: 30,
  },
  separator: {
    height: 1,
    backgroundColor: '#eeeeee',
  },
  spinner: {
    width: 30,
  },
  scrollSpinner: {
    marginVertical: 20,
  },
  textContainer: {
    marginLeft:10,
    flex: 1,
  },
  movieTitle: {
    flex: 1,
    fontSize: 14,
    fontWeight: '300',
    marginBottom: 2,
  },
  movieYear: {
    color: '#999999',
    fontSize: 12,
  },
  row: {
    alignItems: 'center',
    backgroundColor: 'white',
    flexDirection: 'row',
    padding: 10,
  },
  resizeMode: {
    justifyContent: 'flex-start',
    flexDirection: 'column',
    width: 85,
    height: 80,
    marginRight: 5,
    borderColor: 'rgba(0, 0, 0, 0.1)',
    borderWidth: 1,
  },
  cellBorder: {
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    // Trick to get the thinest line the device can display
    height: 1,
  },
});

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


<commit_before>'use strict'

var React = require('react-native');
var { NativeModules, requireNativeComponent } = React;

var MapMixins = {
  setDirectionAnimated(mapRef, heading) {
    NativeModules.MapboxGLManager.setDirectionAnimated(React.findNodeHandle(this.refs[mapRef]), heading);
  },
  setZoomLevelAnimated(mapRef, zoomLevel) {
    NativeModules.MapboxGLManager.setZoomLevelAnimated(React.findNodeHandle(this.refs[mapRef]), zoomLevel);
  },
  setCenterCoordinateAnimated(mapRef, latitude, longitude) {
    NativeModules.MapboxGLManager.setCenterCoordinateAnimated(React.findNodeHandle(this.refs[mapRef]), latitude, longitude);
  },
  setCenterCoordinateZoomLevelAnimated(mapRef, latitude, longitude, zoomLevel) {
    NativeModules.MapboxGLManager.setCenterCoordinateZoomLevelAnimated(React.findNodeHandle(this.refs[mapRef]), latitude, longitude, zoomLevel);
  },
  addAnnotations(mapRef, annotations) {
    NativeModules.MapboxGLManager.addAnnotations(React.findNodeHandle(this.refs[mapRef]), annotations);
  },
  selectAnnotationAnimated(mapRef, selectedIdentifier) {
    NativeModules.MapboxGLManager.selectAnnotationAnimated(React.findNodeHandle(this.refs[mapRef]), selectedIdentifier);
  },
  removeAnnotation(mapRef, selectedIdentifier) {
    NativeModules.MapboxGLManager.removeAnnotation(React.findNodeHandle(this.refs[mapRef]), selectedIdentifier);
  },
  removeAllAnnotations(mapRef) {
    NativeModules.MapboxGLManager.removeAllAnnotations(React.findNodeHandle(this.refs[mapRef]));
  },
  setVisibleCoordinateBoundsAnimated(mapRef, latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft) {
    NativeModules.MapboxGLManager.setVisibleCoordinateBoundsAnimated(React.findNodeHandle(this.refs[mapRef]), latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft);
  },
  setUserTrackingMode(mapRef, userTrackingMode) {
    NativeModules.MapboxGLManager.setUserTrackingMode(React.findNodeHandle(this.refs[mapRef]), userTrackingMode);
  },
  setTilt(mapRef, tilt) {
    NativeModules.MapboxGLManager.setTilt(React.findNodeHandle(this.refs[mapRef]), tilt);
  },
  getCenterCoordinateZoomLevel(mapRef, callback) {
    NativeModules.MapboxGLManager.getCenterCoordinateZoomLevel(React.findNodeHandle(this.refs[mapRef]), callback);
  },
  getDirection(mapRef, callback) {;
    NativeModules.MapboxGLManager.getDirection(React.findNodeHandle(this.refs[mapRef]), function(err){
      console.log(err);
    });
  },
  mapStyles: NativeModules.MapboxGLManager.mapStyles,
  userTrackingMode: NativeModules.MapboxGLManager.userTrackingMode
};

var ReactMapView = requireNativeComponent('RCTMapbox', {
    name: 'RCTMapbox',
    propTypes: {
      accessToken: React.PropTypes.string.isRequired,
      attributionButtonIsHidden: React.PropTypes.bool,
      logoIsHidden: React.PropTypes.bool,
      annotations: React.PropTypes.arrayOf(React.PropTypes.shape({
        title: React.PropTypes.string,
        subtitle: React.PropTypes.string,
        coordinates: React.PropTypes.array.isRequired,
        alpha: React.PropTypes.number,
        fillColor: React.PropTypes.string,
        strokeColor: React.PropTypes.string,
        strokeWidth: React.PropTypes.number
      })),
      centerCoordinate: React.PropTypes.shape({
        latitude: React.PropTypes.number.isRequired,
        longitude: React.PropTypes.number.isRequired
      }),
      centerCoordinateZoom: React.PropTypes.shape(),
      debugActive: React.PropTypes.bool,
      direction: React.PropTypes.number,
      rotateEnabled: React.PropTypes.bool,
      scrollEnabled: React.PropTypes.bool,
      showsUserLocation: React.PropTypes.bool,
      styleUrl: React.PropTypes.string,
      userTrackingMode: React.PropTypes.number,
      zoomEnabled: React.PropTypes.bool,
      zoomLevel: React.PropTypes.number,
      tilt: React.PropTypes.number,
      compassIsHidden: React.PropTypes.bool,
      onRegionChange: React.PropTypes.func,
      onUserLocationChange: React.PropTypes.func,
      // Fix for https://github.com/mapbox/react-native-mapbox-gl/issues/118
      scaleY: React.PropTypes.number,
      scaleX: React.PropTypes.number,
      translateY: React.PropTypes.number,
      translateX: React.PropTypes.number,
      rotation: React.PropTypes.number,
      // Fix for https://github.com/mapbox/react-native-mapbox-gl/issues/175
      renderToHardwareTextureAndroid: React.PropTypes.bool,
      onLayout: React.PropTypes.bool,
      accessibilityLiveRegion: React.PropTypes.string,
      accessibilityComponentType: React.PropTypes.string,
      accessibilityLabel: React.PropTypes.string,
      testID: React.PropTypes.string,
      importantForAccessibility: React.PropTypes.string
    },
    defaultProps() {
      return {
        centerCoordinate: {
          latitude: 0,
          longitude: 0
        },
        debugActive: false,
        direction: 0,
        rotateEnabled: true,
        scrollEnabled: true,
        showsUserLocation: false,
        styleUrl: NativeModules.MapboxGLManager.mapStyles.streets,
        userTrackingMode: NativeModules.MapboxGLManager.userTrackingMode.none,
        zoomEnabled: true,
        zoomLevel: 0,
        tilt: 0,
        compassIsHidden: false
      };
    }
});

var ReactMapViewWrapper = React.createClass({
  statics: {
    Mixin: MapMixins
  },
  propTypes: {
    onRegionChange: React.PropTypes.func,
    onUserLocationChange: React.PropTypes.func
  },
  handleOnChange(event) {
    if (this.props.onRegionChange) this.props.onRegionChange(event.nativeEvent.src);
  },
  handleUserLocation(event) {
    if (this.props.onUserLocationChange) this.props.onUserLocationChange(event.nativeEvent.src);
  },
  render() {
    return (
      <ReactMapView
        {...this.props}
        onChange={this.handleOnChange}
        onSelect={this.handleUserLocation} />
    );
  }
});

module.exports = ReactMapViewWrapper;
<commit_msg>Return the callback<commit_after>'use strict'

var React = require('react-native');
var { NativeModules, requireNativeComponent } = React;

var MapMixins = {
  setDirectionAnimated(mapRef, heading) {
    NativeModules.MapboxGLManager.setDirectionAnimated(React.findNodeHandle(this.refs[mapRef]), heading);
  },
  setZoomLevelAnimated(mapRef, zoomLevel) {
    NativeModules.MapboxGLManager.setZoomLevelAnimated(React.findNodeHandle(this.refs[mapRef]), zoomLevel);
  },
  setCenterCoordinateAnimated(mapRef, latitude, longitude) {
    NativeModules.MapboxGLManager.setCenterCoordinateAnimated(React.findNodeHandle(this.refs[mapRef]), latitude, longitude);
  },
  setCenterCoordinateZoomLevelAnimated(mapRef, latitude, longitude, zoomLevel) {
    NativeModules.MapboxGLManager.setCenterCoordinateZoomLevelAnimated(React.findNodeHandle(this.refs[mapRef]), latitude, longitude, zoomLevel);
  },
  addAnnotations(mapRef, annotations) {
    NativeModules.MapboxGLManager.addAnnotations(React.findNodeHandle(this.refs[mapRef]), annotations);
  },
  selectAnnotationAnimated(mapRef, selectedIdentifier) {
    NativeModules.MapboxGLManager.selectAnnotationAnimated(React.findNodeHandle(this.refs[mapRef]), selectedIdentifier);
  },
  removeAnnotation(mapRef, selectedIdentifier) {
    NativeModules.MapboxGLManager.removeAnnotation(React.findNodeHandle(this.refs[mapRef]), selectedIdentifier);
  },
  removeAllAnnotations(mapRef) {
    NativeModules.MapboxGLManager.removeAllAnnotations(React.findNodeHandle(this.refs[mapRef]));
  },
  setVisibleCoordinateBoundsAnimated(mapRef, latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft) {
    NativeModules.MapboxGLManager.setVisibleCoordinateBoundsAnimated(React.findNodeHandle(this.refs[mapRef]), latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft);
  },
  setUserTrackingMode(mapRef, userTrackingMode) {
    NativeModules.MapboxGLManager.setUserTrackingMode(React.findNodeHandle(this.refs[mapRef]), userTrackingMode);
  },
  setTilt(mapRef, tilt) {
    NativeModules.MapboxGLManager.setTilt(React.findNodeHandle(this.refs[mapRef]), tilt);
  },
  getCenterCoordinateZoomLevel(mapRef, callback) {
    NativeModules.MapboxGLManager.getCenterCoordinateZoomLevel(React.findNodeHandle(this.refs[mapRef]), callback);
  },
  getDirection(mapRef, callback) {;
    NativeModules.MapboxGLManager.getDirection(React.findNodeHandle(this.refs[mapRef]), callback);
  },
  mapStyles: NativeModules.MapboxGLManager.mapStyles,
  userTrackingMode: NativeModules.MapboxGLManager.userTrackingMode
};

var ReactMapView = requireNativeComponent('RCTMapbox', {
    name: 'RCTMapbox',
    propTypes: {
      accessToken: React.PropTypes.string.isRequired,
      attributionButtonIsHidden: React.PropTypes.bool,
      logoIsHidden: React.PropTypes.bool,
      annotations: React.PropTypes.arrayOf(React.PropTypes.shape({
        title: React.PropTypes.string,
        subtitle: React.PropTypes.string,
        coordinates: React.PropTypes.array.isRequired,
        alpha: React.PropTypes.number,
        fillColor: React.PropTypes.string,
        strokeColor: React.PropTypes.string,
        strokeWidth: React.PropTypes.number
      })),
      centerCoordinate: React.PropTypes.shape({
        latitude: React.PropTypes.number.isRequired,
        longitude: React.PropTypes.number.isRequired
      }),
      centerCoordinateZoom: React.PropTypes.shape(),
      debugActive: React.PropTypes.bool,
      direction: React.PropTypes.number,
      rotateEnabled: React.PropTypes.bool,
      scrollEnabled: React.PropTypes.bool,
      showsUserLocation: React.PropTypes.bool,
      styleUrl: React.PropTypes.string,
      userTrackingMode: React.PropTypes.number,
      zoomEnabled: React.PropTypes.bool,
      zoomLevel: React.PropTypes.number,
      tilt: React.PropTypes.number,
      compassIsHidden: React.PropTypes.bool,
      onRegionChange: React.PropTypes.func,
      onUserLocationChange: React.PropTypes.func,
      // Fix for https://github.com/mapbox/react-native-mapbox-gl/issues/118
      scaleY: React.PropTypes.number,
      scaleX: React.PropTypes.number,
      translateY: React.PropTypes.number,
      translateX: React.PropTypes.number,
      rotation: React.PropTypes.number,
      // Fix for https://github.com/mapbox/react-native-mapbox-gl/issues/175
      renderToHardwareTextureAndroid: React.PropTypes.bool,
      onLayout: React.PropTypes.bool,
      accessibilityLiveRegion: React.PropTypes.string,
      accessibilityComponentType: React.PropTypes.string,
      accessibilityLabel: React.PropTypes.string,
      testID: React.PropTypes.string,
      importantForAccessibility: React.PropTypes.string
    },
    defaultProps() {
      return {
        centerCoordinate: {
          latitude: 0,
          longitude: 0
        },
        debugActive: false,
        direction: 0,
        rotateEnabled: true,
        scrollEnabled: true,
        showsUserLocation: false,
        styleUrl: NativeModules.MapboxGLManager.mapStyles.streets,
        userTrackingMode: NativeModules.MapboxGLManager.userTrackingMode.none,
        zoomEnabled: true,
        zoomLevel: 0,
        tilt: 0,
        compassIsHidden: false
      };
    }
});

var ReactMapViewWrapper = React.createClass({
  statics: {
    Mixin: MapMixins
  },
  propTypes: {
    onRegionChange: React.PropTypes.func,
    onUserLocationChange: React.PropTypes.func
  },
  handleOnChange(event) {
    if (this.props.onRegionChange) this.props.onRegionChange(event.nativeEvent.src);
  },
  handleUserLocation(event) {
    if (this.props.onUserLocationChange) this.props.onUserLocationChange(event.nativeEvent.src);
  },
  render() {
    return (
      <ReactMapView
        {...this.props}
        onChange={this.handleOnChange}
        onSelect={this.handleUserLocation} />
    );
  }
});

module.exports = ReactMapViewWrapper;
<|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 HNReactNative = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
});

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

AppRegistry.registerComponent('HNReactNative', () => HNReactNative);
<commit_msg>Pulls data from HN's API and displays them in a ListView. Very basic.<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

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

var apiurl = "https://hacker-news.firebaseio.com/v0/";

var HNReactNative = React.createClass({
  getInitialState: function() {
    return {
      topStories: [],
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  },

  componentDidMount: function() {
    var stories = {};

    fetch(apiurl + "topstories.json")
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          topStories: responseData.slice(0,30),
          loaded: true,
        });
      }).then(() => {
        this.state.topStories.forEach((item) => {
          this.fetchStory(item).then((storyJson) => {
            stories[storyJson.id] = storyJson;
          }).then(() => {
            this.setState({
              dataSource: this.state.dataSource.cloneWithRows(stories),
            });
          }).done();
        });
      }).done();
  },

  fetchStory: function(story) {
    return fetch(apiurl + "item/" + story + ".json")
      .then((response) => response.json())
  },

  render: function() {
    if (!this.state.loaded) {
      return this.renderLoad();
    } else {
      return (
        <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderStory}
            style={styles.listView}
          />
      );
    }
  },

  renderLoad: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Loading...
        </Text>
      </View>
    );
  },

  renderStory: function(story) {
    return (
      <View style={styles.container}>
        <Text>
          {story.id}
        </Text>
        <Text>
          {story.title}
        </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,
  },
  listView: {
    paddingTop: 25,
    backgroundColor: "#F5FCFF",
  }
});

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


<commit_before>
var async = require('async');
var asyncReplace = require( 'async-replace');
var fs = require('fs')
var p = require('path')
var EventEmitterCollector = require("eventemittercollector");
var EventEmitter = require('events').EventEmitter;
var mmm = require('mmmagic');

var files, info, fileStat, fileWithPath;

var eventEC = new EventEmitterCollector;
var Magic = mmm.Magic;
var magic = new Magic( mmm.MAGIC_MIME_TYPE );
var yaml = require('js-yaml');

var tags = {};

/* TODO:
  * [X] Write function that goes through every file
  * [X] Allow plugin functions to process, sequentially, a file
  * [X] Write function that will process a file looking for special tags
  * [X] Implement some basic tags
  * [X] Add event when file is processed
  * [X] Add event when _all_ files are processed

  * [X] Use mmmagic to find out file type, add it to file data

  * [X] Switch to YAML for info
  * [X] Load front matter using YAML, same syntax as Jekyll

  * [X] Do not apply any filtering to files starting with _. Maybe completely ignore such files

  * [ ] Layout templates
      [ ] Add filter that will apply a template and change file name and ext
      [ ] Add original contents, name and ext to data structure
          https://github.com/chjj/marked

  * [ ] Add afterFilter hook to copy files over respecting new info

  * [ ] Create plugins file structure, include code ones, allow non-core ones
  * [ ] Add way to prioritise plugins

  * [ ] Add additional common plugins

Plugins are:

* init()
  They activate listening to events etc.

Events:
* filterBeforePlugins
* filterAfterPlugins
* filterDone

*/

/*
registerTag( 'testTag', function( tagParams, fileContents, fileInfo, cb ){
  cb( null, "TAG RUN! Params were: " + tagParams.join('-') );
});

registerTag( 'include', function( tagParams, fileContents, fileInfo, cb ){
  fs.readFile( p.join( fileInfo.path, tagParams[ 1 ] ), function( err, included ){
    if( err ) return cb( err );

    cb( null, included );
  });
});
*/

function pluginResolver( fileContents, fileInfo, cb ){
  resolveTags( fileContents, fileInfo, cb );
}

// callback( tagParams, fileContents, fileInfo, done )
function registerTag( tagName, callback ){

  // Check that the tag is not already defined
  if( typeof tags[ tagName ] !== 'undefined' ){
    callback( new Error("Tag already defined: " + tagName ) );
  }

  // Assign the tag
  tags[ tagName ] = callback;
}

function resolveTags( fileContents, fileInfo, cb ){

  asyncReplace( fileContents, /\[\[(.*?)\]\]/g,
    function( match, p1, offset, string, done  ){

       // Found a tag marker: apply the registered tag
       var tagParams = p1.split( ' ' );
       var tag = tagParams[ 0 ];

       // Tag is not defined: return whatever was there in the first place
       if( typeof tags[ tag ] === 'undefined' ) return done( null, match );

       // Run the function associated to that tag
       tags[ tag ]( tagParams, fileContents, fileInfo, done );

    },
    function( err, result ){
      cb( null, result, fileInfo );
    }
  );

}

eventEC.onCollect( 'afterFilters', function( cb ){

  var f = function( fileContents, fileInfo, cb ){
    cb( null );
  }

  cb( null, f );

});

// Read header, save data in it
eventEC.onCollect( 'filterBeforePlugins', function( cb ){

  var p1 = function( fileContents, fileInfo, cb ){

    // This filter will only work on text files (of any kind)
    if( fileInfo.mimetype.split('/')[0] !== 'text') return cb( null, fileContents, fileInfo);

    // Wrapping both replace() and yaml.safeLoad in try/catch so that
    // if anything goes wrong the callback gets called correctly
    try {
      fileContents = fileContents.replace(/^---\n([\s\S]*)\n---\n/m, function( match, p1, offset, string) {

        frontMatter = yaml.safeLoad( p1, { filename: fileInfo.fileWithPath } );

        // Assign the parsed frontMatter to fileInfo
        fileInfo.frontMatter = frontMatter;

        // This will ensure that frontMatter will disappear, as it should
        return '';
        ;
      });

    } catch ( e ) {
      return cb( e );
    }

    // All done. At this point, fileContents might have the front matter missing and fileInfo
    // might have the frontMatter attribute added to it
    cb( null, fileContents, fileInfo );
  }

  // Return the function just defined as the filter
  cb( null, p1 );
});

// Read header, save data in it
eventEC.onCollect( 'filterBeforePlugins', function( cb ){

  var p1 = function( fileContents, fileInfo, cb ){
    fileContents += " PROCESSED 1";

    cb( null, fileContents, fileInfo );
  }

  cb( null, p1 );

});

eventEC.onCollect( 'filterAfterPlugins', function( cb ){

  var p1 = function( fileContents, fileInfo, cb ){
    fileContents += " PROCESSED 2";

    cb( null, fileContents, fileInfo );
  }

  cb( null, p1 );

});

// Go through every file, and emit an event for each one
function go( path, cb ){

  fs.readdir( path, function( err, files ){
    if( err ) return cb( err );

    console.log( "FILES:", files );

    var info = null;
    if( files.indexOf( 'info.yaml' ) !== -1 ){

      fs.readFile( p.join( path, 'info.yaml' ), function( err, loadedInfo ){
        if( err ) return cb( err );

        try {
          info = yaml.safeLoad( loadedInfo, { filename: p.join( path, 'info.json' ) } );
        } catch ( e ){
          return cb( e );
        }
        restOfFunction();
      });
    } else {
      restOfFunction();
    }

    function restOfFunction(){

      async.eachSeries(
        files,
        function( file, cb ){

          if( file[ 0 ] === '_' ) return cb( null );

          var fileWithPath = p.join( path, file );

          fs.lstat( fileWithPath, function( err, fileStat ){
            if( err ) return cb( err );

            // It's a directory: rerun the whole thing in that directory
            if( fileStat.isDirectory() ){

              console.log("DIR!", fileWithPath );
              return go( fileWithPath, cb );
            };

            fs.readFile( fileWithPath, function( err, fileContentsAsBuffer ){
              if( err ) return cb( err );

              fileContents = fileContentsAsBuffer.toString();

              magic.detect( fileContentsAsBuffer, function( err, magic ){

                // Sets the basic file info
                var fileInfo = {
                  file: file,
                  fileWithPath: fileWithPath,
                  path: path,
                  fileContentsAsBuffer: fileContentsAsBuffer,
                  info: info,
                  mimetype: magic
                };

                eventEC.emitCollect( 'filterBeforePlugins', function( err, beforePlugins ){
                  if( err ) return cb( err );

                  eventEC.emitCollect( 'filterAfterPlugins', function( err, afterPlugins ){
                    if( err ) return cb( err );

                    var toExecute = [ function( cb ){
                      return cb( null, fileContents, fileInfo );
                    } ].concat( beforePlugins.onlyResults(), pluginResolver, afterPlugins.onlyResults() );

                    async.waterfall( toExecute, function( err, fileContents, fileInfo){
                      if( err ) return cb( err );

                      eventEC.emitCollect( 'afterFilter', function( err, afterFilters ){
                        if( err ) return cb( err );

                        async.applyEach( afterFilters.onlyResults(), fileContents, fileInfo, function( err ){

                          if( err ) return cb( null );

                          console.log("RESULT: ", fileInfo );

                          cb( null );
                        });
                      });
            		    })
            		  })
            		})
              })
            })
          })
        },

        function( err ){
          if( err ) return cb( err );

          eventEC.emitCollect( 'afterFilter', function( err, afterFilters ){
            if( err ) return cb( err );

            async.applyEach( afterFilters.onlyResults(), function( err ){

              if( err ) return cb( null );

              cb( null );
            });
         });
        }
      ); // End of async cycle

    }

  })
}

// Let the fun begin!
go( 'test', function( err ){
  if( err ){
    console.log("ERROR! ", err );
    process.exit();
  }

  console.log("ALL FINISED!");
});
<commit_msg>Deleted old indexWithTags<commit_after><|endoftext|>


<commit_before>/**
 * @(#)yobi.user.SignUp.js 2013.04.02
 *
 * Copyright NHN Corporation.
 * Released under the MIT license
 *
 * http://yobi.dev.naver.com/license
 */

(function(ns){

    var oNS = $yobi.createNamespace(ns);
    oNS.container[oNS.name] = function(){

        var htVar = {};
        var htElement = {};

        /**
         * initialize
         */
        function _init(){
            _initElement();
            _initVar();

            _initFormValidator();
            _attachEvent();
        }

        /**
         * initialize elements
         */
        function _initElement(){
            htElement.welInputPassword  = $('#password');
            htElement.welInputPassword2 = $('#retypedPassword');
            htElement.welInputEmail     = $('#email');
            htElement.welInputLoginId   = $('#loginId');
            htElement.welInputLoginId.focus();

            htElement.welForm = $("form[name=signup]");

        }

        /**
         * initialize variables
         */
        function _initVar(){
            htVar.rxLoginId = /^[a-zA-Z0-9-]+([_.][a-zA-Z0-9-]+)*$/;
        }

        /**
         * attach event
         */
        function _attachEvent(){
            htElement.welInputLoginId.focusout(_onBlurInputLoginId);
            htElement.welInputEmail.focusout(_onBlurInputEmail);
            htElement.welInputPassword.focusout(_onBlurInputPassword);
            htElement.welInputPassword2.focusout(_onBlurInputPassword);
        }

        /**
         * 아이디 입력란 벗어날 때 이벤트 핸들러
         * 중복여부 즉시 확인
         */
        function _onBlurInputLoginId(){
            var welInput = $(this);
            var sLoginId = $yobi.getTrim(welInput.val()).toLowerCase();
            welInput.val(sLoginId);

            if(_onValidateLoginId(sLoginId) === false){
                showErrorMessage(welInput, Messages("validation.allowedCharsForLoginId"));
                return false;
            }

            if(sLoginId != ""){
                doesExists($(this), "/user/isExist/");
            }
        }

        /**
         * 이메일 입력란 벗어날 때 이벤트 핸들러
         * 중복여부 즉시 확인
         */
        function _onBlurInputEmail(){
            var welInput = $(this);

            if(welInput.val() !== ""){
                doesExists(welInput, "/user/isEmailExist/");
            }
        }

        /**
         * 비밀번호 확인 입력란 벗어날 때 이벤트 핸들러
         * 마지막 입력란이므로 전체 폼 유효성 검사
         */
        function _onBlurInputPassword(){
            htVar.oValidator._validateForm();
        }

        /**
         * @param {Wrapped Element} welInput
         * @param {String} sURL
         */
        function doesExists(welInput, sURL){
            if(sURL.substr(-1) != "/"){
                sURL += "/";
            }

            $.ajax({
                "url": sURL + welInput.val()
            }).done(function(htData){
                if(htData.isExist === true){
                    showErrorMessage(welInput, Messages("validation.duplicated"));
                } else if (htData.isReserved == true) {
                    showErrorMessage(welInput, Messages("validation.reservedWord"));
                } else {
                    hideErrorMessage(welInput);
                }
            });
        }

        /**
         * initialize FormValidator
         * @require validate.js
         */
        function _initFormValidator(){
            var aRules = [
                {"name": 'loginId',         "rules": 'required|callback_check_loginId'},
                {"name": 'email',           "rules": 'required|valid_email'},
                {"name": 'password',        "rules": 'required|min_length[4]'},
                {"name": 'retypedPassword', "rules": 'required|matches[password]'}
            ];

            htVar.oValidator = new FormValidator('signup', aRules, _onFormValidate);
            htVar.oValidator.registerCallback('check_loginId', _onValidateLoginId)

            // set error message
            htVar.oValidator.setMessage('check_loginId', Messages("validation.allowedCharsForLoginId"));
            htVar.oValidator.setMessage('required',      Messages("validation.required"));
            htVar.oValidator.setMessage('min_length',    Messages("validation.tooShortPassword"));
            htVar.oValidator.setMessage('matches',       Messages("validation.passwordMismatch"));
            htVar.oValidator.setMessage('valid_email',   Messages("validation.invalidEmail"));
        }

        /**
         * login id validation
         * @param {String} sLoginId
         * @return {Boolean}
         */
        function _onValidateLoginId(sLoginId){
            return htVar.rxLoginId.test(sLoginId);
        }

        /**
         * on validate form
         * @param {Array} aErrors
         */
        function _onFormValidate(aErrors){
            _clearTooltips();
            // to avoid bootstrap bug
            if (aErrors.length <= 0) {
                return _clearTooltips();
            }

            var welTarget;
            aErrors.forEach(function(htError){
                welTarget = htElement.welForm.find("input[name=" + htError.name + "]");
                if(welTarget){
                    showErrorMessage(welTarget, htError.message);
                }
            });
        }

        /**
         * 폼 영역에 있는 jquery.tooltip 모두 제거하는 함수
         */
        function _clearTooltips(){
            try {
                htElement.welForm.find("input").each(function(i, v){
                    $(v).tooltip("destroy");
                });
            } catch(e){}
        }

        /**
         * Bootstrap toolTip function has some limitation.
         * In this case, toolTip doesn't provide easy way to change title and contents.
         * So, unfortunately I had to change data value in directly.
         * @param {Wrapped Element} welInput
         * @param {String} sMessage
         */
        function showErrorMessage(welInput, sMessage){
            welInput.tooltip({"trigger": "manual", "placement": "left"});

            var oToolTip = welInput.data('tooltip');
            oToolTip.options.placement = 'left';
            oToolTip.options.trigger   = 'manual';
            oToolTip.options.title     = sMessage;
            oToolTip.options.content   = sMessage;

            welInput.tooltip('show');
        }

        function hideErrorMessage(welInput){
            welInput.tooltip("hide");

            try{
                welInput.tooltip("destroy");
            } catch(e){} // to avoid bootstrap bug
        }

        _init();
    };
})("yobi.user.SignUp");
<commit_msg>SignUp: use $.popover() instead of $.tooltip()<commit_after>/**
 * @(#)yobi.user.SignUp.js 2013.04.02
 *
 * Copyright NHN Corporation.
 * Released under the MIT license
 *
 * http://yobi.dev.naver.com/license
 */

(function(ns){

    var oNS = $yobi.createNamespace(ns);
    oNS.container[oNS.name] = function(){

        var htVar = {};
        var htElement = {};

        /**
         * initialize
         */
        function _init(){
            _initElement();
            _initVar();

            _initFormValidator();
            _attachEvent();
        }

        /**
         * initialize elements
         */
        function _initElement(){
            htElement.welInputPassword  = $('#password');
            htElement.welInputPassword2 = $('#retypedPassword');
            htElement.welInputEmail     = $('#email');
            htElement.welInputLoginId   = $('#loginId');
            htElement.welInputLoginId.focus();

            htElement.welForm = $("form[name=signup]");

        }

        /**
         * initialize variables
         */
        function _initVar(){
            htVar.rxLoginId = /^[a-zA-Z0-9-]+([_.][a-zA-Z0-9-]+)*$/;
        }

        /**
         * attach event
         */
        function _attachEvent(){
            htElement.welInputLoginId.focusout(_onBlurInputLoginId);
            htElement.welInputEmail.focusout(_onBlurInputEmail);
            htElement.welInputPassword.focusout(_onBlurInputPassword);
            htElement.welInputPassword2.focusout(_onBlurInputPassword);
        }

        /**
         * 아이디 입력란 벗어날 때 이벤트 핸들러
         * 중복여부 즉시 확인
         */
        function _onBlurInputLoginId(){
            var welInput = $(this);
            var sLoginId = $yobi.getTrim(welInput.val()).toLowerCase();
            welInput.val(sLoginId);

            if(_onValidateLoginId(sLoginId) === false){
                showErrorMessage(welInput, Messages("validation.allowedCharsForLoginId"));
                return false;
            }

            if(sLoginId != ""){
                doesExists($(this), "/user/isExist/");
            }
        }

        /**
         * 이메일 입력란 벗어날 때 이벤트 핸들러
         * 중복여부 즉시 확인
         */
        function _onBlurInputEmail(){
            var welInput = $(this);

            if(welInput.val() !== ""){
                doesExists(welInput, "/user/isEmailExist/");
            }
        }

        /**
         * 비밀번호 확인 입력란 벗어날 때 이벤트 핸들러
         * 마지막 입력란이므로 전체 폼 유효성 검사
         */
        function _onBlurInputPassword(){
            htVar.oValidator._validateForm();
        }

        /**
         * @param {Wrapped Element} welInput
         * @param {String} sURL
         */
        function doesExists(welInput, sURL){
            if(sURL.substr(-1) != "/"){
                sURL += "/";
            }

            $.ajax({
                "url": sURL + welInput.val()
            }).done(function(htData){
                if(htData.isExist === true){
                    showErrorMessage(welInput, Messages("validation.duplicated"));
                } else if (htData.isReserved == true) {
                    showErrorMessage(welInput, Messages("validation.reservedWord"));
                } else {
                    hideErrorMessage(welInput);
                }
            });
        }

        /**
         * initialize FormValidator
         * @require validate.js
         */
        function _initFormValidator(){
            var aRules = [
                {"name": 'loginId',         "rules": 'required|callback_check_loginId'},
                {"name": 'email',           "rules": 'required|valid_email'},
                {"name": 'password',        "rules": 'required|min_length[4]'},
                {"name": 'retypedPassword', "rules": 'required|matches[password]'}
            ];

            htVar.oValidator = new FormValidator('signup', aRules, _onFormValidate);
            htVar.oValidator.registerCallback('check_loginId', _onValidateLoginId)

            // set error message
            htVar.oValidator.setMessage('check_loginId', Messages("validation.allowedCharsForLoginId"));
            htVar.oValidator.setMessage('required',      Messages("validation.required"));
            htVar.oValidator.setMessage('min_length',    Messages("validation.tooShortPassword"));
            htVar.oValidator.setMessage('matches',       Messages("validation.passwordMismatch"));
            htVar.oValidator.setMessage('valid_email',   Messages("validation.invalidEmail"));
        }

        /**
         * login id validation
         * @param {String} sLoginId
         * @return {Boolean}
         */
        function _onValidateLoginId(sLoginId){
            return htVar.rxLoginId.test(sLoginId);
        }

        /**
         * on validate form
         * @param {Array} aErrors
         */
        function _onFormValidate(aErrors){
            _clearTooltips();
            // to avoid bootstrap bug
            if (aErrors.length <= 0) {
                return _clearTooltips();
            }

            var welTarget;
            aErrors.forEach(function(htError){
                welTarget = htElement.welForm.find("input[name=" + htError.name + "]");
                if(welTarget){
                    showErrorMessage(welTarget, htError.message);
                }
            });
        }

        /**
         * 폼 영역에 있는 jquery.tooltip 모두 제거하는 함수
         */
        function _clearTooltips(){
            try {
                htElement.welForm.find("input").each(function(i, v){
                    $(v).tooltip("destroy");
                });
            } catch(e){}
        }

        /**
         * Bootstrap toolTip function has some limitation.
         * In this case, toolTip doesn't provide easy way to change title and contents.
         * So, unfortunately I had to change data value in directly.
         * @param {Wrapped Element} welInput
         * @param {String} sMessage
         */
        function showErrorMessage(welInput, sMessage){
            welInput.popover({"trigger": "manual", "placement": "left"});

            var oToolTip = welInput.data('popover');
            oToolTip.options.placement = 'left';
            oToolTip.options.trigger   = 'manual';
            oToolTip.options.content   = sMessage;

            welInput.popover('show');
        }

        function hideErrorMessage(welInput){
            welInput.popover("hide");

            try{
                welInput.popover("destroy");
            } catch(e){} // to avoid bootstrap bug
        }

        _init();
    };
})("yobi.user.SignUp");
<|endoftext|>


<commit_before>(function(){
  console.log("run longTest");
  var userStoryUuid="addNode";
  var testName="add1000Nodes";

  var commonAPI = new CommonAPI();

  var file = $("<a>");
  $("<div>").html("hej").appendTo(file);

  commonAPI.initRepo().then(
    function(data) {
      return commonAPI.commit("a.txt", file[0].outerHTML, "texts");
    },
    function(data) {
      reportIn(userStoryUuid,testName,"error");
      alert("init dont work");
    }
  ).then(
    function(data) {
      return commonAPI.getHEAD();
    },function(data) {
      reportIn(userStoryUuid,testName,"error");
      alert("commit dont work");
    }
  ).then(
    function(data) {
      return compare(file[0].outerHTML, data.files[0].fileContent);
    },function(data) {
      reportIn(userStoryUuid,testName,"error");
      alert("get head dont work");
    }
  ).then(
      function(fromServer) {
        return commonAPI.getLog();
        reportIn(userStoryUuid,testName,"success");
      },function(data) {
        reportIn(userStoryUuid,testName,"error");
        alert("compare dont work");
      }
  )
})();<commit_msg>fixes return before reporting<commit_after>(function(){
  console.log("run longTest");
  var userStoryUuid="addNode";
  var testName="add1000Nodes";

  var commonAPI = new CommonAPI();

  var file = $("<a>");
  $("<div>").html("hej").appendTo(file);

  commonAPI.initRepo().then(
    function(data) {
      return commonAPI.commit("a.txt", file[0].outerHTML, "texts");
    },
    function(data) {
      reportIn(userStoryUuid,testName,"error");
      alert("init dont work");
    }
  ).then(
    function(data) {
      return commonAPI.getHEAD();
    },function(data) {
      reportIn(userStoryUuid,testName,"error");
      alert("commit dont work");
    }
  ).then(
    function(data) {
      return compare(file[0].outerHTML, data.files[0].fileContent);
    },function(data) {
      reportIn(userStoryUuid,testName,"error");
      alert("get head dont work");
    }
  ).then(
      function(fromServer) {
        reportIn(userStoryUuid,testName,"success");
        return commonAPI.getLog();
      },function(data) {
        reportIn(userStoryUuid,testName,"error");
        alert("compare dont work");
      }
  );
})();
<|endoftext|>


<commit_before>function hello(language) {
  var hellos = {
    'Chinese': '你好世界',
    'Dutch': 'Hello wereld',
    'English': 'Hello world',
    'French': 'Bonjour monde',
    'German': 'Hallo Welt',
    'Greek': 'γειά σου κόσμος',
    'Italian': 'Ciao mondo',
    'Japanese': 'こんにちは世界',
    'Korean': '안녕하세요 세계',
    'Portuguese': 'Olá mundo',
    'Russian': 'Здравствулте мир',
    'Spanish': 'Hola mundo',
    'Latin': 'Salve munde',
    'Piglatin': 'Ellohay orldway'
  };
  return hellos[language];
}<commit_msg>feat(international.js): Added Indonesian<commit_after>function hello(language) {
  var hellos = {
    'Chinese': '你好世界',
    'Dutch': 'Hello wereld',
    'English': 'Hello world',
    'French': 'Bonjour monde',
    'German': 'Hallo Welt',
    'Greek': 'γειά σου κόσμος',
    'Indonesian': 'Halo dunia',
    'Italian': 'Ciao mondo',
    'Japanese': 'こんにちは世界',
    'Korean': '안녕하세요 세계',
    'Portuguese': 'Olá mundo',
    'Russian': 'Здравствулте мир',
    'Spanish': 'Hola mundo',
    'Latin': 'Salve munde',
    'Piglatin': 'Ellohay orldway'
  };
  return hellos[language];
}
<|endoftext|>


<commit_before>var $ = require('interlude');
var Tournament = require('tournament');

function Id(t, id) {
  $.extend(this, id); // Tournament style { s, r, m }
  this.t = t; // add stage number - override if exists (from sub Tourney)
}

Id.prototype.toString = function () {
  return "T" + this.t + " S" + this.s + " R" + this.r + " M" + this.m;
};

//------------------------------------------------------------------
// Setup and statics
//------------------------------------------------------------------

function Tourney(np, inst) {
  this._inst = inst;
  this.matches = inst.matches; // proxy reference
  this.oldMatches = []; // stash matches from completed instances here
  this._stage = 1;
  this._oldRes = [];
  // for determining when we can expect Tourney API
  Object.defineProperty(this, 'hasStages', { value: true });
}

Tourney.inherit = function (Klass, Initial) {
  Initial = Initial || Tourney;
  Klass.prototype = Object.create(Initial.prototype);

  var methods = {
    _createNext: false,
    _mustPropagate: false,
    _proxyRes: false,
    _updateRes: null
  };
  Object.keys(methods).forEach(function (fn) {
    // Implement a default if not already implemented (when Initial is Tourney)
    Klass.prototype[fn] = Initial.prototype[fn] || $.constant(methods[fn]);
  });

  Klass.configure = function (obj) {
    // Preserve Tournament API for invalid and defaults
    Tournament.configure(Klass, obj, Initial);
  };

  Klass.from = function (inst, numPlayers, opts) {
    // Since Tourney instances have same interface, can reuse Tournament.from
    var from = Tournament.from(Klass, inst, numPlayers, opts);
    from._oldRes = inst.results();
    return from;
  };

  // ignore inherited `sub` and `inherit` for now for sanity
};

Tourney.defaults = Tournament.defaults;
Tourney.invalid = Tournament.invalid;

Tourney.sub = function (name, init, Initial) {
  // Preserve Tournament API. This ultimately calls Tourney.inherit
  return Tournament.sub(name, init, Initial || Tourney);
};

//------------------------------------------------------------------
// Pure proxy methods
//------------------------------------------------------------------

Tourney.prototype.unscorable = function (id, score, allowPast) {
  return this._inst.unscorable(id, score, allowPast);
};
Tourney.prototype.score = function (id, score) {
  return this._inst.score(id, score);
};
Tourney.prototype.upcoming = function (playerId) {
  return this._inst.upcoming(playerId);
};
Tourney.prototype.players = function (id) {
  return this._inst.players(id);
};
Tourney.prototype.findMatch = function (id) {
  return this._inst.findMatch(id);
};
Tourney.prototype.findMatches = function (id) {
  return this._inst.findMatches(id);
};

//------------------------------------------------------------------
// Helpers for piping modules together
//------------------------------------------------------------------

Tourney.prototype.getName = function (depth) {
  var names = [];
  for (var inst = this._inst; inst ; inst = inst._inst) {
    names.push(inst.name);
  }
  return names.slice(0, depth).join('::');
};

Tourney.prototype.isDone = function () {
  // self-referential isDone for Tourney's (checking if subTourneys are done)
  // but this eventually ends in a Tournament::isDone()
  return this._inst.isDone() &&
        !this._mustPropagate(this._stage, this._inst, this._opts);
};

Tourney.prototype.stageDone = function () {
  return this._inst[this._inst.hasStages ? 'stageDone' : 'isDone']();
};

var formatCurrent = function (stage, ms) {
  // prepare matches from a completed instance for oldMatches
  // NB: if `ms` come from a Tourney, the stage `t` key will be overridden
  // and will use the counter relative to this Tourney
  return ms.map(function (m) {
    var o = { id: new Id(stage, m.id), p: m.p.slice() };
    if (m.m) {
      o.m = m.m.slice();
    }
    return o;
  });
};

Tourney.prototype.createNextStage = function () {
  if (!this.stageDone()) {
    throw new Error("cannot start next stage until current one is done");
  }
  if (this.isDone()) {
    return false;
  }

  // extend current matches' ids with `t` = this._stage (overwriting if necessary)
  var completedMatches = formatCurrent(this._stage, this.matches);
  Array.prototype.push.apply(this.oldMatches, completedMatches);

  // update results for players still in it
  this._oldRes = this.results();

  this._stage += 1;
  // propagate createNext if we have a Tourney instance embedded
  if (this._inst.hasStages && !this._inst.isDone()) {
    this._inst.createNextStage();
    this.matches = this._inst.matches; // update link
    return true;
  }
  // and seal it down if all its stages were done
  if (this._inst.hasStages) {
    this._inst.complete();
  }

  // otherwise _createNext needs to handle progression
  this._inst = this._createNext(this._stage, this._inst, this._opts);
  this.matches = this._inst.matches;
  return true;
};

Tourney.prototype.complete = function () {
  if (!this.isDone()) {
    throw new Error("cannot complete a tourney until it is done");
  }
  // last oldMatches extend
  var completedMatches = formatCurrent(this._stage, this.matches);
  Array.prototype.push.apply(this.oldMatches, completedMatches);
  this.matches = [];
  this.unscorable = $.constant("cannot score matches after completing a tourney");
  this.score = function () {
    console.error(this.unscorable());
    return false;
  };
};

//------------------------------------------------------------------
// Extra helpers - probably won't be included
//------------------------------------------------------------------
/*
Tourney.prototype.rounds = function (stage) {
  return helper.partitionMatches(this.allMatches(), 'r', 't', stage);
};

Tourney.prototype.section = function (stage) {
  return helper.partitionMatches(this.allMatches(), 's', 't', stage);
};

Tourney.prototype.stages = function (section) {
  return helper.partitionMatches(this.allMatches(), 't', 's', section);
};
*/

//------------------------------------------------------------------
// Results
//
// If current instance does not report results for all players,
// we append knocked out players' results from their previous stage.
// By induction, all players always exist in `results`.
//------------------------------------------------------------------

// NB: same as Tournament.resultEntry but does not throw
var resultEntry = function (res, p) {
  return $.firstBy(function (r) {
    return r.seed === p;
  }, res);
};

Tourney.prototype.results = function () {
  var curr = this._inst.results();
  if (this._proxyRes()) {
    return curr;
  }

  var previous = this._oldRes;
  var knockOut = previous.filter(function (r) {
    // players not in current stage exist in previous results below
    return !resultEntry(curr, r.seed);
  });

  var updater = this._updateRes.bind(this);
  return curr.map(function (r) {
    var old = resultEntry(previous, r.seed);
    if (old) {
      updater(r, old);
    }
    return r;
  }).concat(knockOut);
};

//------------------------------------------------------------------

module.exports = Tourney;
<commit_msg>rename to indicate what it is<commit_after>var $ = require('interlude');
var Tournament = require('tournament');

function Id(t, id) {
  $.extend(this, id); // Tournament style { s, r, m }
  this.t = t; // add stage number - override if exists (from sub Tourney)
}

Id.prototype.toString = function () {
  return "T" + this.t + " S" + this.s + " R" + this.r + " M" + this.m;
};

//------------------------------------------------------------------
// Setup and statics
//------------------------------------------------------------------

function Tourney(np, inst) {
  this._inst = inst;
  this.matches = inst.matches; // proxy reference
  this.oldMatches = []; // stash matches from completed instances here
  this._stage = 1;
  this._oldRes = [];
  // for determining when we can expect Tourney API
  Object.defineProperty(this, 'hasStages', { value: true });
}

Tourney.inherit = function (Klass, Initial) {
  Initial = Initial || Tourney;
  Klass.prototype = Object.create(Initial.prototype);

  var virtuals = {
    _createNext: false,
    _mustPropagate: false,
    _proxyRes: false,
    _updateRes: null
  };
  Object.keys(virtuals).forEach(function (fn) {
    // Implement a default if not already implemented (when Initial is Tourney)
    Klass.prototype[fn] = Initial.prototype[fn] || $.constant(virtuals[fn]);
  });

  Klass.configure = function (obj) {
    // Preserve Tournament API for invalid and defaults
    Tournament.configure(Klass, obj, Initial);
  };

  Klass.from = function (inst, numPlayers, opts) {
    // Since Tourney instances have same interface, can reuse Tournament.from
    var from = Tournament.from(Klass, inst, numPlayers, opts);
    from._oldRes = inst.results();
    return from;
  };

  // ignore inherited `sub` and `inherit` for now for sanity
};

Tourney.defaults = Tournament.defaults;
Tourney.invalid = Tournament.invalid;

Tourney.sub = function (name, init, Initial) {
  // Preserve Tournament API. This ultimately calls Tourney.inherit
  return Tournament.sub(name, init, Initial || Tourney);
};

//------------------------------------------------------------------
// Pure proxy methods
//------------------------------------------------------------------

Tourney.prototype.unscorable = function (id, score, allowPast) {
  return this._inst.unscorable(id, score, allowPast);
};
Tourney.prototype.score = function (id, score) {
  return this._inst.score(id, score);
};
Tourney.prototype.upcoming = function (playerId) {
  return this._inst.upcoming(playerId);
};
Tourney.prototype.players = function (id) {
  return this._inst.players(id);
};
Tourney.prototype.findMatch = function (id) {
  return this._inst.findMatch(id);
};
Tourney.prototype.findMatches = function (id) {
  return this._inst.findMatches(id);
};

//------------------------------------------------------------------
// Helpers for piping modules together
//------------------------------------------------------------------

Tourney.prototype.getName = function (depth) {
  var names = [];
  for (var inst = this._inst; inst ; inst = inst._inst) {
    names.push(inst.name);
  }
  return names.slice(0, depth).join('::');
};

Tourney.prototype.isDone = function () {
  // self-referential isDone for Tourney's (checking if subTourneys are done)
  // but this eventually ends in a Tournament::isDone()
  return this._inst.isDone() &&
        !this._mustPropagate(this._stage, this._inst, this._opts);
};

Tourney.prototype.stageDone = function () {
  return this._inst[this._inst.hasStages ? 'stageDone' : 'isDone']();
};

var formatCurrent = function (stage, ms) {
  // prepare matches from a completed instance for oldMatches
  // NB: if `ms` come from a Tourney, the stage `t` key will be overridden
  // and will use the counter relative to this Tourney
  return ms.map(function (m) {
    var o = { id: new Id(stage, m.id), p: m.p.slice() };
    if (m.m) {
      o.m = m.m.slice();
    }
    return o;
  });
};

Tourney.prototype.createNextStage = function () {
  if (!this.stageDone()) {
    throw new Error("cannot start next stage until current one is done");
  }
  if (this.isDone()) {
    return false;
  }

  // extend current matches' ids with `t` = this._stage (overwriting if necessary)
  var completedMatches = formatCurrent(this._stage, this.matches);
  Array.prototype.push.apply(this.oldMatches, completedMatches);

  // update results for players still in it
  this._oldRes = this.results();

  this._stage += 1;
  // propagate createNext if we have a Tourney instance embedded
  if (this._inst.hasStages && !this._inst.isDone()) {
    this._inst.createNextStage();
    this.matches = this._inst.matches; // update link
    return true;
  }
  // and seal it down if all its stages were done
  if (this._inst.hasStages) {
    this._inst.complete();
  }

  // otherwise _createNext needs to handle progression
  this._inst = this._createNext(this._stage, this._inst, this._opts);
  this.matches = this._inst.matches;
  return true;
};

Tourney.prototype.complete = function () {
  if (!this.isDone()) {
    throw new Error("cannot complete a tourney until it is done");
  }
  // last oldMatches extend
  var completedMatches = formatCurrent(this._stage, this.matches);
  Array.prototype.push.apply(this.oldMatches, completedMatches);
  this.matches = [];
  this.unscorable = $.constant("cannot score matches after completing a tourney");
  this.score = function () {
    console.error(this.unscorable());
    return false;
  };
};

//------------------------------------------------------------------
// Extra helpers - probably won't be included
//------------------------------------------------------------------
/*
Tourney.prototype.rounds = function (stage) {
  return helper.partitionMatches(this.allMatches(), 'r', 't', stage);
};

Tourney.prototype.section = function (stage) {
  return helper.partitionMatches(this.allMatches(), 's', 't', stage);
};

Tourney.prototype.stages = function (section) {
  return helper.partitionMatches(this.allMatches(), 't', 's', section);
};
*/

//------------------------------------------------------------------
// Results
//
// If current instance does not report results for all players,
// we append knocked out players' results from their previous stage.
// By induction, all players always exist in `results`.
//------------------------------------------------------------------

// NB: same as Tournament.resultEntry but does not throw
var resultEntry = function (res, p) {
  return $.firstBy(function (r) {
    return r.seed === p;
  }, res);
};

Tourney.prototype.results = function () {
  var curr = this._inst.results();
  if (this._proxyRes()) {
    return curr;
  }

  var previous = this._oldRes;
  var knockOut = previous.filter(function (r) {
    // players not in current stage exist in previous results below
    return !resultEntry(curr, r.seed);
  });

  var updater = this._updateRes.bind(this);
  return curr.map(function (r) {
    var old = resultEntry(previous, r.seed);
    if (old) {
      updater(r, old);
    }
    return r;
  }).concat(knockOut);
};

//------------------------------------------------------------------

module.exports = Tourney;
<|endoftext|>


<commit_before>/*
 * Tangram
 * Copyright 2011 Baidu Inc. All rights reserved.
 */
///import baidu.ui.createUI;
///import baidu.dom.insertHTML;
///import baidu.dom.children;
///import baidu.dom.getStyle;
///import baidu.dom.create;
///import baidu.dom.remove;
///import baidu.dom.addClass;
///import baidu.dom.removeClass;
///import baidu.string.format;
///import baidu.array.each;
///import baidu.array.indexOf;
///import baidu.browser.ie;
///import baidu.fn.bind;

baidu.ui.Carousel = baidu.ui.createUI(function(options){
    var me = this,
        data = me.contentText || [];
    me._datas = data.slice(0, data.length);
    me._itemIds = [];
    me._items = {};//用来存入被删除的节点，当再次被使用时可以直接拿回来
    baidu.array.each(me._datas, function(item){
        me._itemIds.push(baidu.lang.guid());
    })
    me.flip = me.flip.toLowerCase();
    me.orientation = me.orientation.toLowerCase();
}).extend(
    /**
     *  @lends baidu.ui.Carousel.prototype
     */
{
    uiType: 'carousel',
    orientation: 'horizontal',//horizontal|vertical
    //direction: 'down',//up|right|down|left
    flip: 'item',//item|page
    pageSize: 3,
    scrollIndex: 0,
    offsetWidth: 0,
    offsetHeight: 0,

    _axis: {
        horizontal: {pos: 'left', size: 'width', offset: 'offsetWidth', scrollPos: 'scrollLeft', scrollSize: 'scrollWidth'},
        vertical: {pos: 'top', size: 'height', offset: 'offsetHeight', scrollPos: 'scrollTop', scrollSize: 'scrollHeight'}
    },

    tplDOM: '
#{content}
',

    getString: function(){
        var me = this,
            str = baidu.string.format(me.tplDOM, {
                id: me.getId('scroll'),
                'class': me.getClass('scroll')
            });
        return baidu.string.format(me.tplDOM, {
            id: me.getId(),
            'class': me.getClass(),
            content: str
        });
    },

    render: function(target){
        var me = this;
        if(!target || me.getMain()){return;}
        baidu.dom.insertHTML(me.renderMain(target), 'beforeEnd', me.getString());
        me._renderItems();
//        me._renderItems(8, 0);
        me._resizeView();
        me._moveCenter();
        me.focus(me.scrollIndex);
        me.dispatchEvent('onload');
    },

    _renderItems: function(index, offset){
        var me = this,
            sContainer = me.getScrollContainer(),
            index = Math.min(Math.max(index | 0, 0), me._datas.length - 1),
            offset = Math.min(Math.max(offset | 0, 0), me.pageSize - 1),
            sContainer = me.getScrollContainer(),
            i = 0,
            count = me.pageSize * 3;
        index < offset && (offset = index);//这种情况比如把1放到可视区域2的位置
        sContainer.innerHTML = '';
        for(; i < count; i++){
            sContainer.appendChild(
                me._getItemElement(index - offset - me.pageSize + i)
            );
        }
    },

    _moveCenter: function(){
        if(!this._boundX && !this._boundY){return;}
        var me = this,
            axis = me._axis[me.orientation],
            orie = me.orientation == 'horizontal'
            ieOffset = orie && baidu.browser.ie == 6 ? me._boundX.marginX : 0;
        me.getBody()[axis.scrollPos] = me[axis.offset]
            * me.pageSize
            + (orie ? 0 : Math.abs(Math.max(me._boundY.marginX, me._boundY.marginY) / 2 - me._boundY.marginX))
            + ieOffset;
    },

    _resizeView: function(){
        if(this._datas.length <= 0){return;}//没有数据
        var me = this,
            axis = me._axis[me.orientation],
            orie = me.orientation == 'horizontal',
            sContainer = me.getScrollContainer(),
            child = baidu.dom.children(sContainer),
            boundX,
            boundY;
        function getItemBound(item, type){
            var type = type == 'x',
                bound = item[type ? 'offsetWidth' : 'offsetHeight'],
                marginX = parseInt(baidu.dom.getStyle(item, type ? 'marginLeft' : 'marginTop')),
                marginY = parseInt(baidu.dom.getStyle(item, type ? 'marginRight' : 'marginBottom'));
            isNaN(marginX) && (marginX = 0);
            isNaN(marginY) && (marginY = 0);
            return {
//                width: bound,
                offset: bound + (orie ? marginX + marginY : Math.max(marginX, marginY)),
                marginX: marginX,
                marginY: marginY
            };
        }
        me._boundX = boundX = getItemBound(child[0], 'x');
        me._boundY = boundY = getItemBound(child[0], 'y');
        me.offsetWidth <= 0 && (me.offsetWidth = boundX.offset);
        me.offsetHeight <= 0 && (me.offsetHeight = boundY.offset);

        sContainer.style.width = boundX.offset
            * (orie ? child.length : 1)
            + (baidu.browser.ie == 6 ? boundX.marginX + boundX.marginY : 0)
            + 'px';
        orie && (sContainer.style.height = boundY.offset + 'px');//如果是横向滚动需要设一下高度，防止不会自动撑开
        me.getBody().style[axis.size] = me[axis.offset] * me.pageSize + 'px';
    },

    _getItemElement: function(index){
        var me = this,
            itemId = me._itemIds[index],
            element = me._items[itemId],
            txt = me._datas[index];
        if(!element){
            element = baidu.dom.create('div', {
                id: itemId || '',
                'class': me.getClass('item')
            });
            element.innerHTML = txt ? txt.content : '';
            if(itemId){
                me._items[itemId] = element;
                element.onclick = baidu.fn.bind('_onItemClickHandler', me, element);
                element.onmouseover = baidu.fn.bind('_onMouseHandler', me, 'mouseover');
                element.onmouseout = baidu.fn.bind('_onMouseHandler', me, 'mouseout');
            }
        }
        return element;
    },

    _onItemClickHandler: function(ele, evt){
        var me = this;
        me.focus(baidu.array.indexOf(me._itemIds, ele.id));
        me.dispatchEvent('onitemclick');
    },

    _onMouseHandler: function(type, evt){
        var me = this;
        me.dispatchEvent('on' + type);
    },

    getCurrentIndex: function(){
        return this.scrollIndex;
    },

    getTotalCount: function(){
        return this._datas.length;
    },

    /**
     * 根据数据的索引值取得对应在页面的DOM节点，当节点不存时返回null
     * @param {Number} index 在数据中的索引值
     * @return {HTMLElement} 返回一个DOM节点
     */
    getItem: function(index){
        return baidu.dom.g(this._itemIds[index]);
    },

    /**
     *
     */
    scrollTo: function(index, scrollOffset){
        var me = this;
        if(me._datas.length <= 0){return;}
        if(me.dispatchEvent('onbeforescroll',
            {index: index, scrollOffset: offset})){
            me._renderItems(index, scrollOffset);
            me.dispatchEvent('onafterscroll');
        }
    },

    prev: function(){
        var me = this;
    },

    next: function(){
        var me = this;
    },

    isFirst: function(){
        return this.scrollIndex <= 0;
    },

    isLast: function(){
        var me = this;
        return me.scrollIndex >= me._datas.length - 1;
    },

    focus: function(index){
        var me = this,
            beforeItem = me._itemIds[index]
                && me._getItemElement(me.scrollIndex),
            currItem = me._itemIds[index]
                && me._getItemElement(index);
        beforeItem
            && baidu.dom.removeClass(beforeItem, me.getClass('item-focus'));
        if(currItem){
            baidu.dom.addClass(currItem, me.getClass('item-focus'));
            me.scrollIndex = index;
        }
    },

    getScrollContainer: function(){
        return baidu.dom.g(this.getId('scroll'));
    },

    dispose: function(){
        var me = this;
        me.dispatchEvent('ondispose');
        baidu.dom.remove(me.getMain());
        baidu.lang.Class.prototype.dispose.call(me);
    }
});<commit_msg>增加scrollTo中对传数的判断<commit_after>/*
 * Tangram
 * Copyright 2011 Baidu Inc. All rights reserved.
 */
///import baidu.ui.createUI;
///import baidu.dom.insertHTML;
///import baidu.dom.children;
///import baidu.dom.getStyle;
///import baidu.dom.create;
///import baidu.dom.remove;
///import baidu.dom.addClass;
///import baidu.dom.removeClass;
///import baidu.string.format;
///import baidu.array.each;
///import baidu.array.indexOf;
///import baidu.browser.ie;
///import baidu.fn.bind;

baidu.ui.Carousel = baidu.ui.createUI(function(options){
    var me = this,
        data = me.contentText || [];
    me._datas = data.slice(0, data.length);
    me._itemIds = [];
    me._items = {};//用来存入被删除的节点，当再次被使用时可以直接拿回来
    baidu.array.each(me._datas, function(item){
        me._itemIds.push(baidu.lang.guid());
    })
    me.flip = me.flip.toLowerCase();
    me.orientation = me.orientation.toLowerCase();
}).extend(
    /**
     *  @lends baidu.ui.Carousel.prototype
     */
{
    uiType: 'carousel',
    orientation: 'horizontal',//horizontal|vertical
    //direction: 'down',//up|right|down|left
    flip: 'item',//item|page
    pageSize: 3,
    scrollIndex: 0,
    offsetWidth: 0,
    offsetHeight: 0,

    _axis: {
        horizontal: {pos: 'left', size: 'width', offset: 'offsetWidth', scrollPos: 'scrollLeft', scrollSize: 'scrollWidth'},
        vertical: {pos: 'top', size: 'height', offset: 'offsetHeight', scrollPos: 'scrollTop', scrollSize: 'scrollHeight'}
    },

    tplDOM: '
#{content}
',

    getString: function(){
        var me = this,
            str = baidu.string.format(me.tplDOM, {
                id: me.getId('scroll'),
                'class': me.getClass('scroll')
            });
        return baidu.string.format(me.tplDOM, {
            id: me.getId(),
            'class': me.getClass(),
            content: str
        });
    },

    render: function(target){
        var me = this;
        if(!target || me.getMain()){return;}
        baidu.dom.insertHTML(me.renderMain(target), 'beforeEnd', me.getString());
        me._renderItems();
//        me._renderItems(8, 0);
        me._resizeView();
        me._moveCenter();
        me.focus(me.scrollIndex);
        me.dispatchEvent('onload');
    },

    _renderItems: function(index, offset){
        var me = this,
            sContainer = me.getScrollContainer(),
            index = Math.min(Math.max(index | 0, 0), me._datas.length - 1),
            offset = Math.min(Math.max(offset | 0, 0), me.pageSize - 1),
            sContainer = me.getScrollContainer(),
            i = 0,
            count = me.pageSize * 3;
        index < offset && (offset = index);//这种情况比如把1放到可视区域2的位置
        sContainer.innerHTML = '';
        for(; i < count; i++){
            sContainer.appendChild(
                me._getItemElement(index - offset - me.pageSize + i)
            );
        }
    },

    _moveCenter: function(){
        if(!this._boundX && !this._boundY){return;}
        var me = this,
            axis = me._axis[me.orientation],
            orie = me.orientation == 'horizontal'
            ieOffset = orie && baidu.browser.ie == 6 ? me._boundX.marginX : 0;
        me.getBody()[axis.scrollPos] = me[axis.offset]
            * me.pageSize
            + (orie ? 0 : Math.abs(Math.max(me._boundY.marginX, me._boundY.marginY) / 2 - me._boundY.marginX))
            + ieOffset;
    },

    _resizeView: function(){
        if(this._datas.length <= 0){return;}//没有数据
        var me = this,
            axis = me._axis[me.orientation],
            orie = me.orientation == 'horizontal',
            sContainer = me.getScrollContainer(),
            child = baidu.dom.children(sContainer),
            boundX,
            boundY;
        function getItemBound(item, type){
            var type = type == 'x',
                bound = item[type ? 'offsetWidth' : 'offsetHeight'],
                marginX = parseInt(baidu.dom.getStyle(item, type ? 'marginLeft' : 'marginTop')),
                marginY = parseInt(baidu.dom.getStyle(item, type ? 'marginRight' : 'marginBottom'));
            isNaN(marginX) && (marginX = 0);
            isNaN(marginY) && (marginY = 0);
            return {
//                width: bound,
                offset: bound + (orie ? marginX + marginY : Math.max(marginX, marginY)),
                marginX: marginX,
                marginY: marginY
            };
        }
        me._boundX = boundX = getItemBound(child[0], 'x');
        me._boundY = boundY = getItemBound(child[0], 'y');
        me.offsetWidth <= 0 && (me.offsetWidth = boundX.offset);
        me.offsetHeight <= 0 && (me.offsetHeight = boundY.offset);

        sContainer.style.width = boundX.offset
            * (orie ? child.length : 1)
            + (baidu.browser.ie == 6 ? boundX.marginX + boundX.marginY : 0)
            + 'px';
        orie && (sContainer.style.height = boundY.offset + 'px');//如果是横向滚动需要设一下高度，防止不会自动撑开
        me.getBody().style[axis.size] = me[axis.offset] * me.pageSize + 'px';
    },

    _getItemElement: function(index){
        var me = this,
            itemId = me._itemIds[index],
            element = me._items[itemId],
            txt = me._datas[index];
        if(!element){
            element = baidu.dom.create('div', {
                id: itemId || '',
                'class': me.getClass('item')
            });
            element.innerHTML = txt ? txt.content : '';
            if(itemId){
                me._items[itemId] = element;
                element.onclick = baidu.fn.bind('_onItemClickHandler', me, element);
                element.onmouseover = baidu.fn.bind('_onMouseHandler', me, 'mouseover');
                element.onmouseout = baidu.fn.bind('_onMouseHandler', me, 'mouseout');
            }
        }
        return element;
    },

    _onItemClickHandler: function(ele, evt){
        var me = this;
        me.focus(baidu.array.indexOf(me._itemIds, ele.id));
        me.dispatchEvent('onitemclick');
    },

    _onMouseHandler: function(type, evt){
        var me = this;
        me.dispatchEvent('on' + type);
    },

    getCurrentIndex: function(){
        return this.scrollIndex;
    },

    getTotalCount: function(){
        return this._datas.length;
    },

    /**
     * 根据数据的索引值取得对应在页面的DOM节点，当节点不存时返回null
     * @param {Number} index 在数据中的索引值
     * @return {HTMLElement} 返回一个DOM节点
     */
    getItem: function(index){
        return baidu.dom.g(this._itemIds[index]);
    },

    /**
     *
     */
    scrollTo: function(index, scrollOffset){
        var me = this,
            index = Math.min(Math.max(index | 0, 0), me._datas.length - 1),
            offset = Math.min(Math.max(scrollOffset | 0, 0), me.pageSize - 1);
        if(me._datas.length <= 0){return;}
        if(me.dispatchEvent('onbeforescroll',
            {index: index, scrollOffset: offset})){
            me._renderItems(index, scrollOffset);
            me.dispatchEvent('onafterscroll');
        }
    },

    prev: function(){
        var me = this;
    },

    next: function(){
        var me = this;
    },

    isFirst: function(){
        return this.scrollIndex <= 0;
    },

    isLast: function(){
        var me = this;
        return me.scrollIndex >= me._datas.length - 1;
    },

    focus: function(index){
        var me = this,
            beforeItem = me._itemIds[index]
                && me._getItemElement(me.scrollIndex),
            currItem = me._itemIds[index]
                && me._getItemElement(index);
        beforeItem
            && baidu.dom.removeClass(beforeItem, me.getClass('item-focus'));
        if(currItem){
            baidu.dom.addClass(currItem, me.getClass('item-focus'));
            me.scrollIndex = index;
        }
    },

    getScrollContainer: function(){
        return baidu.dom.g(this.getId('scroll'));
    },

    dispose: function(){
        var me = this;
        me.dispatchEvent('ondispose');
        baidu.dom.remove(me.getMain());
        baidu.lang.Class.prototype.dispose.call(me);
    }
});<|endoftext|>