<commit_before>angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $ionicSideMenuDelegate, $timeout, api, $timeout, $rootScope) {
    setTimeout(function() {
        $ionicSideMenuDelegate.toggleLeft();
        $rootScope.isSideMenuOpen = false;
    }, 100);
    $rootScope.isAddActive = true;
    $scope.menuClicked = function() {
        $rootScope.isSideMenuOpen= $ionicSideMenuDelegate.isOpen();
    };
    $rootScope.addIconToggle = function(){
        $rootScope.isAddActive = $rootScope.isAddActive?false:true;
    }
})
.controller('SectionCtrl', function($scope, $rootScope, api, $stateParams, $ionicPopup) {
    $rootScope.selected = {};
    $scope.$on('$ionicView.beforeEnter', function() {
        $scope.name = $stateParams.sectionid;
        $rootScope.toles = [];
        $rootScope.districts = [];

        var refresh = $scope.dataset?false:true;
        api.coordinates().then(function(position) {
            $rootScope.coordinates = position.coords;
            $scope.getData(refresh);
        },
        function(err) {
            $scope.getData(refresh);
        });
    });
    $rootScope.updateDistrict = function(){
        //$rootScope.toles = api.location.tole($scope.dataset, $scope.name, $rootScope.selected.district);
        $rootScope.items = api.filter.location.district($scope.dataset, $scope.name, $rootScope.selected.district);
    }
    $rootScope.updateTole = function(){
        $rootScope.items = api.filter.location.tole($rootScope.items, $scope.name,  $rootScope.selected.tole);
    }
    $scope.loadItem = function(item){
        $rootScope.selectedItem = item;
        api.selected.set(item);
        window.location = "#/app/item/"+item.uuid;
    }
    $rootScope.doRefresh = function(refresh){
        if (typeof refresh != 'undefined') {
            refresh = true;
        }
        $scope.getData(refresh);
    }
    $scope.getData = function(refresh){
        api.data(refresh).then(function(data){
            $scope.dataset = api.filter.type(data.content, $scope.name);
            $rootScope.items = $scope.dataset;
            $rootScope.districts = api.location.districts(data.content, $scope.name);
            $scope.$broadcast('scroll.refreshComplete');
            if ($rootScope.coordinates) {
                // Guess the district based on coordinates above and set it
                //$rootScope.selected.district = 'kathmandu';

                if($rootScope.selected.district){
                    $rootScope.updateDistrict();
                }
                if($rootScope.selected.tole){
                    $rootScope.updateTole();
                }
            }
        });
    }
})

.controller('ItemCtrl', function($scope, $stateParams, $rootScope, api, $ionicHistory, $stateParams) {
    $rootScope.selectedItem = api.selected.get();
    $rootScope.selectedItem.channel = $rootScope.selectedItem.channel ? $rootScope.selectedItem.channel : 'supply';
    if ($rootScope.selectedItem.channel == 'supply') {
        $rootScope.selectedItem.activeText = $rootScope.selectedItem.active ? 'available' : 'not available';
    } else {
        $rootScope.selectedItem.activeText = $rootScope.selectedItem.active ? 'needed' : 'not needed';
    }
    if(!$rootScope.selectedItem){
        api.getItem($stateParams.uuid).then(function(data){
            if(data.success){
                $rootScope.selectedItem = data.content;
                api.stat($rootScope.selectedItem).then(function(data){
                    $scope.stat = data;
                });
            }else{
                alert("no data found");
                window.location = "/";
            }
        })
    }else{
        api.stat($rootScope.selectedItem).then(function(data){
            $scope.stat = data;
        });
    }
    $scope.incrStat = function(statKey) {
        api.incrStat($rootScope.selectedItem.uuid, statKey).then(function(data) {
            if (typeof($scope.stat.$$statKey) == 'undefined') {
                $scope.stat.$$statKey = 0;
            }
            var startAt = $scope.stat.$$statKey ? parseInt($scope.stat.$$statKey) : 0;
            $scope.stat.$$statKey = startAt+1;
        },
        function(error) {
            alert('Error updating stat');
        });
    }
    $scope.editItem = function(){
        window.location = "#/app/submit?edit=1";
    }
    $scope.requestDelete = function(){
        api.requestDelete($rootScope.selectedItem).then(function(data){
            if(data){
                $ionicHistory.goBack();
            }else{
                alert("Couldn't delete");
            }
        });
    }
})
.controller('AboutCtrl', function($scope, $stateParams, $rootScope, api) {
    $scope.submitdata = {};
    $scope.signin = function(){
        api.verifyAdmin($scope.submitdata.admincode).then(function(data){
            if(data){
                $rootScope.isloggedin = true;
            }else{
                $rootScope.isloggedin = false;
            }
        });
    }
    $scope.signout = function(){
        $scope.isloggedin = false;
    }

})
.controller('SubmitCtrl', function($scope, api, $stateParams, $rootScope, $ionicHistory, $window) {
    $scope.formTitle = 'New Supply/Resource';
    $scope.submitdata = {
        channel:'supply',
        datasource:'kaha'
    };
    if ($stateParams) {
        if ($stateParams.edit) {
            //$scope.selectedItem = api.selected.get();
            if ($scope.selectedItem) {
                $scope.submitdata = {
                    channel: $scope.selectedItem.channel ? $scope.selectedItem.channel : $scope.submitdata.channel,
                    datasource: $scope.selectedItem.datasource ? $scope.selectedItem.datasource: $scope.submitdata.datasource,
                    uuid: $scope.selectedItem.uuid,
                    supplytype: $scope.selectedItem.type,
                    district: $scope.selectedItem.location.district,
                    tole: $scope.selectedItem.location.tole,
                    title: $scope.selectedItem.description.title,
                    contactname :$scope.selectedItem.description.contactname,
                    contactnumber :$scope.selectedItem.description.contactnumber,
                    description :$scope.selectedItem.description.detail
                };
                console.log('Edit ');
                console.log($scope.selectedItem)
            };
        } else {
            $scope.submitdata.supplytype = $stateParams.type;
        }

        if ($stateParams.channel) {
            $scope.submitdata.channel = $stateParams.channel;
            if ($stateParams.channel == 'need') {
                $scope.formTitle = 'Request Supply/Resource';
            }
        }

        if ($stateParams.datasource) {
            $scope.submitdata.datasource = $stateParams.datasource;
        }
    }
    $scope.districts = api.districts.sort();
    $scope.supplytypes = api.supplytypes.sort();
    $scope.submit = function(){
        var data = {
            datasource: $scope.submitdata.datasource,
            channel: $scope.submitdata.channel,
            type: $scope.submitdata.supplytype,
            location: {
                district: $scope.submitdata.district,
                tole: $scope.submitdata.tole,
            },
            description:{
                title: $scope.submitdata.title,
                detail: $scope.submitdata.description,
                contactname: $scope.submitdata.contactname,
                contactnumber: $scope.submitdata.contactnumber
            },
            active: true
            //description: "Contact Name: "+$scope.submitdata.contactname+" Contact Number: "+$scope.submitdata.contactnumber+" Description: "+$scope.submitdata.description
        };
        if ($scope.submitdata.uuid) {
            data.uuid = $scope.submitdata.uuid;
        }
        if ($rootScope.coordinates) {
            data.coordinates = {
                longitude : $rootScope.coordinates.longitude,
                latitude : $rootScope.coordinates.latitude
            }
        }
        var error = false;
        if(!data.type){
            error = true;
        }
        else if(!data.location.district){
            error = true;
        }
        else if(!data.location.tole){
            error =true;
        }
        else if(!data.description.title){
            error = true;
        }
        else if(!data.description.detail){
            error = true;
        }
        else if(!data.description.contactname){
            error = true;
        }
        else if(!data.description.contactnumber){
            error = true;
        }
        if(!error){
            console.log('Saving Data');
            console.log(data);
            if (data.uuid) {
                api.update(data).then(
                    function(status){
                        alert("Successfully Updated");
                        $ionicHistory.goBack();
                    },
                    function(status) {
                        console.log('Failed to save');
                        console.log(status);
                        alert("We are currently not able to process your request. Please try again later");
                    }
                );
            } else {
                api.submit(data).then(
                    function(status){
                    if(status){
                        alert("Successfully Created");
                        $window.location.reload();
                    }
                    },
                    function(status) {
                        console.log('Failed to save');
                        console.log(status);
                        alert("We are currently not able to process your request. Please try again later");
                    }
                );
            }
        }
        else{
            alert("All fields are required");
        }
    };
}
);
<commit_msg>disabled location api as it was slow in firefox<commit_after>angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $ionicSideMenuDelegate, $timeout, api, $timeout, $rootScope) {
    setTimeout(function() {
        $ionicSideMenuDelegate.toggleLeft();
        $rootScope.isSideMenuOpen = false;
    }, 100);
    $rootScope.isAddActive = true;
    $scope.menuClicked = function() {
        $rootScope.isSideMenuOpen= $ionicSideMenuDelegate.isOpen();
    };
    $rootScope.addIconToggle = function(){
        $rootScope.isAddActive = $rootScope.isAddActive?false:true;
    }
})
.controller('SectionCtrl', function($scope, $rootScope, api, $stateParams, $ionicPopup) {
    $rootScope.selected = {};
    $scope.$on('$ionicView.beforeEnter', function() {
        $scope.name = $stateParams.sectionid;
        $rootScope.toles = [];
        $rootScope.districts = [];

        var refresh = $scope.dataset?false:true;
        /*api.coordinates().then(function(position) {
            $rootScope.coordinates = position.coords;
            $scope.getData(refresh);
        },
        function(err) {
            $scope.getData(refresh);
        });*/
        $scope.getData(refresh);
    });
    $rootScope.updateDistrict = function(){
        //$rootScope.toles = api.location.tole($scope.dataset, $scope.name, $rootScope.selected.district);
        $rootScope.items = api.filter.location.district($scope.dataset, $scope.name, $rootScope.selected.district);
    }
    $rootScope.updateTole = function(){
        $rootScope.items = api.filter.location.tole($rootScope.items, $scope.name,  $rootScope.selected.tole);
    }
    $scope.loadItem = function(item){
        $rootScope.selectedItem = item;
        api.selected.set(item);
        window.location = "#/app/item/"+item.uuid;
    }
    $rootScope.doRefresh = function(refresh){
        if (typeof refresh != 'undefined') {
            refresh = true;
        }
        $scope.getData(refresh);
    }
    $scope.getData = function(refresh){
        api.data(refresh).then(function(data){
            $scope.dataset = api.filter.type(data.content, $scope.name);
            $rootScope.items = $scope.dataset;
            $rootScope.districts = api.location.districts(data.content, $scope.name);
            $scope.$broadcast('scroll.refreshComplete');
            if ($rootScope.coordinates) {
                // Guess the district based on coordinates above and set it
                //$rootScope.selected.district = 'kathmandu';

                if($rootScope.selected.district){
                    $rootScope.updateDistrict();
                }
                if($rootScope.selected.tole){
                    $rootScope.updateTole();
                }
            }
        });
    }
})

.controller('ItemCtrl', function($scope, $stateParams, $rootScope, api, $ionicHistory, $stateParams) {
    $rootScope.selectedItem = api.selected.get();
    $rootScope.selectedItem.channel = $rootScope.selectedItem.channel ? $rootScope.selectedItem.channel : 'supply';
    if ($rootScope.selectedItem.channel == 'supply') {
        $rootScope.selectedItem.activeText = $rootScope.selectedItem.active ? 'available' : 'not available';
    } else {
        $rootScope.selectedItem.activeText = $rootScope.selectedItem.active ? 'needed' : 'not needed';
    }
    if(!$rootScope.selectedItem){
        api.getItem($stateParams.uuid).then(function(data){
            if(data.success){
                $rootScope.selectedItem = data.content;
                api.stat($rootScope.selectedItem).then(function(data){
                    $scope.stat = data;
                });
            }else{
                alert("no data found");
                window.location = "/";
            }
        })
    }else{
        api.stat($rootScope.selectedItem).then(function(data){
            $scope.stat = data;
        });
    }
    $scope.incrStat = function(statKey) {
        api.incrStat($rootScope.selectedItem.uuid, statKey).then(function(data) {
            if (typeof($scope.stat.$$statKey) == 'undefined') {
                $scope.stat.$$statKey = 0;
            }
            var startAt = $scope.stat.$$statKey ? parseInt($scope.stat.$$statKey) : 0;
            $scope.stat.$$statKey = startAt+1;
        },
        function(error) {
            alert('Error updating stat');
        });
    }
    $scope.editItem = function(){
        window.location = "#/app/submit?edit=1";
    }
    $scope.requestDelete = function(){
        api.requestDelete($rootScope.selectedItem).then(function(data){
            if(data){
                $ionicHistory.goBack();
            }else{
                alert("Couldn't delete");
            }
        });
    }
})
.controller('AboutCtrl', function($scope, $stateParams, $rootScope, api) {
    $scope.submitdata = {};
    $scope.signin = function(){
        api.verifyAdmin($scope.submitdata.admincode).then(function(data){
            if(data){
                $rootScope.isloggedin = true;
            }else{
                $rootScope.isloggedin = false;
            }
        });
    }
    $scope.signout = function(){
        $scope.isloggedin = false;
    }

})
.controller('SubmitCtrl', function($scope, api, $stateParams, $rootScope, $ionicHistory, $window) {
    $scope.formTitle = 'New Supply/Resource';
    $scope.submitdata = {
        channel:'supply',
        datasource:'kaha'
    };
    if ($stateParams) {
        if ($stateParams.edit) {
            //$scope.selectedItem = api.selected.get();
            if ($scope.selectedItem) {
                $scope.submitdata = {
                    channel: $scope.selectedItem.channel ? $scope.selectedItem.channel : $scope.submitdata.channel,
                    datasource: $scope.selectedItem.datasource ? $scope.selectedItem.datasource: $scope.submitdata.datasource,
                    uuid: $scope.selectedItem.uuid,
                    supplytype: $scope.selectedItem.type,
                    district: $scope.selectedItem.location.district,
                    tole: $scope.selectedItem.location.tole,
                    title: $scope.selectedItem.description.title,
                    contactname :$scope.selectedItem.description.contactname,
                    contactnumber :$scope.selectedItem.description.contactnumber,
                    description :$scope.selectedItem.description.detail
                };
                console.log('Edit ');
                console.log($scope.selectedItem)
            };
        } else {
            $scope.submitdata.supplytype = $stateParams.type;
        }

        if ($stateParams.channel) {
            $scope.submitdata.channel = $stateParams.channel;
            if ($stateParams.channel == 'need') {
                $scope.formTitle = 'Request Supply/Resource';
            }
        }

        if ($stateParams.datasource) {
            $scope.submitdata.datasource = $stateParams.datasource;
        }
    }
    $scope.districts = api.districts.sort();
    $scope.supplytypes = api.supplytypes.sort();
    $scope.submit = function(){
        var data = {
            datasource: $scope.submitdata.datasource,
            channel: $scope.submitdata.channel,
            type: $scope.submitdata.supplytype,
            location: {
                district: $scope.submitdata.district,
                tole: $scope.submitdata.tole,
            },
            description:{
                title: $scope.submitdata.title,
                detail: $scope.submitdata.description,
                contactname: $scope.submitdata.contactname,
                contactnumber: $scope.submitdata.contactnumber
            },
            active: true
            //description: "Contact Name: "+$scope.submitdata.contactname+" Contact Number: "+$scope.submitdata.contactnumber+" Description: "+$scope.submitdata.description
        };
        if ($scope.submitdata.uuid) {
            data.uuid = $scope.submitdata.uuid;
        }
        if ($rootScope.coordinates) {
            data.coordinates = {
                longitude : $rootScope.coordinates.longitude,
                latitude : $rootScope.coordinates.latitude
            }
        }
        var error = false;
        if(!data.type){
            error = true;
        }
        else if(!data.location.district){
            error = true;
        }
        else if(!data.location.tole){
            error =true;
        }
        else if(!data.description.title){
            error = true;
        }
        else if(!data.description.detail){
            error = true;
        }
        else if(!data.description.contactname){
            error = true;
        }
        else if(!data.description.contactnumber){
            error = true;
        }
        if(!error){
            console.log('Saving Data');
            console.log(data);
            if (data.uuid) {
                api.update(data).then(
                    function(status){
                        alert("Successfully Updated");
                        $ionicHistory.goBack();
                    },
                    function(status) {
                        console.log('Failed to save');
                        console.log(status);
                        alert("We are currently not able to process your request. Please try again later");
                    }
                );
            } else {
                api.submit(data).then(
                    function(status){
                    if(status){
                        alert("Successfully Created");
                        $window.location.reload();
                    }
                    },
                    function(status) {
                        console.log('Failed to save');
                        console.log(status);
                        alert("We are currently not able to process your request. Please try again later");
                    }
                );
            }
        }
        else{
            alert("All fields are required");
        }
    };
}
);
<|endoftext|>


<commit_before>import LocationField from '@opentripplanner/location-field'
import {
  DropdownContainer,
  FormGroup,
  Input,
  InputGroup,
  InputGroupAddon
} from '@opentripplanner/location-field/lib/styled'
import { connect } from 'react-redux'
import styled from 'styled-components'

import { clearLocation, onLocationSelected } from '../../actions/map'
import { addLocationSearch, getCurrentPosition } from '../../actions/location'
import { findNearbyStops } from '../../actions/api'
import { getActiveSearch, getShowUserSettings } from '../../util/state'

const StyledLocationField = styled(LocationField)`
  width: 100%;

  ${DropdownContainer} {
    display: table-cell;
    vertical-align: middle;
    width: 1%;
  }

  ${FormGroup} {
    display: table;
    padding: 6px 12px;
    width: 100%;
  }

  ${Input} {
    display: table-cell;
    padding: 6px 12px;
    width: 100%;
  }

  ${InputGroup} {
    width: 100%;
  }

  ${InputGroupAddon} {
    display: table-cell;
    vertical-align: middle;
    width: 1%;
  }
`

// connect to redux store

const mapStateToProps = (state, ownProps) => {
  const { config, currentQuery, location, transitIndex, user } = state.otp
  const { currentPosition, nearbyStops, sessionSearches } = location
  const activeSearch = getActiveSearch(state.otp)
  const query = activeSearch ? activeSearch.query : currentQuery
  return {
    currentPosition,
    geocoderConfig: config.geocoder,
    location: query[ownProps.locationType],
    nearbyStops,
    sessionSearches,
    showUserSettings: getShowUserSettings(state.otp),
    stopsIndex: transitIndex.stops,
    userLocationsAndRecentPlaces: [...user.locations, ...user.recentPlaces]
  }
}

const mapDispatchToProps = {
  addLocationSearch,
  findNearbyStops,
  getCurrentPosition,
  onLocationSelected,
  clearLocation
}

export default connect(mapStateToProps, mapDispatchToProps)(StyledLocationField)
<commit_msg>refactor(location-field): don't underline or change color options on hover<commit_after>import LocationField from '@opentripplanner/location-field'
import {
  DropdownContainer,
  FormGroup,
  Input,
  InputGroup,
  InputGroupAddon,
  MenuItemA
} from '@opentripplanner/location-field/lib/styled'
import { connect } from 'react-redux'
import styled from 'styled-components'

import { clearLocation, onLocationSelected } from '../../actions/map'
import { addLocationSearch, getCurrentPosition } from '../../actions/location'
import { findNearbyStops } from '../../actions/api'
import { getActiveSearch, getShowUserSettings } from '../../util/state'

const StyledLocationField = styled(LocationField)`
  width: 100%;

  ${DropdownContainer} {
    display: table-cell;
    vertical-align: middle;
    width: 1%;
  }

  ${FormGroup} {
    display: table;
    padding: 6px 12px;
    width: 100%;
  }

  ${Input} {
    display: table-cell;
    padding: 6px 12px;
    width: 100%;
  }

  ${InputGroup} {
    width: 100%;
  }

  ${InputGroupAddon} {
    display: table-cell;
    vertical-align: middle;
    width: 1%;
  }

  ${MenuItemA} {
    text-decoration: none;
  }

  ${MenuItemA}:hover {
    color: #333;
  }
`

// connect to redux store

const mapStateToProps = (state, ownProps) => {
  const { config, currentQuery, location, transitIndex, user } = state.otp
  const { currentPosition, nearbyStops, sessionSearches } = location
  const activeSearch = getActiveSearch(state.otp)
  const query = activeSearch ? activeSearch.query : currentQuery
  return {
    currentPosition,
    geocoderConfig: config.geocoder,
    location: query[ownProps.locationType],
    nearbyStops,
    sessionSearches,
    showUserSettings: getShowUserSettings(state.otp),
    stopsIndex: transitIndex.stops,
    userLocationsAndRecentPlaces: [...user.locations, ...user.recentPlaces]
  }
}

const mapDispatchToProps = {
  addLocationSearch,
  findNearbyStops,
  getCurrentPosition,
  onLocationSelected,
  clearLocation
}

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


<commit_before>// chessdiagram.js : defines Chess Diagram Component

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Board from './board.js';
import Piece from './piece.js';

class Chessdiagram extends Component {
	constructor(props){
		super(props);
		this.state = {
			selectedSquare: null,
			selectedPieceType: null,
			dragX: 0,
			dragY: 0,
			isDragging: false,
			left: 0,
			top: 0,
			width: 0,
			height: 0,
		};
	}

	// Lifecycle events ////

	componentDidMount() {
		this._getClientPos();
		addEventListener('resize', this._onResize.bind(this)); // resize event not provided by React; use DOM version
	}

	componentWillUnmount() {
		removeEventListener('resize', this._onResize.bind(this));
	}

	// event handling ////

	_onResize(evt) { // (DOM event)
		this._getClientPos();
	}

	_onMouseDown(evt) {
		evt.preventDefault();
		let x = evt.clientX - this.state.left;
		let y = evt.clientY - this.state.top;

		this._grab(x,y);
	}

	_onTouchStart(evt) {
		evt.preventDefault();
		let x = evt.touches[0].clientX - this.state.left;
		let y = evt.touches[0].clientY - this.state.top;
		this._grab(x,y);
	}

	_onMouseMove(evt) {
		evt.preventDefault();
		let x = evt.clientX - this.state.left;
		let y = evt.clientY - this.state.top;
		this._move(x,y);
	}

	_onTouchMove(evt) {
		evt.preventDefault();
		let x = evt.touches[0].clientX - this.state.left;
		let y = evt.touches[0].clientY - this.state.top;
		this._move(x,y);
	}

	_onMouseUp(evt) {
		evt.preventDefault();
		let x = evt.clientX - this.state.left;
		let y = evt.clientY - this.state.top;

		this._release(x,y);
	}
	_onTouchEnd(evt) {
		evt.preventDefault();
		let x = evt.touches[0].clientX - this.state.left;
		let y = evt.touches[0].clientY - this.state.top;
		this._release(x,y);
	}

	// coordinate conversion functions ////

	_squareToCoords(square) { // convert a square name (eg 'e4') to coordinates
		if(this.props.flip) {
			let x = this.props.squareSize * (this.props.files - (square.toLowerCase().charCodeAt(0)-97));
			let y = (Number(square.slice(1))-1) * this.props.squareSize;
			return [x,y];
		} else {
			let x = this.props.squareSize * (1 + square.toLowerCase().charCodeAt(0)-97);
			let y = (this.props.ranks-Number(square.slice(1))) * this.props.squareSize;
			return [x,y];
		}
	}

	_fileRankToCoords(file, rank) { // convert zero-based file and rank values to coordinates
		if(this.props.flip) {
			let	x = this.props.squareSize * (this.props.files - file);
			let y = this.props.squareSize * rank;
			return [x,y];
		} else {
			let	x = this.props.squareSize * (1 + file);
			let y = this.props.squareSize * (this.props.ranks - rank -1);
			return [x,y];
		}
	}

	_coordsToSquare (x,y) { // convert coordinates to square name (eg e4)
		if(this.props.flip) {
			let file = String.fromCharCode(97 + this.props.files - x / this.props.squareSize + 1);
			let rank = 1 + Math.floor(y / this.props.squareSize);
			return file + rank;
		} else {
			let file = String.fromCharCode(97 + x / this.props.squareSize - 1);
			let rank = 1 + Math.floor((this.props.ranks * this.props.squareSize - y) / this.props.squareSize);
			return file + rank;
		}
	}

	// private actions

	_grab(x,y) {

		let boardW = this.props.squareSize * (1+this.props.files);
		let boardH = this.props.squareSize * (this.props.ranks);

		if(x < this.props.squareSize || x > boardW || y < 0 || y > boardH) {
			//outside the board ...
			return false;
		}

		let selectedSquare = this._coordsToSquare(x,y);
		let selectedPiece = this._getPieceAtSquare(selectedSquare);

		this.setState({
			selectedSquare: selectedSquare,
			selectedPieceType: selectedPiece ? selectedPiece.pieceType : null,
			dragX: selectedPiece ? selectedPiece.x + this.props.squareSize / 2: this.state.dragX,
			dragY: selectedPiece ? selectedPiece.y + this.props.squareSize / 2: this.state.dragY,
			isDragging: true
		});
	}

	_move(x, y) {

		if(this.state.isDragging) {
			this.setState({dragX: x, dragY: y});
		}
	}

	_release(x,y) {
		this.setState({isDragging: false});
		if(this.props.onMovePiece) {
			let finalSquare = this._coordsToSquare(x,y);
			if(this.state.selectedSquare !== finalSquare) {
				this.props.onMovePiece(this.state.selectedPieceType, this.state.selectedSquare, finalSquare);
			}
		}
	}

	// self-enquiry ////

	_getClientPos() {
		let rect = ReactDOM.findDOMNode(this).getBoundingClientRect();
		this.setState({left: rect.left, top: rect.top, width: rect.width, height: rect.height});
	}

	_getPieces() {
		if(!this.props.pieces)
			return [];

		return this.props.pieces.map((pieceString,i) => {
			let [pieceType, square ] = pieceString.split('@',2);	// split 'piece@square' into pieceType, square
			if(!square)
				return {pieceType: 'invalid', square: 'none', x: 0,y: 0}; // guard against nonsense input
			let [x,y] = this._squareToCoords(square);
			if (isNaN(y))
				return {pieceType: 'invalid', square: 'none', x: 0,y: 0}; // invalid y-coordinate
			return {pieceType: pieceType, square: square.toLowerCase(), x: x, y: y};
		});
	}

	_getPiecesFromFEN() {
		let pieces = [];
		let fields = this.props.fen.split(" ", 6);

		let rank=7, file = 0; // (zero-indexed)
		let x,y,square;
		for (let i = 0; i<fields[0].length; i++) {
			let c = fields[0].charAt(i);
			if(/[KQRBNPkqrbnp]/.test(c)) {
				[x,y] = this._fileRankToCoords(file, rank);
				square = String.fromCharCode(97 + file) + (rank + 1).toString();
				pieces.push({pieceType: c, square: square, x: x, y: y});
				file++;
			} else if (c === "/") {
				rank -= 1;
				file = 0;
			}	else if(/[1-8]/.test(c)) {
				file += Number(c);
			}
		}
		return pieces;
	}

	_getPieceAtSquare(square) {
			let pieces = this.props.fen ? this._getPiecesFromFEN() : this._getPieces();
			return pieces.filter(pieceLocation => pieceLocation.square === square)[0];
	}

	// render function

	render() {
		let pieces = this.props.fen ? this._getPiecesFromFEN() : this._getPieces();

		return (
				<svg
					width={this.props.width === "auto" ? (1 + this.props.files) * this.props.squareSize : this.props.width}
					height={this.props.height === "auto" ? (1 + this.props.ranks) * this.props.squareSize : this.props.height}
					onMouseDown={this._onMouseDown.bind(this)}
					onTouchStart={this._onTouchStart.bind(this)}
					onMouseMove={this._onMouseMove.bind(this)}
					onTouchMove={this._onTouchMove.bind(this)}
					onMouseUp={this._onMouseUp.bind(this)}
					onTouchEnd={this._onTouchEnd.bind(this)}
				>

					<Board
						squareSize={this.props.squareSize} ranks={this.props.ranks} files={this.props.files} selectedSquare={this.state.selectedSquare}
						lightSquareColor={this.props.lightSquareColor} darkSquareColor={this.props.darkSquareColor} flip={!!this.props.flip}
					/>

					{pieces.map((piece, i) =>
						<Piece
							x={this.state.isDragging && piece.square === this.state.selectedSquare ? this.state.dragX - this.props.squareSize / 2 : piece.x}
							y={this.state.isDragging && piece.square === this.state.selectedSquare ? this.state.dragY - this.props.squareSize / 2 : piece.y}
							key={i} pieceType={piece.pieceType} squareSize={this.props.squareSize}
						/>
					)}
				</svg>
		);
	}
}

Chessdiagram.propTypes = {
	squareSize: React.PropTypes.number,
	ranks: React.PropTypes.number,
	files: React.PropTypes.number,
	lightSquareColor: React.PropTypes.string,
	darkSquareColor: React.PropTypes.string,
	flip: React.PropTypes.bool,
}

Chessdiagram.defaultProps = {
	width: 'auto',
	height: 'auto',
	squareSize: 45,
	ranks: 8,
	files: 8,
	lightSquareColor: "#2492FF",
	darkSquareColor:  "#005EBB",
	flip: false,
}

export default Chessdiagram;<commit_msg>cleanup<commit_after>// chessdiagram.js : defines Chess Diagram Component

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Board from './board.js';
import Piece from './piece.js';

class Chessdiagram extends Component {
	constructor(props){
		super(props);
		this.state = {
			selectedSquare: null,
			selectedPieceType: null,
			dragX: 0,
			dragY: 0,
			isDragging: false,
			left: 0,
			top: 0,
			width: 0,
			height: 0,
		};
	}

	// Lifecycle events ////

	componentDidMount() {
		this._getClientPos();
		addEventListener('resize', this._onResize.bind(this)); // resize event not provided by React; use DOM version
	}

	componentWillUnmount() {
		removeEventListener('resize', this._onResize.bind(this));
	}

	// event handling ////

	_onResize(evt) { // (DOM event)
		this._getClientPos();
	}

	_onMouseDown(evt) {
		evt.preventDefault();
		let x = evt.clientX - this.state.left;
		let y = evt.clientY - this.state.top;
		this._grab(x,y);
	}

	_onTouchStart(evt) {
		evt.preventDefault();
		let x = evt.touches[0].clientX - this.state.left;
		let y = evt.touches[0].clientY - this.state.top;
		this._grab(x,y);
	}

	_onMouseMove(evt) {
		evt.preventDefault();
		let x = evt.clientX - this.state.left;
		let y = evt.clientY - this.state.top;
		this._move(x,y);
	}

	_onTouchMove(evt) {
		evt.preventDefault();
		let x = evt.touches[0].clientX - this.state.left;
		let y = evt.touches[0].clientY - this.state.top;
		this._move(x,y);
	}

	_onMouseUp(evt) {
		evt.preventDefault();
		let x = evt.clientX - this.state.left;
		let y = evt.clientY - this.state.top;
		this._release(x,y);
	}
	_onTouchEnd(evt) {
		evt.preventDefault();
		let x = evt.touches[0].clientX - this.state.left;
		let y = evt.touches[0].clientY - this.state.top;
		this._release(x,y);
	}

	// coordinate conversion functions ////

	_squareToCoords(square) { // convert a square name (eg 'e4') to coordinates
		if(this.props.flip) {
			let x = this.props.squareSize * (this.props.files - (square.toLowerCase().charCodeAt(0)-97));
			let y = (Number(square.slice(1))-1) * this.props.squareSize;
			return [x,y];
		} else {
			let x = this.props.squareSize * (1 + square.toLowerCase().charCodeAt(0)-97);
			let y = (this.props.ranks-Number(square.slice(1))) * this.props.squareSize;
			return [x,y];
		}
	}

	_fileRankToCoords(file, rank) { // convert zero-based file and rank values to coordinates
		if(this.props.flip) {
			let	x = this.props.squareSize * (this.props.files - file);
			let y = this.props.squareSize * rank;
			return [x,y];
		} else {
			let	x = this.props.squareSize * (1 + file);
			let y = this.props.squareSize * (this.props.ranks - rank -1);
			return [x,y];
		}
	}

	_coordsToSquare (x,y) { // convert coordinates to square name (eg e4)
		if(this.props.flip) {
			let file = String.fromCharCode(97 + this.props.files - x / this.props.squareSize + 1);
			let rank = 1 + Math.floor(y / this.props.squareSize);
			return file + rank;
		} else {
			let file = String.fromCharCode(97 + x / this.props.squareSize - 1);
			let rank = 1 + Math.floor((this.props.ranks * this.props.squareSize - y) / this.props.squareSize);
			return file + rank;
		}
	}

	// private actions

	_grab(x,y) {

		let boardW = this.props.squareSize * (1+this.props.files);
		let boardH = this.props.squareSize * (this.props.ranks);

		if(x < this.props.squareSize || x > boardW || y < 0 || y > boardH) {
			//outside the board ...
			return false;
		}

		let selectedSquare = this._coordsToSquare(x,y);
		let selectedPiece = this._getPieceAtSquare(selectedSquare);

		this.setState({
			selectedSquare: selectedSquare,
			selectedPieceType: selectedPiece ? selectedPiece.pieceType : null,
			dragX: selectedPiece ? selectedPiece.x + this.props.squareSize / 2: this.state.dragX,
			dragY: selectedPiece ? selectedPiece.y + this.props.squareSize / 2: this.state.dragY,
			isDragging: true
		});
	}

	_move(x, y) {

		if(this.state.isDragging) {
			this.setState({dragX: x, dragY: y});
		}
	}

	_release(x,y) {
		this.setState({isDragging: false});
		if(this.props.onMovePiece) {
			let finalSquare = this._coordsToSquare(x,y);
			if(this.state.selectedSquare !== finalSquare) {
				this.props.onMovePiece(this.state.selectedPieceType, this.state.selectedSquare, finalSquare);
			}
		}
	}

	// self-enquiry ////

	_getClientPos() {
		let rect = ReactDOM.findDOMNode(this).getBoundingClientRect();
		this.setState({left: rect.left, top: rect.top, width: rect.width, height: rect.height});
	}

	_getPieces() {
		if(!this.props.pieces)
			return [];

		return this.props.pieces.map((pieceString,i) => {
			let [pieceType, square ] = pieceString.split('@',2);	// split 'piece@square' into pieceType, square
			if(!square)
				return {pieceType: 'invalid', square: 'none', x: 0,y: 0}; // guard against nonsense input
			let [x,y] = this._squareToCoords(square);
			if (isNaN(y))
				return {pieceType: 'invalid', square: 'none', x: 0,y: 0}; // invalid y-coordinate
			return {pieceType: pieceType, square: square.toLowerCase(), x: x, y: y};
		});
	}

	_getPiecesFromFEN() {
		let pieces = [];
		let fields = this.props.fen.split(" ", 6);

		let rank=7, file = 0; // (zero-indexed)
		let x,y,square;
		for (let i = 0; i<fields[0].length; i++) {
			let c = fields[0].charAt(i);
			if(/[KQRBNPkqrbnp]/.test(c)) {
				[x,y] = this._fileRankToCoords(file, rank);
				square = String.fromCharCode(97 + file) + (rank + 1).toString();
				pieces.push({pieceType: c, square: square, x: x, y: y});
				file++;
			} else if (c === "/") {
				rank -= 1;
				file = 0;
			}	else if(/[1-8]/.test(c)) {
				file += Number(c);
			}
		}
		return pieces;
	}

	_getPieceAtSquare(square) {
			let pieces = this.props.fen ? this._getPiecesFromFEN() : this._getPieces();
			return pieces.filter(pieceLocation => pieceLocation.square === square)[0];
	}

	// render function

	render() {
		let pieces = this.props.fen ? this._getPiecesFromFEN() : this._getPieces();

		return (
				<svg
					width={this.props.width === "auto" ? (1 + this.props.files) * this.props.squareSize : this.props.width}
					height={this.props.height === "auto" ? (1 + this.props.ranks) * this.props.squareSize : this.props.height}
					onMouseDown={this._onMouseDown.bind(this)}
					onTouchStart={this._onTouchStart.bind(this)}
					onMouseMove={this._onMouseMove.bind(this)}
					onTouchMove={this._onTouchMove.bind(this)}
					onMouseUp={this._onMouseUp.bind(this)}
					onTouchEnd={this._onTouchEnd.bind(this)}
				>

					<Board
						squareSize={this.props.squareSize} ranks={this.props.ranks} files={this.props.files} selectedSquare={this.state.selectedSquare}
						lightSquareColor={this.props.lightSquareColor} darkSquareColor={this.props.darkSquareColor} flip={!!this.props.flip}
					/>

					{pieces.map((piece, i) =>
						<Piece
							x={this.state.isDragging && piece.square === this.state.selectedSquare ? this.state.dragX - this.props.squareSize / 2 : piece.x}
							y={this.state.isDragging && piece.square === this.state.selectedSquare ? this.state.dragY - this.props.squareSize / 2 : piece.y}
							key={i} pieceType={piece.pieceType} squareSize={this.props.squareSize}
						/>
					)}
				</svg>
		);
	}
}

Chessdiagram.propTypes = {
	squareSize: React.PropTypes.number,
	ranks: React.PropTypes.number,
	files: React.PropTypes.number,
	lightSquareColor: React.PropTypes.string,
	darkSquareColor: React.PropTypes.string,
	flip: React.PropTypes.bool,
}

Chessdiagram.defaultProps = {
	width: 'auto',
	height: 'auto',
	squareSize: 45,
	ranks: 8,
	files: 8,
	lightSquareColor: "#2492FF",
	darkSquareColor:  "#005EBB",
	flip: false,
}

export default Chessdiagram;<|endoftext|>


<commit_before>'use strict';

var controllers = angular.module('app.controllers', [])

controllers.controller('EventAddCtrl', function ($scope, $http, $modal, $interval, userData) {
  // User Initialization
  userData.getInformation(function(data){
    // Put the user into the current scope
    $scope.currentUser = data;
    // Fix the addedBy null in the event scope
    $scope.event.addedBy = $scope.currentUser['id'];
    // Check if the user is Logged in
    if (userData.isLoggedIn($scope.currentUser)) {
      console.log("User logged in");
    }
    // Get the teams corresponding to a particular user
    userData.onTeams($scope.currentUser, function(teamData){
      $scope.currentUserTeams = teamData;
    });
  });

  // Data Initialization
  $scope.event = { addedBy: null, links: {}, startDateTime: new Date(), endDateTime: new Date()};
  $scope.selectedTeams = {};
  $http.get("https://api.tnyu.org/v1.0/teams?isMeta=false")
    .success(function(data){
      $scope.teams = data.teams;
    })
    .error(function(data, status){
      console.log("Failed to fetch teams from API with error " + status);
    });

  $scope.eventStatuses = [];
  $http.get("https://api.tnyu.org/v1.0/event-statuses")
    .success(function(data) {
      $scope.eventStatuses = data["event-statuses"];
    })
    .error(function(data, status) {
      console.log("Failed to fetch event-statuses from API with error " + status);
    });

  /* Multi-select requires an input model as an array of object literals. An optional
   * output model can also be specified. This writes an array of selected object literals
   * to the current scope.
   */

  $scope.refreshPresenters = function() {
    $scope.presenters = [];
    $http.get("https://api.tnyu.org/v1.0/presenters")
      .success(function(data){
        data.presenters.forEach(function(presenter) {
          $scope.presenters.push({ name: presenter.name, id: presenter.id, ticked: false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshCoorganizers = function() {
    $scope.coorganizers = [];
    $http.get("https://api.tnyu.org/v1.0/organizations")
      .success(function(data) {
        data["organizations"].forEach(function(club) {
          $scope.coorganizers.push({ name: club.name, id: club.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshVenues = function() {
    $scope.venues = [];
    $http.get("https://api.tnyu.org/v1.0/venues")
      .success(function(data){
        data["venues"].forEach(function(venue) {
          $scope.venues.push({ name: venue.name, id: venue.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshGenderRep = function() {
    $scope.genderRep = [];
    $http.get("https://api.tnyu.org/v1.0/people/board")
      .success(function(data){
        data["people"].forEach(function(person) {
          $scope.genderRep.push(
            { name: person.name, id: person.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshPresenters();
  $scope.refreshCoorganizers();
  $scope.refreshVenues();
  $scope.refreshGenderRep();

  $scope.toggleTeam = function(teamid) {
    if($scope.selectedTeams[teamid])
      delete $scope.selectedTeams[teamid];
    else $scope.selectedTeams[teamid] = true;
  }

  $scope.submit = function() {
    $scope.event.startDateTime = $scope.event.startDateTime.toISOString();
    $scope.event.endDateTime = $scope.event.endDateTime.toISOString();

    // Aggregrate all selected teams into our event to be submitted.
    $scope.event.links.teams = [];
    Object.keys($scope.selectedTeams).forEach(function(teamid) {
      $scope.event.links.teams.push(teamid);
    });

    $scope.event.links.presenters = [];
    $scope.selectedPresenters.forEach(function(presenter) {
      $scope.event.links.presenters.push(presenter.id);
    });

    $scope.event.links.coorganizers = [];
    $scope.selectedCoorgs.forEach(function(coorganizer) {
      $scope.event.links.coorganizers.push(coorganizer.id);
    });

    if($scope.selectedVenue[0])
      $scope.event.links.venue = $scope.selectedVenue[0].id;

    if($scope.selectedGenderRep) {
      $scope.event.links.genderRep = $scope.selectedGenderRep;
    }

    console.log($scope.event);

    $http.post('https://api.tnyu.org/v1.0/events',
          {
            "links": {
              "events.venue": {
                "type": "venues"
              },
              "events.coorganizers": {
                "type": "related-clubs"
              },
              "events.presenters": {
                "type": "presenters"
              },
              "events.teams": {
                "type": "teams"
              },
              "events.genderRep": {
                "type": "person"
              },
              "events.status": {
                "type": "event-statuses"
              }
            },
            "events": $scope.event
          },
          { headers: { "Content-Type": "application/vnd.api+json" } })
      .success(function(data) {
        console.log(data);
      })
      .error(function(data, status) {
        $scope.validationErrors = data.errors;
      });
  }

  $scope.addCoorganizer = function addCoorganizer() {
    $modal.open({
      templateUrl: '/partials/coorganizer.html',
      controller: 'AddCoorganizerCtrl'
    }).result.then(function() {
      $scope.refreshCoorganizers();
    });
  };

  $scope.addPresenter = function addPresenter() {
    $modal.open({
      templateUrl: '/partials/presenter.html',
      controller: 'AddPresenterCtrl'
    }).result.then(function() {
      $scope.refreshPresenters();
    });
  };

  $scope.addVenue = function addVenue() {
    $modal.open({
      templateUrl: '/partials/venue.html',
      controller: 'AddVenueCtrl'
    }).result.then(function() { // This fires on modal close (not dismiss)
      $scope.refreshVenues();
    });
  };
});

controllers.controller('AddPresenterCtrl', function($scope, $modalInstance, $http) {
  function serializeData(data) {
    var result = {};
    result.links = {};
    result.links['presenters.currentEmployer'] = {};
    result.links['presenters.currentEmployer'].type = 'organizations';

    result.presenters = {};

    for(var key in data) {
      result.presenters[key] = data[key];
    }

    delete result.presenters.currentEmployer;

    result.presenters.links = {};
    result.presenters.links.currentEmployer = data.currentEmployer;

    console.log('JSON Presenter', result);
    return result;
  }

  $scope.formData = {};

  $scope.companies = [];
  $http.get("https://api.tnyu.org/v1.0/organizations")
    .success(function(data) {
      $scope.companies = data["organizations"];
      console.log(data);
    })
    .error(function(data, status) {
      console.log("Failed to fetch companies from API with error " + status);
    });

  $scope.processForm = function() {
    $http({
      method  : 'POST',
      url     : 'https://api.tnyu.org/v1.0/presenters',
      data    : serializeData($scope.formData),
      headers : { 'Content-Type': 'application/vnd.api+json' }
    })
    .success(function(data) {
      // $scope.formData = {};
      console.log('Submitted form.');
    });
  };

  $scope.submitPresenter = function() {
    $scope.processForm();
    $modalInstance.close();
  };

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

controllers.controller('AddVenueCtrl', function($scope, $modalInstance, $http) {
  $scope.companies = [];
  $http.get("https://api.tnyu.org/v1.0/organizations")
    .success(function(data){
      data.organizations.forEach(function(organization) {
        $scope.companies.push({ name: organization.name, id: organization.id, ticked: false});
      });
    })
    .error(function(data, status){
      console.log(status);
    });

  $scope.showAddCompanyForm = false;

  $scope.addCompany = function() {
    $scope.showAddCompanyForm = true;
  };

  function serializeData(data) {
    var result = {};
    result.links = {};
    result.links['venues.organization'] = {};
    result.links['venues.organization'].type = 'organizations';

    result.venues = {};

    for(var key in data) {
      result.venues[key] = data[key];
    }

    delete result.venues.organization;

    result.venues.links = {};
    result.venues.links.organization = data.organization;

    console.log('JSON Venue', result);
    return result;
  }

  $scope.formData = {};

  $scope.submitVenue = function() {
    $http({
      method  : 'POST',
      url     : 'https://api.tnyu.org/v1.0/venues',
      data    : serializeData($scope.formData),
      headers : { 'Content-Type': 'application/vnd.api+json' }
    })
    .success(function(data) {
      // $scope.formData = {};
      console.log('Submitted form.');
    });
    $modalInstance.close();
  };

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

controllers.controller('AddCoorganizerCtrl', function($scope, $modalInstance, $http) {
  $scope.liaisons = [];
  $http.get("https://api.tnyu.org/v1.0/people")
    .success(function(data){
      data.people.forEach(function(person) {
        $scope.liaisons.push({ name: person.name, id: person.id, ticked: false});
      });
    })
    .error(function(data, status){
      console.log(status);
    });

  function serializeData(data, resource) {
    var result = {};
    result.links = {};
    result.links[resource + '.liaisons'] = {};
    result.links[resource + '.liaisons'].type = 'organizations';

    result[resource] = {};

    for(var key in data) {
      result[resource][key] = data[key];
    }

    delete result[resource].liaisons;

    result[resource].links = {};
    result[resource].links.liaisons = data.liaisons;

    console.log('JSON Coorganizer', result);
    return result;
  }

  $scope.formData = { inNYUEN: false };

  $scope.submitCoorganizer = function() {
    var resource = $scope.isRelatedClub ? 'related-clubs' : 'organizations';

    $http({
      method  : 'POST',
      url     : 'https://api.tnyu.org/v1.0/' + resource,
      data    : serializeData($scope.formData, resource),
      headers : { 'Content-Type': 'application/vnd.api+json' }
    })
    .success(function(data) {
      // $scope.formData = {};
      console.log('Submitted form.');
    });
    $modalInstance.close();
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
});
<commit_msg>Populate host pulldown<commit_after>'use strict';

var controllers = angular.module('app.controllers', [])

controllers.controller('EventAddCtrl', function ($scope, $http, $modal, $interval, userData) {
  // User Initialization
  userData.getInformation(function(data){
    // Put the user into the current scope
    $scope.currentUser = data;
    // Fix the addedBy null in the event scope
    $scope.event.addedBy = $scope.currentUser['id'];
    // Check if the user is Logged in
    if (userData.isLoggedIn($scope.currentUser)) {
      console.log("User logged in");
    }
    // Get the teams corresponding to a particular user
    userData.onTeams($scope.currentUser, function(teamData){
      $scope.currentUserTeams = teamData;
    });
  });

  // Data Initialization
  $scope.event = { addedBy: null, links: {}, startDateTime: new Date(), endDateTime: new Date()};
  $scope.selectedTeams = {};
  $http.get("https://api.tnyu.org/v1.0/teams?isMeta=false")
    .success(function(data){
      $scope.teams = data.teams;
    })
    .error(function(data, status){
      console.log("Failed to fetch teams from API with error " + status);
    });

  $scope.eventStatuses = [];
  $http.get("https://api.tnyu.org/v1.0/event-statuses")
    .success(function(data) {
      $scope.eventStatuses = data["event-statuses"];
    })
    .error(function(data, status) {
      console.log("Failed to fetch event-statuses from API with error " + status);
    });

  /* Multi-select requires an input model as an array of object literals. An optional
   * output model can also be specified. This writes an array of selected object literals
   * to the current scope.
   */

  $scope.refreshPresenters = function() {
    $scope.presenters = [];
    $http.get("https://api.tnyu.org/v1.0/presenters")
      .success(function(data){
        data.presenters.forEach(function(presenter) {
          $scope.presenters.push({ name: presenter.name, id: presenter.id, ticked: false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshCoorganizers = function() {
    $scope.coorganizers = [];
    $http.get("https://api.tnyu.org/v1.0/organizations")
      .success(function(data) {
        data["organizations"].forEach(function(club) {
          $scope.coorganizers.push({ name: club.name, id: club.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshVenues = function() {
    $scope.venues = [];
    $http.get("https://api.tnyu.org/v1.0/venues")
      .success(function(data){
        data["venues"].forEach(function(venue) {
          $scope.venues.push({ name: venue.name, id: venue.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshGenderRep = function() {
    $scope.genderRep = [];
    $http.get("https://api.tnyu.org/v1.0/people/board")
      .success(function(data){
        data["people"].forEach(function(person) {
          $scope.genderRep.push(
            { name: person.name, id: person.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshHost = function() {
    $scope.host = [];
    $http.get("https://api.tnyu.org/v1.0/people/board")
      .success(function(data){
        data["people"].forEach(function(person) {
          $scope.host.push(
            { name: person.name, id: person.id, ticked : false});
        });
      })
      .error(function(data, status){
        console.log(status);
      });
  }

  $scope.refreshPresenters();
  $scope.refreshCoorganizers();
  $scope.refreshVenues();
  $scope.refreshGenderRep();
  $scope.refreshHost();

  $scope.toggleTeam = function(teamid) {
    if($scope.selectedTeams[teamid])
      delete $scope.selectedTeams[teamid];
    else $scope.selectedTeams[teamid] = true;
  }

  $scope.submit = function() {
    $scope.event.startDateTime = $scope.event.startDateTime.toISOString();
    $scope.event.endDateTime = $scope.event.endDateTime.toISOString();

    // Aggregrate all selected teams into our event to be submitted.
    $scope.event.links.teams = [];
    Object.keys($scope.selectedTeams).forEach(function(teamid) {
      $scope.event.links.teams.push(teamid);
    });

    $scope.event.links.presenters = [];
    $scope.selectedPresenters.forEach(function(presenter) {
      $scope.event.links.presenters.push(presenter.id);
    });

    $scope.event.links.coorganizers = [];
    $scope.selectedCoorgs.forEach(function(coorganizer) {
      $scope.event.links.coorganizers.push(coorganizer.id);
    });

    if($scope.selectedVenue[0])
      $scope.event.links.venue = $scope.selectedVenue[0].id;

    if($scope.selectedGenderRep) {
      $scope.event.links.genderRep = $scope.selectedGenderRep;
    }

    console.log($scope.event);

    $http.post('https://api.tnyu.org/v1.0/events',
          {
            "links": {
              "events.venue": {
                "type": "venues"
              },
              "events.coorganizers": {
                "type": "related-clubs"
              },
              "events.presenters": {
                "type": "presenters"
              },
              "events.teams": {
                "type": "teams"
              },
              "events.genderRep": {
                "type": "person"
              },
              "events.status": {
                "type": "event-statuses"
              }
            },
            "events": $scope.event
          },
          { headers: { "Content-Type": "application/vnd.api+json" } })
      .success(function(data) {
        console.log(data);
      })
      .error(function(data, status) {
        $scope.validationErrors = data.errors;
      });
  }

  $scope.addCoorganizer = function addCoorganizer() {
    $modal.open({
      templateUrl: '/partials/coorganizer.html',
      controller: 'AddCoorganizerCtrl'
    }).result.then(function() {
      $scope.refreshCoorganizers();
    });
  };

  $scope.addPresenter = function addPresenter() {
    $modal.open({
      templateUrl: '/partials/presenter.html',
      controller: 'AddPresenterCtrl'
    }).result.then(function() {
      $scope.refreshPresenters();
    });
  };

  $scope.addVenue = function addVenue() {
    $modal.open({
      templateUrl: '/partials/venue.html',
      controller: 'AddVenueCtrl'
    }).result.then(function() { // This fires on modal close (not dismiss)
      $scope.refreshVenues();
    });
  };
});

controllers.controller('AddPresenterCtrl', function($scope, $modalInstance, $http) {
  function serializeData(data) {
    var result = {};
    result.links = {};
    result.links['presenters.currentEmployer'] = {};
    result.links['presenters.currentEmployer'].type = 'organizations';

    result.presenters = {};

    for(var key in data) {
      result.presenters[key] = data[key];
    }

    delete result.presenters.currentEmployer;

    result.presenters.links = {};
    result.presenters.links.currentEmployer = data.currentEmployer;

    console.log('JSON Presenter', result);
    return result;
  }

  $scope.formData = {};

  $scope.companies = [];
  $http.get("https://api.tnyu.org/v1.0/organizations")
    .success(function(data) {
      $scope.companies = data["organizations"];
      console.log(data);
    })
    .error(function(data, status) {
      console.log("Failed to fetch companies from API with error " + status);
    });

  $scope.processForm = function() {
    $http({
      method  : 'POST',
      url     : 'https://api.tnyu.org/v1.0/presenters',
      data    : serializeData($scope.formData),
      headers : { 'Content-Type': 'application/vnd.api+json' }
    })
    .success(function(data) {
      // $scope.formData = {};
      console.log('Submitted form.');
    });
  };

  $scope.submitPresenter = function() {
    $scope.processForm();
    $modalInstance.close();
  };

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

controllers.controller('AddVenueCtrl', function($scope, $modalInstance, $http) {
  $scope.companies = [];
  $http.get("https://api.tnyu.org/v1.0/organizations")
    .success(function(data){
      data.organizations.forEach(function(organization) {
        $scope.companies.push({ name: organization.name, id: organization.id, ticked: false});
      });
    })
    .error(function(data, status){
      console.log(status);
    });

  $scope.showAddCompanyForm = false;

  $scope.addCompany = function() {
    $scope.showAddCompanyForm = true;
  };

  function serializeData(data) {
    var result = {};
    result.links = {};
    result.links['venues.organization'] = {};
    result.links['venues.organization'].type = 'organizations';

    result.venues = {};

    for(var key in data) {
      result.venues[key] = data[key];
    }

    delete result.venues.organization;

    result.venues.links = {};
    result.venues.links.organization = data.organization;

    console.log('JSON Venue', result);
    return result;
  }

  $scope.formData = {};

  $scope.submitVenue = function() {
    $http({
      method  : 'POST',
      url     : 'https://api.tnyu.org/v1.0/venues',
      data    : serializeData($scope.formData),
      headers : { 'Content-Type': 'application/vnd.api+json' }
    })
    .success(function(data) {
      // $scope.formData = {};
      console.log('Submitted form.');
    });
    $modalInstance.close();
  };

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

controllers.controller('AddCoorganizerCtrl', function($scope, $modalInstance, $http) {
  $scope.liaisons = [];
  $http.get("https://api.tnyu.org/v1.0/people")
    .success(function(data){
      data.people.forEach(function(person) {
        $scope.liaisons.push({ name: person.name, id: person.id, ticked: false});
      });
    })
    .error(function(data, status){
      console.log(status);
    });

  function serializeData(data, resource) {
    var result = {};
    result.links = {};
    result.links[resource + '.liaisons'] = {};
    result.links[resource + '.liaisons'].type = 'organizations';

    result[resource] = {};

    for(var key in data) {
      result[resource][key] = data[key];
    }

    delete result[resource].liaisons;

    result[resource].links = {};
    result[resource].links.liaisons = data.liaisons;

    console.log('JSON Coorganizer', result);
    return result;
  }

  $scope.formData = { inNYUEN: false };

  $scope.submitCoorganizer = function() {
    var resource = $scope.isRelatedClub ? 'related-clubs' : 'organizations';

    $http({
      method  : 'POST',
      url     : 'https://api.tnyu.org/v1.0/' + resource,
      data    : serializeData($scope.formData, resource),
      headers : { 'Content-Type': 'application/vnd.api+json' }
    })
    .success(function(data) {
      // $scope.formData = {};
      console.log('Submitted form.');
    });
    $modalInstance.close();
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
});
<|endoftext|>


<commit_before>var corePrograms = corePrograms || [];

corePrograms.push({
    name: "info",
    alias: [],
    man: "This command gives you info about the system.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        stdout.end("UNIJS 0.1");
        _return();
    }
});

corePrograms.push({
    name: "echo",
    alias: [],
    man: "This command behaves like a parrot.\nExecute with no arguments to pipe the input to the output.\nExecute with arguments to print them in the output.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length > 1) {
            for (var i = 1; i < argv.length; i++) {
                stdout.write(argv[i]);
            }
            _return();
        } else {
            stdin.on("data", function (data) { stdout.write(data) });
            stdin.on("end", function () { _return() });
            async();
        }
    }
});

corePrograms.push({
    name: "cat",
    alias: [],
    man: "Shows the content of a file.\n Execute 'cat filename'",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 2) {
            var file = fs.readFile(argv[1]);
            if (file === false) {
                stdout.write("File " + argv[1] + " does not exist.");
                _return();
                return;
            }
            if (file === "Locked") {
                stdout.write("This file is locked by another program.");
                _return();
                return;
            }
            file.on("data", function (data) { stdout.write(data) });
            file.on("end", function () { _return() });
            async();
        } else {
            stdout.write("Incorrect number of arguments.");
            _return();
        }
    }
});

corePrograms.push({
    name: "caesar",
    alias: [],
    man: "Vini, vidi, encodi.\n Must be executed with one argument, 'caesar n' \n It will add n to the unicode code of each character in the input and print it to output.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length != 2) {
            _return();
        } else {
            var n = parseInt(argv[1]);
            stdin.on("data", function (data) { stdout.write(data.split("").map(function (x) { return String.fromCharCode(x.charCodeAt(0) + n) }).join("")) });
            stdin.on("end", function () { _return() });
            async();
        }
    }
});

corePrograms.push({
    name: "cd",
    alias: [],
    man: "Executed with no arguments, prints the current path.\nExecuted with one argument, navigates to that relative path.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 1) {
            stdout.write(fs.getCurrentPath());
        } else if (argv.length == 2) {
            var folders = argv[1].split("/").filter(function (x) { return x != ""; });
            for (var i = 0; i < folders.length; i++) {
                if (folders[i] != "..") {
                    if (fs.navigateChild(folders[i])) {

                    } else {
                        stdout.write("Folder " + folders[i] + " is not a child of " + fs.getCurrentFolder());
                        break;
                    }
                } else {
                    if (fs.navigateUp()) {

                    } else {
                        stdout.write("You are already in the root folder");
                        break;
                    }
                }
            }
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});

corePrograms.push({
    name: "mkdir",
    alias: [],
    man: "Creates a folder in the current folder, the name must be specified in the first parameter.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 2) {
            if (fs.createFolder(argv[1])) {

            } else {
                stdout.write("That folder already exists");
            }
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});

corePrograms.push({
    name: "ls",
    alias: ["dir"],
    man: "Shows the content of the current folder.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 1) {
            fs.getChilds().map(function (x) { return x.name; }).forEach(stdout.write);
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});

corePrograms.push({
    name: "tree",
    alias: [],
    man: "Prints the structure of the current folder as a tree.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        function printTree(level, levelsfinished) {
            var tabs = "", i = 0;
            level = level || 0;
            levelsfinished = levelsfinished || 0;
            while (i++ < level - levelsfinished) {
                tabs += "│";
            }
            i = 0;
            while (i++ < levelsfinished) {
                tabs += " ";
            }
            var childs = fs.getChilds();
            for (i = 0; i < childs.length; i++) {
                if (i != childs.length - 1) {
                    stdout.write(tabs + "├── " + childs[i].name);
                } else {
                    levelsfinished += 1;
                    stdout.write(tabs + "└── " + childs[i].name);
                }
                if (childs[i].type == "folder") {
                    fs.navigateChild(childs[i].name);
                    printTree(level + 1, levelsfinished);
                    fs.navigateUp();
                }
            }
        }
        if (argv.length == 1) {
            stdout.write(fs.getCurrentFolder());
            printTree();
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});<commit_msg>js command<commit_after>var corePrograms = corePrograms || [];

corePrograms.push({
    name: "info",
    alias: [],
    man: "This command gives you info about the system.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        stdout.end("UNIJS 0.1");
        _return();
    }
});

corePrograms.push({
    name: "echo",
    alias: [],
    man: "This command behaves like a parrot.\nExecute with no arguments to pipe the input to the output.\nExecute with arguments to print them in the output.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length > 1) {
            for (var i = 1; i < argv.length; i++) {
                stdout.write(argv[i]);
            }
            _return();
        } else {
            stdin.on("data", function (data) { stdout.write(data) });
            stdin.on("end", function () { _return() });
            async();
        }
    }
});

corePrograms.push({
    name: "js",
    alias: [],
    man: "Executes JavaScript code.\nExecute with no arguments to get a JS command line.\nYou can also execute js followed by the code.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length > 1) {
            argv.shift();
            stdout.write(eval(argv.join(" ")));
            _return();
        } else {
            stdin.on("data", function (data) { stdout.write(eval(data)) });
            stdin.on("end", function () { _return() });
            async();
        }
    }
});

corePrograms.push({
    name: "cat",
    alias: [],
    man: "Shows the content of a file.\n Execute 'cat filename'",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 2) {
            var file = fs.readFile(argv[1]);
            if (file === false) {
                stdout.write("File " + argv[1] + " does not exist.");
                _return();
                return;
            }
            if (file === "Locked") {
                stdout.write("This file is locked by another program.");
                _return();
                return;
            }
            file.on("data", function (data) { stdout.write(data) });
            file.on("end", function () { _return() });
            async();
        } else {
            stdout.write("Incorrect number of arguments.");
            _return();
        }
    }
});

corePrograms.push({
    name: "caesar",
    alias: [],
    man: "Vini, vidi, encodi.\n Must be executed with one argument, 'caesar n' \n It will add n to the unicode code of each character in the input and print it to output.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length != 2) {
            _return();
        } else {
            var n = parseInt(argv[1]);
            stdin.on("data", function (data) { stdout.write(data.split("").map(function (x) { return String.fromCharCode(x.charCodeAt(0) + n) }).join("")) });
            stdin.on("end", function () { _return() });
            async();
        }
    }
});

corePrograms.push({
    name: "cd",
    alias: [],
    man: "Executed with no arguments, prints the current path.\nExecuted with one argument, navigates to that relative path.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 1) {
            stdout.write(fs.getCurrentPath());
        } else if (argv.length == 2) {
            var folders = argv[1].split("/").filter(function (x) { return x != ""; });
            for (var i = 0; i < folders.length; i++) {
                if (folders[i] != "..") {
                    if (fs.navigateChild(folders[i])) {

                    } else {
                        stdout.write("Folder " + folders[i] + " is not a child of " + fs.getCurrentFolder());
                        break;
                    }
                } else {
                    if (fs.navigateUp()) {

                    } else {
                        stdout.write("You are already in the root folder");
                        break;
                    }
                }
            }
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});

corePrograms.push({
    name: "mkdir",
    alias: [],
    man: "Creates a folder in the current folder, the name must be specified in the first parameter.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 2) {
            if (fs.createFolder(argv[1])) {

            } else {
                stdout.write("That folder already exists");
            }
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});

corePrograms.push({
    name: "ls",
    alias: ["dir"],
    man: "Shows the content of the current folder.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        if (argv.length == 1) {
            fs.getChilds().map(function (x) { return x.name; }).forEach(stdout.write);
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});

corePrograms.push({
    name: "tree",
    alias: [],
    man: "Prints the structure of the current folder as a tree.",
    entryPoint: function (argv, stdin, stdout, fs, _return, async) {
        function printTree(level, levelsfinished) {
            var tabs = "", i = 0;
            level = level || 0;
            levelsfinished = levelsfinished || 0;
            while (i++ < level - levelsfinished) {
                tabs += "│";
            }
            i = 0;
            while (i++ < levelsfinished) {
                tabs += " ";
            }
            var childs = fs.getChilds();
            for (i = 0; i < childs.length; i++) {
                if (i != childs.length - 1) {
                    stdout.write(tabs + "├── " + childs[i].name);
                } else {
                    levelsfinished += 1;
                    stdout.write(tabs + "└── " + childs[i].name);
                }
                if (childs[i].type == "folder") {
                    fs.navigateChild(childs[i].name);
                    printTree(level + 1, levelsfinished);
                    fs.navigateUp();
                }
            }
        }
        if (argv.length == 1) {
            stdout.write(fs.getCurrentFolder());
            printTree();
        } else {
            stdout.write("Wrong number of parameters");
        }
        _return();
    }
});<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import {QueryRenderer, graphql} from 'react-relay';

import CommentDecorationsController from '../controllers/comment-decorations-controller';
import ObserveModel from '../views/observe-model';
import RelayEnvironment from '../views/relay-environment';
import {GithubLoginModelPropType} from '../prop-types';
import {UNAUTHENTICATED, INSUFFICIENT} from '../shared/keytar-strategy';
import RelayNetworkLayerManager from '../relay-network-layer-manager';
import {PAGE_SIZE} from '../helpers';
import AggregatedReviewsContainer from './aggregated-reviews-container';
import CommentPositioningContainer from './comment-positioning-container';
import ErrorView from '../views/error-view';

export default class CommentDecorationsContainer extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    localRepository: PropTypes.object.isRequired,
    loginModel: GithubLoginModelPropType.isRequired,
  };

  fetchRepositoryData = repository => {
    return yubikiri({
      branches: repository.getBranches(),
      remotes: repository.getRemotes(),
      currentRemote: repository.getCurrentGitHubRemote(),
      workingDirectoryPath: repository.getWorkingDirectoryPath(),
    });
  }

  fetchToken = (loginModel, repoData) => {
    if (!repoData) {
      return null;
    }

    const endpoint = repoData.currentRemote.getEndpoint();

    if (!endpoint) {
      return null;
    }
    return yubikiri({
      token: loginModel.getToken(endpoint.getLoginAccount()),
    });
  }

  render() {
    return (
      <ObserveModel model={this.props.localRepository} fetchData={this.fetchRepositoryData}>
        {repoData => this.renderWithLocalRepositoryData(repoData)}
      </ObserveModel>
    );
  }

  renderWithLocalRepositoryData(repoData) {
    if (!repoData) {
      return null;
    }

    return (
      <ObserveModel
        model={this.props.loginModel}
        fetchParams={[repoData, this.props.loginModel]}
        fetchData={this.fetchToken}>
        {token => this.renderWithToken(repoData, token)}
      </ObserveModel>
    );
  }

  renderWithToken = (repoData, tokenData) => {
    if (!repoData || !tokenData || tokenData.token === UNAUTHENTICATED || tokenData.token === INSUFFICIENT) {
      // we're not going to prompt users to log in to render decorations for comments
      // just let it go and move on with our lives.
      return null;
    }

    const head = repoData.branches.getHeadBranch();
    if (!head.isPresent) {
      return null;
    }

    const push = head.getPush();
    if (!push.isPresent() || !push.isRemoteTracking()) {
      return null;
    }

    const pushRemote = repoData.remotes.withName(push.getRemoteName());
    if (!pushRemote.isPresent() || !pushRemote.isGithubRepo()) {
      return null;
    }

    const endpoint = repoData.currentRemote.getEndpoint();
    const environment = RelayNetworkLayerManager.getEnvironmentForHost(endpoint, tokenData.token);
    const query = graphql`
      query commentDecorationsContainerQuery(
        $headOwner: String!
        $headName: String!
        $headRef: String!
        $reviewCount: Int!
        $reviewCursor: String
        $threadCount: Int!
        $threadCursor: String
        $commentCount: Int!
        $commentCursor: String
        $first: Int!) {
        repository(owner: $headOwner, name: $headName) {
          ref(qualifiedName: $headRef) {
            associatedPullRequests(
              first: $first, states: [OPEN]) {
              totalCount
              nodes {
                ...commentDecorationsController_results
              }
            }
          }
        }
      }
    `;
    const variables = {
      headOwner: pushRemote.getOwner(),
      headName: pushRemote.getRepo(),
      headRef: push.getRemoteRef(),
      first: 1,
      reviewCount: PAGE_SIZE,
      reviewCursor: null,
      threadCount: PAGE_SIZE,
      threadCursor: null,
      commentCount: PAGE_SIZE,
      commentCursor: null,
    };

    return (
      <RelayEnvironment.Provider value={environment}>
        <QueryRenderer
          environment={environment}
          query={query}
          variables={variables}
          render={queryResult => this.renderWithGraphQLData({
            endpoint,
            owner: variables.headOwner,
            repo: variables.headName,
            ...queryResult,
          }, repoData)}
        />
      </RelayEnvironment.Provider>
    );
  }

  renderWithGraphQLData({error, props, endpoint, owner, repo}, repoData) {
    if (error) {
      // eslint-disable-next-line no-console
      console.warn(`error fetching CommentDecorationsContainer data: ${error}`);
      return null;
    }

    if (!props || !props.repository || !props.repository.ref) {
      // no loading spinner for you
      // just fetch silently behind the scenes like a good little container
      return null;
    }

    return (
      <PullRequestPatchContainer
        owner={this.props.owner}
        repo={this.props.repo}
        number={this.props.number}
        endpoint={this.props.endpoint}
        token={token}>
        {(error, patch) => this.renderWithPatch(error, {token, patch})}
      </PullRequestPatchContainer>
    );

    const associatedPullRequests = props.repository.ref.associatedPullRequests.nodes;

    return (
      <AggregatedReviewsContainer pullRequest={props.repository.pullRequest}>
        {({errors, summaries, commentThreads, refetch}) => {
          if (errors && errors.length > 0) {
            return errors.map((error, i) => (
              <ErrorView
                key={`error-${i}`}
                title="Pagination error"
                descriptions={[error.stack || error.toString()]}
              />
            ));
          }
          const aggregationResult = {summaries, commentThreads, refetch};

          return this.renderWithResult({
            aggregationResult,
            queryProps: props,
            repoData,
            patch,
            refetch,
          });
        }}
      </AggregatedReviewsContainer>
    );
  }

  renderWithResult({aggregationResult, queryProps, repoData, patch}) {
    return (
      <CommentPositioningContainer
        multiFilePatch={patch}
        {...aggregationResult}
        prCommitSha={queryProps.repository.pullRequest.headRefOid}
        localRepository={this.props.repository}>
        {commentTranslations => {
          return (
            <CommentDecorationsController
              endpoint={endpoint}
              owner={owner}
              repo={repo}
              workspace={this.props.workspace}
              localRepository={repoData}
              results={associatedPullRequests}
            />
          );
        }}
      </CommentPositioningContainer>
    );
  }
}
<commit_msg>Revert "WIP Start moving AggregatedReviewsContainer to CommentDecorationsContainer"<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import yubikiri from 'yubikiri';
import {QueryRenderer, graphql} from 'react-relay';

import CommentDecorationsController from '../controllers/comment-decorations-controller';
import ObserveModel from '../views/observe-model';
import RelayEnvironment from '../views/relay-environment';
import {GithubLoginModelPropType} from '../prop-types';
import {UNAUTHENTICATED, INSUFFICIENT} from '../shared/keytar-strategy';
import RelayNetworkLayerManager from '../relay-network-layer-manager';
import {PAGE_SIZE} from '../helpers';

export default class CommentDecorationsContainer extends React.Component {
  static propTypes = {
    workspace: PropTypes.object.isRequired,
    localRepository: PropTypes.object.isRequired,
    loginModel: GithubLoginModelPropType.isRequired,
  };

  fetchRepositoryData = repository => {
    return yubikiri({
      branches: repository.getBranches(),
      remotes: repository.getRemotes(),
      currentRemote: repository.getCurrentGitHubRemote(),
      workingDirectoryPath: repository.getWorkingDirectoryPath(),
    });
  }

  fetchToken = (loginModel, repoData) => {
    if (!repoData) {
      return null;
    }

    const endpoint = repoData.currentRemote.getEndpoint();

    if (!endpoint) {
      return null;
    }
    return yubikiri({
      token: loginModel.getToken(endpoint.getLoginAccount()),
    });
  }

  render() {
    return (
      <ObserveModel model={this.props.localRepository} fetchData={this.fetchRepositoryData}>
        {repoData => this.renderWithRepositoryData(repoData)}
      </ObserveModel>
    );
  }

  renderWithRepositoryData(repoData) {
    if (!repoData) {
      return null;
    }

    return (
      <ObserveModel
        model={this.props.loginModel}
        fetchParams={[repoData, this.props.loginModel]}
        fetchData={this.fetchToken}>
        {token => this.renderWithToken(repoData, token)}
      </ObserveModel>
    );
  }

  renderWithToken = (repoData, tokenData) => {
    if (!repoData || !tokenData || tokenData.token === UNAUTHENTICATED || tokenData.token === INSUFFICIENT) {
      // we're not going to prompt users to log in to render decorations for comments
      // just let it go and move on with our lives.
      return null;
    }

    const head = repoData.branches.getHeadBranch();
    if (!head.isPresent) {
      return null;
    }

    const push = head.getPush();
    if (!push.isPresent() || !push.isRemoteTracking()) {
      return null;
    }

    const pushRemote = repoData.remotes.withName(push.getRemoteName());
    if (!pushRemote.isPresent() || !pushRemote.isGithubRepo()) {
      return null;
    }

    const endpoint = repoData.currentRemote.getEndpoint();
    const environment = RelayNetworkLayerManager.getEnvironmentForHost(endpoint, tokenData.token);
    const query = graphql`
      query commentDecorationsContainerQuery(
        $headOwner: String!
        $headName: String!
        $headRef: String!
        $reviewCount: Int!
        $reviewCursor: String
        $threadCount: Int!
        $threadCursor: String
        $commentCount: Int!
        $commentCursor: String
        $first: Int!) {
        repository(owner: $headOwner, name: $headName) {
          ref(qualifiedName: $headRef) {
            associatedPullRequests(
              first: $first, states: [OPEN]) {
              totalCount
              nodes {
                ...commentDecorationsController_results
              }
            }
          }
        }
      }
    `;
    const variables = {
      headOwner: pushRemote.getOwner(),
      headName: pushRemote.getRepo(),
      headRef: push.getRemoteRef(),
      first: 1,
      reviewCount: PAGE_SIZE,
      reviewCursor: null,
      threadCount: PAGE_SIZE,
      threadCursor: null,
      commentCount: PAGE_SIZE,
      commentCursor: null,
    };

    return (
      <RelayEnvironment.Provider value={environment}>
        <QueryRenderer
          environment={environment}
          query={query}
          variables={variables}
          render={queryResult => this.renderWithGraphQLData({
            endpoint,
            owner: variables.headOwner,
            repo: variables.headName,
            ...queryResult,
          }, repoData)}
        />
      </RelayEnvironment.Provider>
    );
  }

  renderWithGraphQLData({error, props, endpoint, owner, repo}, repoData) {
    if (error) {
      // eslint-disable-next-line no-console
      console.warn(`error fetching CommentDecorationsContainer data: ${error}`);
      return null;
    }

    if (!props || !props.repository || !props.repository.ref) {
      // no loading spinner for you
      // just fetch silently behind the scenes like a good little container
      return null;
    }

    const associatedPullRequests = props.repository.ref.associatedPullRequests.nodes;

    return (
      <CommentDecorationsController
        endpoint={endpoint}
        owner={owner}
        repo={repo}
        workspace={this.props.workspace}
        localRepository={repoData}
        results={associatedPullRequests}
      />
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
	controller('AppCtrl', function ($scope, $http) {

	}).
	controller('landingCtrl', function ($scope, $http) {
		// $scope.twitter = function(){
		// 	$http({
		// 		method: 'GET',
		// 		url: '/auth/twitter'
		// 	}).success(function (data, status, headers, config) {
		// 		$location.path('/auth/twitter');
		// 	}).error(function (data, status, headers, config) {
		// 		$scope.name = 'Error!'
		// 	});
		// }

	}).
	controller('dashboardCtrl', function ($scope, $http, auth) {
	// write Ctrl here
		$scope.getTweets = function() {
			console.log("calling getTweets in front end");
			$http({
				method: 'GET',
				url: '/api/cronjobs',

			}).success(function (data, status, headers, config) {
				//$scope.tweets = data;
				console.log(data);
				//console.log($scope.tweets);
			}).error(function (data, status, headers, config) {
				console.log(data);
			});
		}

		function draw(data){

			console.log("program is calling to draw the map");
			console.log("Date from DB");

			var parsedDates = [];
			for (var i = 0; i < data.length; i++) {

				var db_date = data[i].created_at;
				console.log("db_date: ");
				console.log(db_date);

				var JS_date = new Date(db_date);
				console.log("JS_date");
				console.log(JS_date);

				parsedDates.push(JS_date);

			};

			console.log("length: ");
			console.log(parsedDates.length);

			console.log("parsedDates");

			console.log(parsedDates[3]);
			console.log(parsedDates[4]);

			// create a simple data array that we'll plot with a line (this array represents only the Y values, X will just be the index location)
			// var data = [3, 6, 2, 7, 5, 2, 0, 3, 8, 9, 12, 5, 9, 3, 6, 3, 6, 2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];

			// write Ctrl here
			var m = [80, 200, 80, 200]; // margins
			var w = 1000 - m[1] - m[3]; // width
			var h = 400 - m[0] - m[2]; // height

		// X scale will fit all values from data[] within pixels 0-w
		// var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
		var x = d3.time.scale()
		.domain([new Date(parsedDates[0]), d3.time.day.offset(new Date(parsedDates[parsedDates.length - 1]), 1)])
		// .rangeRound([0, w - m.left - m.right]);

		// Y scale will fit values from 0-10 within pixels h-0 (Note the inverted domain for the y-scale: bigger is up!)
		var y = d3.scale.linear().domain([0, 20]).range([h, 0]);
			// automatically determining max range can work something like this
			// var y = d3.scale.linear().domain([0, d3.max(data)]).range([h, 0]);

		// create a line function that can convert data[] into x and y points
		var line = d3.svg.line()
			// assign the X function to plot our line as we wish
			.x(function(d,i) {
				// verbose logging to show what's actually being done
				console.log('Plotting X value for data point: ' + d + ' using index: ' + i + ' to be at: ' + x(i) + ' using our xScale.');
				// return the X coordinate where we want to plot this datapoint
				return x(i);
			})
			.y(function(d) {
				// verbose logging to show what's actually being done
				console.log('Plotting Y value for data point: ' + d + ' to be at: ' + y(d) + " using our yScale.");
				// return the Y coordinate where we want to plot this datapoint
				return y(d);
			})

			// Add an SVG element with the desired dimensions and margin.
			var graph = d3.select("#graph").append("svg:svg")
			.attr("width", w + m[1] + m[3])
			.attr("height", h + m[0] + m[2])
			.append("svg:g")
			.attr("transform", "translate(" + m[3] + "," + m[0] + ")");

			// create yAxis
			var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(true);
			// Add the x-axis.
			graph.append("svg:g")
			.attr("class", "x axis")
			.attr("transform", "translate(0," + h + ")")
			.call(xAxis);

			// create left yAxis
			var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");
			// Add the y-axis to the left
			graph.append("svg:g")
			.attr("class", "y axis")
			.attr("transform", "translate(-25,0)")
			.call(yAxisLeft);

  			// Add the line by appending an svg:path element with the data line we created above
			// do this AFTER the axes above so that the line is above the tick-lines
			graph.append("svg:path").attr("d", line(data.created_at));

		}

	}).

	controller('profileCtrl', function ($scope, $http, $location, auth) {
		$scope.$watch('user', function(newValue) {
			if($scope.user) {
				console.log('watch change');
				console.log($scope.user);
			}
		});

		$scope.logout = function() {
			$http.get('/api/logout');
		}
	});<commit_msg>cron jobbbbb<commit_after>'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
	controller('AppCtrl', function ($scope, $http) {

	}).
	controller('landingCtrl', function ($scope, $http) {
		// $scope.twitter = function(){
		// 	$http({
		// 		method: 'GET',
		// 		url: '/auth/twitter'
		// 	}).success(function (data, status, headers, config) {
		// 		$location.path('/auth/twitter');
		// 	}).error(function (data, status, headers, config) {
		// 		$scope.name = 'Error!'
		// 	});
		// }

	}).
	controller('dashboardCtrl', function ($scope, $http, auth) {
	// write Ctrl here
		$scope.getTweets = function() {
			console.log("calling getTweets in front end");
			$http({
				method: 'GET',
				url: '/api/cronJob?username=freeslugs',

			}).success(function (data, status, headers, config) {
				//$scope.tweets = data;
				console.log(data);
				//console.log($scope.tweets);
			}).error(function (data, status, headers, config) {
				console.log(data);
			});
		}

		function draw(data){

			console.log("program is calling to draw the map");
			console.log("Date from DB");

			var parsedDates = [];
			for (var i = 0; i < data.length; i++) {

				var db_date = data[i].created_at;
				console.log("db_date: ");
				console.log(db_date);

				var JS_date = new Date(db_date);
				console.log("JS_date");
				console.log(JS_date);

				parsedDates.push(JS_date);

			};

			console.log("length: ");
			console.log(parsedDates.length);

			console.log("parsedDates");

			console.log(parsedDates[3]);
			console.log(parsedDates[4]);

			// create a simple data array that we'll plot with a line (this array represents only the Y values, X will just be the index location)
			// var data = [3, 6, 2, 7, 5, 2, 0, 3, 8, 9, 12, 5, 9, 3, 6, 3, 6, 2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];

			// write Ctrl here
			var m = [80, 200, 80, 200]; // margins
			var w = 1000 - m[1] - m[3]; // width
			var h = 400 - m[0] - m[2]; // height

		// X scale will fit all values from data[] within pixels 0-w
		// var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
		var x = d3.time.scale()
		.domain([new Date(parsedDates[0]), d3.time.day.offset(new Date(parsedDates[parsedDates.length - 1]), 1)])
		// .rangeRound([0, w - m.left - m.right]);

		// Y scale will fit values from 0-10 within pixels h-0 (Note the inverted domain for the y-scale: bigger is up!)
		var y = d3.scale.linear().domain([0, 20]).range([h, 0]);
			// automatically determining max range can work something like this
			// var y = d3.scale.linear().domain([0, d3.max(data)]).range([h, 0]);

		// create a line function that can convert data[] into x and y points
		var line = d3.svg.line()
			// assign the X function to plot our line as we wish
			.x(function(d,i) {
				// verbose logging to show what's actually being done
				console.log('Plotting X value for data point: ' + d + ' using index: ' + i + ' to be at: ' + x(i) + ' using our xScale.');
				// return the X coordinate where we want to plot this datapoint
				return x(i);
			})
			.y(function(d) {
				// verbose logging to show what's actually being done
				console.log('Plotting Y value for data point: ' + d + ' to be at: ' + y(d) + " using our yScale.");
				// return the Y coordinate where we want to plot this datapoint
				return y(d);
			})

			// Add an SVG element with the desired dimensions and margin.
			var graph = d3.select("#graph").append("svg:svg")
			.attr("width", w + m[1] + m[3])
			.attr("height", h + m[0] + m[2])
			.append("svg:g")
			.attr("transform", "translate(" + m[3] + "," + m[0] + ")");

			// create yAxis
			var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(true);
			// Add the x-axis.
			graph.append("svg:g")
			.attr("class", "x axis")
			.attr("transform", "translate(0," + h + ")")
			.call(xAxis);

			// create left yAxis
			var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");
			// Add the y-axis to the left
			graph.append("svg:g")
			.attr("class", "y axis")
			.attr("transform", "translate(-25,0)")
			.call(yAxisLeft);

  			// Add the line by appending an svg:path element with the data line we created above
			// do this AFTER the axes above so that the line is above the tick-lines
			graph.append("svg:path").attr("d", line(data.created_at));

		}

	}).

	controller('profileCtrl', function ($scope, $http, $location, auth) {
		$scope.$watch('user', function(newValue) {
			if($scope.user) {
				console.log('watch change');
				console.log($scope.user);
			}
		});

		$scope.logout = function() {
			$http.get('/api/logout');
		}
	});<|endoftext|>


<commit_before>'use strict';

/* Controllers */

function HangDownListCntr($scope) {
  $scope.apiLive = false;

  $scope.items = [];

  $scope.activeItem = 0;
  $scope.currentUser = null;

  $scope.regressTopic = function(){
    // If the API is not up yet, bail.
    if (!$scope.apiLive) return;

    if ($scope.activeItem > 0) {
      $scope.activeItem--;

      // Submit changes to Google.
      gapi.hangout.data.submitDelta( { activeItem: $scope.activeItem } );
    }
  };

  $scope.advanceTopic = function(){
    // If the API is not up yet, bail.
    if (!$scope.apiLive) return;

    if ($scope.activeItem < $scope.items.length - 1) {
      $scope.activeItem++;

      // Submit changes to Google.
      gapi.hangout.data.submitDelta( { activeItem: $scope.activeItem } );
    }
  };

  $scope.newTopicBuffer = '';
  $scope.addNewTopic = function(){
    // If the user has not been initialized yet, bail.
    if ($scope.currentUser == null) return;

    // If there is no topic set, bail.
    if (!$scope.newTopicBuffer.length) return;

    // Otherwise, add the topic and reset the buffer.
    $scope.items.push({ label: $scope.newTopicBuffer, creator: $scope.currentUser });
    $scope.newTopicBuffer = '';

    // TODO: Create a model to encapsulate the list and notify Google of changes.

    // Submit changes to Google.
    gapi.hangout.data.submitDelta( { topics: JSON.stringify($scope.items) } );
  };

  var updateSharedState = function(StateChangedEvent){
    console.log(StateChangedEvent);

    $scope.items = JSON.parse(StateChangedEvent.state.topics);
    $scope.activeItem = parseInt(StateChangedEvent.state.activeItem);
  };

  // Add a callback to initialize gAPI elements.
  gapi.hangout.onApiReady.add(function(eventObj){
    // TODO: Fetch and set the current app state.
    var initialState = gapi.hangout.data.getState();
    console.log("Initial state...", initialState);

    if (initialState.activeItem == undefined)
      gapi.hangout.data.setValue('activeItem', $scope.activeItem.toString());

    $scope.apiLive = true;
    $scope.currentUser = gapi.hangout.getLocalParticipant().person.displayName;
    gapi.hangout.data.onStateChanged.add(updateSharedState);
  });
}

//HangDownListCntr.$inject = ['$scope'];
<commit_msg>Fix a typo in the previous bug fix.<commit_after>'use strict';

/* Controllers */

function HangDownListCntr($scope) {
  $scope.apiLive = false;

  $scope.items = [];

  $scope.activeItem = 0;
  $scope.currentUser = null;

  $scope.regressTopic = function(){
    // If the API is not up yet, bail.
    if (!$scope.apiLive) return;

    if ($scope.activeItem > 0) {
      $scope.activeItem--;

      // Submit changes to Google.
      gapi.hangout.data.submitDelta( { activeItem: $scope.activeItem.toString() } );
    }
  };

  $scope.advanceTopic = function(){
    // If the API is not up yet, bail.
    if (!$scope.apiLive) return;

    if ($scope.activeItem < $scope.items.length - 1) {
      $scope.activeItem++;

      // Submit changes to Google.
      gapi.hangout.data.submitDelta( { activeItem: $scope.activeItem.toString() } );
    }
  };

  $scope.newTopicBuffer = '';
  $scope.addNewTopic = function(){
    // If the user has not been initialized yet, bail.
    if ($scope.currentUser == null) return;

    // If there is no topic set, bail.
    if (!$scope.newTopicBuffer.length) return;

    // Otherwise, add the topic and reset the buffer.
    $scope.items.push({ label: $scope.newTopicBuffer, creator: $scope.currentUser });
    $scope.newTopicBuffer = '';

    // TODO: Create a model to encapsulate the list and notify Google of changes.

    // Submit changes to Google.
    gapi.hangout.data.submitDelta( { topics: JSON.stringify($scope.items) } );
  };

  var updateSharedState = function(StateChangedEvent){
    console.log(StateChangedEvent);

    $scope.items = JSON.parse(StateChangedEvent.state.topics);
    $scope.activeItem = parseInt(StateChangedEvent.state.activeItem);
  };

  // Add a callback to initialize gAPI elements.
  gapi.hangout.onApiReady.add(function(eventObj){
    // TODO: Fetch and set the current app state.
    var initialState = gapi.hangout.data.getState();
    console.log("Initial state...", initialState);

    if (initialState.activeItem == undefined)
      gapi.hangout.data.setValue('activeItem', $scope.activeItem.toString());

    $scope.apiLive = true;
    $scope.currentUser = gapi.hangout.getLocalParticipant().person.displayName;
    gapi.hangout.data.onStateChanged.add(updateSharedState);
  });
}

//HangDownListCntr.$inject = ['$scope'];
<|endoftext|>